I’d like to call exec in an async function and do something like the following code (which is not valid):
JavaScript
x
5
1
import asyncio
2
3
async def f():
4
await exec('x = 1n' 'await asyncio.sleep(x)')
5
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?
Advertisement
Answer
Note: F-strings are only supported in python 3.6+. For older versions, use
%s
,.format()
or the classic+
concatenation.
JavaScript
1
10
10
1
async def aexec(code):
2
# Make an async function with the code and `exec` it
3
exec(
4
f'async def __ex(): ' +
5
''.join(f'n {l}' for l in code.split('n'))
6
)
7
8
# Get `__ex` from local variables, call it and return the result
9
return await locals()['__ex']()
10
Known issues:
- If you use new lines in a string (triple quotes), it will mess up the formatting.