Issue
I want to make keyboard manager with python for the reinforcement learning environemnt. I have some problem with time.sleep() synchronized with environment
This is What I want :
import asyncio
from pynput.keyboard import Key, Controller
class KeyboardManager:
def __init__(self):
self.keyboard = Controller()
def release(self):
self.keyboard.release(Key.left)
self.keyboard.release(Key.right)
async def press_right(self, press_time):
self.keyboard.press(Key.right)
await asyncio.sleep(press_time)
self.keyboard.release(Key.right)
And Use this class with another script
class Env:
def action_right(self):
self.keyboard_manager.press_right(10)
this code is not work.
I guess I have to listen asyncio loop somewhere.
Is there any good Idea?
please help
Solution
Once you have tagged the press_right
function with async
, you convert its return value to a coroutine that has to be awaited somewhere.
You could just propagate the asynchronousity to Env.action_right
by:
class Env:
async def action_right(self):
await self.keyboard_manager.press_right(10)
But at some point wou'll have to wait your async code. For instance you could handle the asyncio event loop yourself with loop.run_until_complete()
:
from asyncio import get_event_loop
class Env:
def __init__(self, ...):
...
self.loop = get_event_loop()
def action_right(self):
loop.run_until_complete(self.keyboard_manager.press_right(10))
If you are using Python 3.7, you could just:
import asyncio
class Env:
def action_right(self):
asyncio.run(self.keyboard_manager.press_right(10))
Anyway, I guess you don't want to wait your async code at that point, because I can't see the point in making KeywordManager.press_right
async in that case.
If your framework is meant to be used with async code, the event loop may be handled by the framework and you just need to propagate your async code (as is the case of aiohttp server for instance). Instead, if you are using the RL library gym
you are not given such feature and I don't think using some async code will be of much help.
Answered By - josoler
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.