I'd like to call exec in an async function and do something like the following code (which is not valid):
import asyncio
async def f():
await exec('x = 1\n' 'await asyncio.sleep(x)')
More precisely, I'd like to be able to wait for a future inside the code that runs in exec.
How can this be achieved?
Note: F-strings are only supported in python 3.6+. For older versions, use
%s
,.format()
or the classic+
concatenation.
async def aexec(code):
# Make an async function with the code and `exec` it
exec(
f'async def __ex(): ' +
''.join(f'\n {l}' for l in code.split('\n'))
)
# Get `__ex` from local variables, call it and return the result
return await locals()['__ex']()