python runtime_error ai_generated true

RuntimeError: 在另一个循环运行时无法运行事件循环

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

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

其他格式: JSON · Markdown 中文 · English
80%修复率
86%置信度
0证据数
2024-04-03首次发现

版本兼容性

版本状态引入弃用备注
3.7+ active — — —

根因分析

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

English

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

generic

解决方案

  1. 95% 成功率
    async def outer():
        result = await inner_coro()  # no nested loop
  2. 82% 成功率
    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()))

无效尝试

常见但无效的做法:

  1. 90% 失败

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

  2. 85% 失败

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