You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 09:07:02