python runtime_error ai_generated true

RuntimeError: 此事件循环已在运行

RuntimeError: This event loop is already running

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

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

版本兼容性

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

根因分析

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

English

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

解决方案

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

无效尝试

常见但无效的做法:

  1. 85% 失败

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

  2. 70% 失败

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