DEBUG.WIKI
搬瓦工;先看线路,再选 VPS;CN2 GIA · 对应线路套餐;查看线路 →
RackNerd;$21.99/年 · 1GB KVM
京东云;让 AI 进入真实业务;零售 · 物流 · 客服 · 硬件;查看方案 →

解决 Python 报错 RuntimeError: Event loop is closed 异常

分析 Python 异步编程在程序退出或跨线程调用时报 Event loop is closed 的根因,详解 Windows 事件循环策略与优雅停机清理方案。

问题现象

在使用 asyncio、FastAPI、Playwright、aiohttp 或 Tornado 编写的 Python 应用程序在正常结束或收到终止信号时,控制台抛出刺眼的异常追踪栈:

Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x7f...>
Traceback (most recent call last):
  File "asyncio/proactor_events.py", line 116, in __del__
    self.close()
  File "asyncio/proactor_events.py", line 108, in close
    self._loop.call_soon(self._call_connection_lost, None)
  File "asyncio/base_events.py", line 753, in call_soon
    self._check_closed()
  File "asyncio/base_events.py", line 515, in _check_closed
    raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed

触发根因

  1. 底层异步传输句柄(Transport)垃圾回收晚于事件循环关闭:TCP 连接或管道(如 ProactorTransport)尚未完全析构释放,而主程序已经退出了 asyncio.run() 并销毁了 Event Loop。
  2. 在多线程环境中错误复用非当前线程的事件循环。
  3. Windows 平台特有的默认事件循环实现缺陷:Python 3.8+ 在 Windows 上默认改用 ProactorEventLoop,在特定版本中其底层套接字关闭顺序存在已知设计缺陷。

诊断排查步骤

  1. 检查 Python 运行版本与操作系统:
python --version
  1. 定位报错发生时刻(通常发生在脚本的最后一行执行完毕退出的瞬间)。

解决步骤与操作命令

方案 A:在 Windows 平台切换事件循环策略(最直接)

如果是 Windows 环境下运行脚本,在代码入口最顶部切换为 SelectorEventLoop:

import sys
import asyncio

if sys.platform.startswith('win'):
    asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())

方案 B:规范实现异步客户端与任务的优雅停机(标准做法)

确保在关闭事件循环前,等待所有打开的网络会话(如 aiohttp.ClientSession)与未完成的任务安全退出:

import asyncio
import aiohttp

async def main():
    async with aiohttp.ClientSession() as session:
        async with session.get('https://example.com') as resp:
            print(resp.status)
    # 留出短暂时间让底层 TCP 传输层完成挥手关闭
    await asyncio.sleep(0.25)

if __name__ == '__main__':
    asyncio.run(main())

方案 C:捕获并规避垃圾回收过程中的无害异常

若属于第三方库遗留问题,可通过包装退出处理避免打印无害的析构报错:

# 确保在退出前取消并排空所有孤儿 Task
loop = asyncio.get_event_loop()
pending = asyncio.all_tasks(loop)
for task in pending:
    task.cancel()
loop.run_until_complete(asyncio.gather(*pending, return_exceptions=True))

验证程序退出干脆利落,控制台不再喷出 RuntimeError: Event loop is closed。