python runtime_error ai_generated true

RuntimeError: no running event loop

ID: python/asyncio-no-running-event-loop

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.8+ active
3.9+ active
3.10+ active
3.11+ active
3.12+ active

Root Cause

asyncio.get_running_loop() or an await was executed outside an active event loop, typically from synchronous code or a thread that never entered asyncio.run().

generic

中文

在活动事件循环之外调用了 asyncio.get_running_loop() 或执行了 await,通常来自同步代码或未进入 asyncio.run() 的线程。

Workarounds

  1. 95% success
    async def main():
        ...
    
    if __name__ == '__main__':
        asyncio.run(main())
  2. 90% success
    loop = main_loop  # captured earlier
    future = asyncio.run_coroutine_threadsafe(coro(), loop)
    result = future.result(timeout=10)

Dead Ends

Common approaches that don't work:

  1. 70% fail

    In Python 3.10+ this raises DeprecationWarning and in 3.12 raises RuntimeError when no loop exists.

  2. 90% fail

    No loop will spontaneously appear; the coroutine never runs.