python
runtime_error
ai_generated
true
RuntimeError: 另一个循环正在运行时无法运行事件循环
RuntimeError: Cannot run the event loop while another loop is running
ID: python/asyncio-loop-already-running-nested
80%修复率
87%置信度
0证据数
2024-06-01首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.8 | active | — | — | — |
| 3.9 | active | — | — | — |
| 3.10 | active | — | — | — |
| 3.11 | active | — | — | — |
| 3.12 | active | — | — | — |
根因分析
在已运行于同一循环的协程内部调用了 loop.run_until_complete(),导致 asyncio 禁止的嵌套循环执行。
English
loop.run_until_complete() was called from inside a coroutine that is already executing on the same loop, causing nested loop execution which asyncio forbids.
解决方案
-
95% 成功率
async def outer(): # WRONG: loop.run_until_complete(inner()) await inner() # correct -
88% 成功率
result = await asyncio.to_thread(sync_blocking_fn, arg1, arg2)
无效尝试
常见但无效的做法:
-
90% 失败
get_event_loop returns the running loop; run_until_complete still raises.
-
85% 失败
The loop is still running; a yield point does not allow re-entrant run_until_complete.