python
runtime_error
ai_generated
true
RuntimeError: 此事件循环已在运行
RuntimeError: This event loop is already running
ID: python/asyncio-event-loop-already-running
80%修复率
88%置信度
0证据数
2024-03-12首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.8+ | active | — | — | — |
根因分析
在已经运行的事件循环内部调用了 asyncio.run() 或 loop.run_until_complete(),例如在 Jupyter notebook、异步函数或已持有循环的框架中。
English
Calling asyncio.run() or loop.run_until_complete() from within an already-running event loop, e.g. inside a Jupyter notebook, an async function, or a framework that already owns the loop.
解决方案
-
90% 成功率
import nest_asyncio nest_asyncio.apply() asyncio.run(main())
-
95% 成功率
async def outer(): await main() # instead of asyncio.run(main())
无效尝试
常见但无效的做法:
-
85% 失败
Stopping the loop corrupts the outer framework's scheduling and causes pending tasks to hang.
-
70% 失败
Creates a nested loop that cannot await futures belonging to the outer loop; raises 'attached to a different loop'.