python
runtime_error
ai_generated
true
RuntimeError: 事件循环已关闭
RuntimeError: Event loop is closed
ID: python/asyncio-event-loop-closed
80%修复率
88%置信度
0证据数
2024-02-14首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.8 | active | — | — | — |
| 3.9 | active | — | — | — |
| 3.10 | active | — | — | — |
| 3.11 | active | — | — | — |
| 3.12 | active | — | — | — |
根因分析
事件循环在所有挂起任务完成之前被关闭,通常是因为多次调用 asyncio.run() 或 Windows 上 ProactorEventLoop 在清理期间过早关闭。
English
The event loop was closed before all pending tasks completed, often caused by calling asyncio.run() multiple times or by the ProactorEventLoop on Windows closing prematurely during cleanup.
解决方案
-
90% 成功率
Use a single asyncio.run() entry point and await all tasks before exiting: async def main(): await asyncio.gather(*tasks) asyncio.run(main()) -
75% 成功率
On Windows, set the event loop policy before creating the loop: import asyncio, sys if sys.platform == 'win32': asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
无效尝试
常见但无效的做法:
-
70% 失败
Silences the symptom but leaves coroutines unfinished and connections unclosed, causing resource leaks.
-
85% 失败
A closed loop cannot be reopened; you get the same RuntimeError or an uninitialized loop.