如何在阻塞样式中运行异步函数?我不允许修改模拟函数f1()的签名,也不能轻松切换到异步def,因此不能使用等待表达式。
async def cc2():
await asyncio.sleep(1)
await asyncio.to_thread(print, "qwerty")
def f1():
t = asyncio.create_task(cc2())
# wait until the task finished before returning
async def main():
f1() # typical call from many places of a program
asyncio.run(main())我尝试了asyncio.get_running_loop().run_until_complete(t),但黑客没有工作,我得到了下一个错误。
回溯(最近一次调用):文件“,第1行,在文件"/usr/lib/python3.9/asyncio/runners.py",第44行,在运行返回loop.run_until_complete(主)文件”/usr/lib/python3.9/asyncio/base_vents.py“,第642行,在run_until_complete返回future.result()文件”,第2行,在主文件"",第3行,在f1文件“/usr/lib/python3.9/asyncio/base_vents.py”第618行中,在run_until_complete self._check_running() File“/usr/lib/python3.9/异步lib/base_vents.py”中的第578行中,在_check_running raise (‘This event循环已经运行’)RuntimeError中:该事件循环已经在运行
。
发布于 2020-11-24 15:08:31
如何在阻塞样式中运行异步函数?
如果您处于同步代码中,可以使用asyncio.run(async_function())调用它。如果您在异步代码中,可以使用await async_function()或asyncio.create_task(async_function()),而后者则将其安排在后台运行。不允许在异步代码中使用asyncio.run() (或run_until_complete,即使是新创建的事件循环对象),因为它会阻塞并停止外部事件循环。
但是,如果您为了测试目的需要它,您总是可以这样做:
# XXX dangerous - could block the current event loop
with concurrent.futures.ThreadPoolExecutor() as pool:
pool.submit(asyncio.run, async_function()).result()https://stackoverflow.com/questions/64988720
复制相似问题