jer*_*rry 5 python exec python-3.x python-asyncio
我想在异步函数中调用exec并执行类似下面的代码(这是无效的):
import asyncio
async def f():
await exec('x = 1\n' 'await asyncio.sleep(x)')
Run Code Online (Sandbox Code Playgroud)
更确切地说,我希望能够在exec中运行的代码中等待未来.
怎么能实现这一目标?
注意: F字符串仅在python 3.6+中受支持。对于旧版本,使用
%s,.format()或经典的+级联。
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']()
Run Code Online (Sandbox Code Playgroud)
你的问题是你试图等待None对象exec忽略其代码中的返回值,并始终返回None.如果要执行并等待结果,则应使用eval- eval返回给定表达式的值.
你的代码应如下所示:
import asyncio
async def f():
exec('x = 1')
await eval('asyncio.sleep(x)')
loop = asyncio.get_event_loop()
loop.run_until_complete(f())
loop.close()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2297 次 |
| 最近记录: |