python runtime_error ai_generated true

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

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

Also available as: JSON · Markdown · 中文
80%Fix Rate
89%Confidence
0Evidence
2024-01-15First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.8+ active
3.9+ active
3.10+ active
3.11+ active
3.12+ active

Root Cause

asyncio.run() was called from inside an already-running loop, common in Jupyter notebooks, IPython, or async frameworks.

generic

中文

在已运行的事件循环内部调用了 asyncio.run(),常见于 Jupyter notebook、IPython 或异步框架中。

Workarounds

  1. 97% success
    # In a Jupyter cell:
    await main()
    # Do NOT use asyncio.run() in Jupyter
  2. 95% success
    task = asyncio.create_task(main())
    await task

Dead Ends

Common approaches that don't work:

  1. 55% fail

    Nest_asyncio patches the loop but breaks some libraries and can deadlock; often produces subtle bugs.

  2. 90% fail

    Raises the same error because the loop is already running.