从未等待过Python异步协程

问题描述 投票:0回答:1

我正在使用带有此代码的python 3.8

async def main():
    pass

async def build():
    pass

asyncio.create_task(build())
loop = asyncio.get_event_loop()
asyncio.create_task(main())
pending = asyncio.all_tasks()
loop.run_until_complete(asyncio.gather(*pending))

并出现以下错误

sys:1:RuntimeWarning:从未等待协程'build'

我在这里想念什么?不应该等到所有任务完成才运行?

python python-asyncio coroutine
1个回答
0
投票

由于创建任务时循环未运行,因此asyncio无法将任务附加到它。

可以通过将asyncio.create_task()替换为loop.create_task()来解决。

可以使用asyncio.gather(..., return_exceptions=True)来检索全部错误,因此gather()将引发RuntimeError: no running event loop

© www.soinside.com 2019 - 2024. All rights reserved.