python runtime_error ai_generated true

RuntimeError: 无法从正在运行的事件循环中调用 asyncio.run()

RuntimeError: asyncio.run() cannot be called from a running event loop

ID: python/asyncio-run-called-from-running-loop

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

版本兼容性

版本状态引入弃用备注
3.8 active — — —
3.9 active — — —
3.10 active — — —
3.11 active — — —
3.12 active — — —

根因分析

在已运行的事件循环内部调用 asyncio.run(),例如在 Jupyter 笔记本单元格中或异步函数内部调用。

English

asyncio.run() is invoked from inside an already-running event loop, e.g. calling it in a Jupyter notebook cell or from within an async function.

generic

解决方案

  1. 95% 成功率
    # in a Jupyter cell
    result = await main()  # top-level await, no asyncio.run
  2. 85% 成功率
    import threading, asyncio
    result = {}
    def _run():
        result['v'] = asyncio.run(main())
    t = threading.Thread(target=_run); t.start(); t.join()

无效尝试

常见但无效的做法:

  1. 90% 失败

    Raises the same error because the loop is already running.

  2. 70% 失败

    Works only if you create a fresh loop in that thread; otherwise you get 'no running event loop'.