using exec() inside uasyncio task #11800
Replies: 3 comments 1 reply
-
asyncio.sleep() needs await. But even with that, exec("await uasyncio.sleep(1)") will not work because it throws a Syntax Error "await outside function" error. CPython also does. |
Beta Was this translation helpful? Give feedback.
-
I'm not sure if it's possible to execute dynamically generated Will this work (in CPython or MP)? I really don't know... |
Beta Was this translation helpful? Give feedback.
-
[EDIT] Removed stupid bug. code = '''
import uasyncio as asyncio
async def test():
for n in range(10):
await asyncio.sleep_ms(500)
print(n)
async def run():
print("Run started")
tsk = loop.create_task(test())
print("Created task")
await tsk
done.set()
asyncio.create_task(run())
'''
import uasyncio as asyncio
async def twiddle():
while True:
print("Waiting")
await asyncio.sleep_ms(600)
async def main():
evt = asyncio.Event()
globs = {'done': evt, 'loop': asyncio.get_event_loop()}
exec(code, globs)
tw = asyncio.create_task(twiddle())
await evt.wait()
tw.cancel()
print("Done")
asyncio.run(main()) This script works under the Unix build. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Hello,
I am struggeling a little bit with the exec command calling inside of a task.
Since my code is very large, I have reduced it here to the core of my problem:
The
mainLoop
was started withuasyncio.create_task(mainLoop())
, so it is running as a task.In this code, the exec call returns immediately without waiting any time.
What I need is: exec should return if the given time is elapsed (same behavior, like i directly call
await uasyncio.sleep(1)
without exec)I tried it also with:
I need to call the code here with exec. Using eval is not possible at this point because in the original code there is a function call inside exec that does some additional function calls.
Does anyone have an idea how to get a sleep function by using an exec() call, which does not block all running tasks and only returns after time has elapsed?
Beta Was this translation helpful? Give feedback.
All reactions