python runtime_error ai_generated true

RuntimeError: 无法复用已经 await 过的协程

RuntimeError: cannot reuse already awaited coroutine

ID: python/asyncio-cannot-run-coroutine-already-running

其他格式: JSON · Markdown 中文 · English
80%修复率
90%置信度
0证据数
2024-02-14首次发现

版本兼容性

版本状态引入弃用备注
3.8 active — — —
3.9 active — — —
3.10 active — — —
3.11 active — — —
3.12 active — — —

根因分析

同一个协程对象被 await 了多次。Python 中的协程是一次性的;在重试循环中复用同一个协程对象或将其缓存到变量后重复 await 都会触发此错误。

English

A coroutine object was awaited more than once. Coroutines in Python are single-shot; reusing the same coroutine object (e.g., in a retry loop or cached in a variable) raises this error.

generic

解决方案

  1. 95% 成功率
    async def fetch(): ...
    for _ in range(3):
        await fetch()   # new coroutine each iteration
  2. 85% 成功率
    task = asyncio.ensure_future(fetch())
    await task
    await task   # Tasks can be awaited multiple times
  3. 88% 成功率
    from functools import partial
    make = partial(fetch, url)
    await make()
    await make()

无效尝试

常见但无效的做法:

  1. 95% 失败

    The coroutine frame is exhausted; send raises StopIteration immediately.

  2. 90% 失败

    Shallow copy shares the same frame; awaiting the copy raises the same error.