debugModerate
Python asyncio event loop already running — cannot use asyncio.run()
Viewed 0 times
asyncio.runevent loopalready runningnest_asyncioJupyterRuntimeError
terminalnodejs
Error Messages
Problem
Calling asyncio.run() inside an environment that already has a running event loop (Jupyter notebooks, some web frameworks, nested async) raises RuntimeError: This event loop is already running.
Solution
(1) In Jupyter notebooks: use await directly in cells (Jupyter runs its own loop) or use nest_asyncio: import nest_asyncio; nest_asyncio.apply(). (2) If you are inside an async function, just await the coroutine directly instead of wrapping in asyncio.run(). (3) In frameworks like FastAPI/Quart that run their own loop, never call asyncio.run() — use await. (4) For sync-to-async bridges, use asyncio.get_event_loop().run_until_complete() or loop.create_task(). (5) Consider restructuring to be fully async top-to-bottom.
Why
asyncio.run() creates a new event loop and runs it. If a loop is already running (Jupyter, web frameworks), you cannot nest another. Python asyncio does not support nested event loops natively.
Revisions (0)
No revisions yet.