python runtime_error ai_generated true

RuntimeError: Event loop is closed

ID: python/asyncio-event-loop-closed

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2024-02-14First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.8 active
3.9 active
3.10 active
3.11 active
3.12 active

Root Cause

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.

generic

中文

事件循环在所有挂起任务完成之前被关闭,通常是因为多次调用 asyncio.run() 或 Windows 上 ProactorEventLoop 在清理期间过早关闭。

Workarounds

  1. 90% success
    Use a single asyncio.run() entry point and await all tasks before exiting:
    
    async def main():
        await asyncio.gather(*tasks)
    
    asyncio.run(main())
  2. 75% success
    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())

Dead Ends

Common approaches that don't work:

  1. 70% fail

    Silences the symptom but leaves coroutines unfinished and connections unclosed, causing resource leaks.

  2. 85% fail

    A closed loop cannot be reopened; you get the same RuntimeError or an uninitialized loop.