python runtime_error ai_generated true

RuntimeError: Cannot run the event loop while another loop is running

ID: python/asyncio-cannot-reenter-running-loop

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.7+ active — — —

Root Cause

Calling loop.run_until_complete() or asyncio.run() from within a coroutine that is already executing on a running loop.

generic

中文

在已在运行循环上执行的协程中调用 loop.run_until_complete() 或 asyncio.run()。

Workarounds

  1. 95% success
    async def outer():
        result = await inner_coro()  # no nested loop
  2. 82% success
    import asyncio, concurrent.futures
    loop = asyncio.get_running_loop()
    with concurrent.futures.ThreadPoolExecutor() as pool:
        result = await loop.run_in_executor(pool, lambda: asyncio.run(inner_coro()))

Dead Ends

Common approaches that don't work:

  1. 90% fail

    asyncio.run() refuses when a loop is already running and raises the same error.

  2. 85% fail

    Same restriction: you cannot nest loop runners on the same thread.