python
runtime_error
ai_generated
true
RuntimeError: 没有正在运行的事件循环
RuntimeError: no running event loop
ID: python/no-running-event-loop
80%修复率
89%置信度
0证据数
2024-01-22首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.8 | active | — | — | — |
| 3.9 | active | — | — | — |
| 3.10 | active | — | — | — |
| 3.11 | active | — | — | — |
| 3.12 | active | — | — | — |
根因分析
在没有任何正在运行的循环的同步代码中调用了 asyncio.get_running_loop()(或内部调用它的 API,如 asyncio.create_task)。
English
asyncio.get_running_loop() (or an API that calls it internally, like asyncio.create_task) was invoked from synchronous code outside any running loop.
解决方案
-
95% 成功率
Only call create_task/get_running_loop from inside a coroutine: async def main(): asyncio.create_task(worker()) asyncio.run(main()) -
85% 成功率
From sync code that must schedule work, use asyncio.run_coroutine_threadsafe when you have a loop reference: future = asyncio.run_coroutine_threadsafe(coro(), loop)
-
80% 成功率
In Jupyter/IPython, use `await` directly in the cell, or call nest_asyncio.apply() once at the top of the notebook.
无效尝试
常见但无效的做法:
-
55% 失败
Deprecated since 3.10 and emits DeprecationWarning; in 3.12 it still raises when no loop is set.
-
95% 失败
Makes it worse — guarantees no loop is available.
-
90% 失败
Timing has nothing to do with loop presence.