python/cpython · error · RuntimeError

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

Error message

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

What it means

Error "asyncio.run() cannot be called from a running event loop" thrown in python/cpython.

Source

Thrown at Lib/asyncio/runners.py:201

    This function always creates a new event loop and closes it at the end.
    It should be used as a main entry point for asyncio programs, and should
    ideally only be called once.

    The executor is given a timeout duration of 5 minutes to shutdown.
    If the executor hasn't finished within that duration, a warning is
    emitted and the executor is closed.

    Example:

        async def main():
            await asyncio.sleep(1)
            print('hello')

        asyncio.run(main())
    """
    if events._get_running_loop() is not None:
        # fail fast with short traceback
        raise RuntimeError(
            "asyncio.run() cannot be called from a running event loop")

    with Runner(debug=debug, loop_factory=loop_factory) as runner:
        return runner.run(main)


def _cancel_all_tasks(loop):
    to_cancel = tasks.all_tasks(loop)
    if not to_cancel:
        return

    for task in to_cancel:
        task.cancel()

    loop.run_until_complete(tasks.gather(*to_cancel, return_exceptions=True))

    for task in to_cancel:
        if task.cancelled():

View on GitHub (pinned to bc6749cc3b)

Solutions

  1. Do not call asyncio.run() inside async code; await the coroutine directly.
  2. If running in an environment with an existing loop (e.g. Jupyter), use 'await main()' instead of asyncio.run(main()).

When it happens

Trigger: Raised when asyncio.run() is called from within a running event loop.

Common situations: See trigger scenarios.


AI-assisted analysis of python/cpython@bc6749cc3b (2026-08-14). Data as JSON: /api/errors/38c56bd6fe102f9c. Report an issue: GitHub.