如何在Google Colab中使用asyncio获取协程对象的执行结果?
在Google Colab中运行Asyncio异步代码的解决方案
你遇到的问题是因为Google Colab环境已经启动了一个事件循环,所以不能用asyncio.run()(它会尝试创建新的事件循环),而直接调用main()只是生成协程对象,不会执行。以下是两种可行的解决方法:
方法1:使用Top-level Await
Colab的交互式环境支持直接在顶层使用await来执行协程,把代码最后一行替换为:
await main()
完整代码示例:
import asyncio async def main(): task = asyncio.create_task(other_function()) print("1") await asyncio.sleep(1) print("2") await task async def other_function(): print('A') await asyncio.sleep(1) print('B') await main()
方法2:利用现有事件循环执行
获取Colab当前运行的事件循环,调用run_until_complete方法执行协程:
import asyncio async def main(): task = asyncio.create_task(other_function()) print("1") await asyncio.sleep(1) print("2") await task async def other_function(): print('A') await asyncio.sleep(1) print('B') loop = asyncio.get_running_loop() loop.run_until_complete(main())
两种方法运行后都会得到你预期的输出:
1 A 2 B
内容的提问来源于stack exchange,提问作者Carl Lennartson
相关产品推荐
相关产品推荐

