解决 Python 异步编程报错 RuntimeError: Event loop is closed
分析 Python asyncio 任务退出时报 Event loop is closed 诱因,详解 Windows 平台 Proactor 事件循环处理。
问题现象
在 Windows 或多线程环境下执行 Python 异步任务退出时抛出未捕获异常:
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x0000...>
Traceback (most recent call last):
File "asyncio/proactor_events.py", line 116, in __del__
RuntimeError: Event loop is closed
触发根因
在 Python 3.8+ 的 Windows 平台上,默认使用 ProactorEventLoop。当主线程或子任务结束时,底层管道传输层在垃圾回收(__del__)时事件循环已经被先行销毁关闭。
解决方案
在 Windows 平台切换为 SelectorEventLoop
在代码入口处显式指定事件循环策略:
import sys
import asyncio
if sys.platform == 'win32':
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
验证方法
再次运行脚本退出,终端干净退出,不再抛出任何 RuntimeError 警告。


