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

为何asyncio会出现cannot reuse already awaited coroutine错误?

关于cannot reuse already awaited coroutine错误的问题

我无法理解代码中为何会出现cannot reuse already awaited coroutine运行时错误。我在for循环中两次执行以下代码:

loop = asyncio.get_event_loop()
if loop.is_running():
    task = asyncio.ensure_future(self.async_print_stats(curb, iswhite, full))
else:
    loop.run_until_complete(self.async_print_stats(curb, iswhite, full))

两次执行均进入else分支,第一次执行完全正常,但第二次会在async_print_stats函数的唯一代码行触发错误:

async def async_print_stats(self, fen, iswhite, full=True):
    print(await self.async_ret_stats(fen, iswhite, full))
          ^

我并没有像使用gather那样同时等待同一个协程,因此完全无法理解报错的原因。另外尝试创建task时,系统提示循环未运行。


更新:测试代码可正常运行

我编写了一段逻辑类似的测试代码,运行却完全正常,目前无法定位问题根源:

import asyncio 
asyncio.set_event_loop(asyncio.new_event_loop())
loop = asyncio.get_event_loop()
async def tmp():
    await asyncio.sleep(3)
    print('a')
async def func():
    await tmp()
    print('b')

for i in range(2):
    loop.run_until_complete(func())

内容的提问来源于stack exchange,提问作者user2679290

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 08:52:16