python runtime_error ai_generated true

RuntimeError: This event loop is already running

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

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.8+ active — — —

Root Cause

Calling asyncio.run() or loop.run_until_complete() from within an already-running event loop, e.g. inside a Jupyter notebook, an async function, or a framework that already owns the loop.

generic

中文

在已经运行的事件循环内部调用了 asyncio.run() 或 loop.run_until_complete(),例如在 Jupyter notebook、异步函数或已持有循环的框架中。

Workarounds

  1. 90% success
    import nest_asyncio
    nest_asyncio.apply()
    asyncio.run(main())
  2. 95% success
    async def outer():
        await main()  # instead of asyncio.run(main())

Dead Ends

Common approaches that don't work:

  1. 85% fail

    Stopping the loop corrupts the outer framework's scheduling and causes pending tasks to hang.

  2. 70% fail

    Creates a nested loop that cannot await futures belonging to the outer loop; raises 'attached to a different loop'.