python runtime_error ai_generated true

RuntimeError: There is no current event loop in thread 'Thread-1'

ID: python/asyncio-loop-created-in-thread

Also available as: JSON · Markdown · 中文
80%Fix Rate
87%Confidence
0Evidence
2025-03-15First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.7 active
3.8 active
3.9 active
3.10 active

Root Cause

Attempting to use asyncio functions in a thread without a running event loop.

generic

中文

在没有运行事件循环的线程中尝试使用asyncio函数。

Workarounds

  1. 95% success
    loop = asyncio.new_event_loop(); asyncio.set_event_loop(loop); loop.run_until_complete(coro())
  2. 90% success
    future = asyncio.run_coroutine_threadsafe(coro(), loop)

Dead Ends

Common approaches that don't work:

  1. 70% fail

    In Python 3.10+, it may raise an error or return a closed loop.

  2. 50% fail

    asyncio.run() creates a new loop, but it's not accessible from other threads.