python runtime_error ai_generated true

运行时错误:事件循环已关闭

RuntimeError: Event loop is closed

ID: python/asyncio-event-loop-closed

其他格式: JSON · Markdown 中文 · English
80%修复率
85%置信度
0证据数
2024-02-15首次发现

版本兼容性

版本状态引入弃用备注
3.8 active
3.9 active
3.10 active
3.11 active

根因分析

在事件循环已被显式关闭后尝试使用它,通常是因为过早调用 loop.close() 或在关闭后重用循环。

English

Attempting to use an asyncio event loop after it has been explicitly closed, often due to calling loop.close() prematurely or reusing a loop after shutdown.

generic

解决方案

  1. 95% 成功率 Use asyncio.run() for top-level entry point to avoid manual loop management
    async def main(): await some_coroutine(); asyncio.run(main())
  2. 85% 成功率 Check if loop is closed before using it, and create a new one if needed
    if loop.is_closed(): loop = asyncio.new_event_loop(); asyncio.set_event_loop(loop)

无效尝试

常见但无效的做法:

  1. Recreating the loop with asyncio.new_event_loop() without setting it as current 70% 失败

    The new loop is not set as the current loop, so asyncio.get_event_loop() still returns a closed loop.

  2. Ignoring the error and continuing execution 90% 失败

    The closed loop cannot process coroutines, leading to hangs or crashes later.

  3. Using loop.run_forever() after loop.close() 100% 失败

    A closed loop cannot be restarted; run_forever() raises RuntimeError.