python
runtime_error
ai_generated
true
RuntimeError: asyncio.run() cannot be called from a running event loop
ID: python/asyncio-run-called-from-running-loop
80%Fix Rate
90%Confidence
0Evidence
2024-01-25First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.8 | active | — | — | — |
| 3.9 | active | — | — | — |
| 3.10 | active | — | — | — |
| 3.11 | active | — | — | — |
| 3.12 | active | — | — | — |
Root Cause
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中文
在已运行的事件循环内部调用 asyncio.run(),例如在 Jupyter 笔记本单元格中或异步函数内部调用。
Workarounds
-
95% success
# in a Jupyter cell result = await main() # top-level await, no asyncio.run
-
85% success
import threading, asyncio result = {} def _run(): result['v'] = asyncio.run(main()) t = threading.Thread(target=_run); t.start(); t.join()
Dead Ends
Common approaches that don't work:
-
90% fail
Raises the same error because the loop is already running.
-
70% fail
Works only if you create a fresh loop in that thread; otherwise you get 'no running event loop'.