python
runtime_error
ai_generated
true
RuntimeError: 无法复用已经 await 过的协程
RuntimeError: cannot reuse already awaited coroutine
ID: python/asyncio-cannot-run-coroutine-already-running
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.
解决方案
-
95% 成功率
async def fetch(): ... for _ in range(3): await fetch() # new coroutine each iteration -
85% 成功率
task = asyncio.ensure_future(fetch()) await task await task # Tasks can be awaited multiple times
-
88% 成功率
from functools import partial make = partial(fetch, url) await make() await make()
无效尝试
常见但无效的做法:
-
95% 失败
The coroutine frame is exhausted; send raises StopIteration immediately.
-
90% 失败
Shallow copy shares the same frame; awaiting the copy raises the same error.