Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 40 ยท Getting Started

asyncio.run, Runner and Program Entry Points

Learn how to start async programs with asyncio.run and asyncio.Runner, structure main(), use top-level await in notebooks, and avoid nested run errors.

Every asyncio program needs a bridge from ordinary synchronous Python into the world of await. That bridge is the entry point. Getting it right once, at the bottom of your script, saves you from a whole family of confusing errors such as "event loop is already running" or "attached to a different loop".

This lesson covers asyncio.run(), the asyncio.Runner class for repeated runs, the conventional main() layout, and the special cases of notebooks, REPLs and this site's editor.

asyncio.run(main())

asyncio.run(coro) does four things in order: creates a fresh event loop, runs your coroutine until it finishes, cancels and cleans up any leftover tasks and async generators, and closes the loop. It returns whatever the coroutine returned.

Python asyncio.run returns the result

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The canonical script layout looks like this:

Python
import asyncio


async def main() -> None:
    ...  # all your application logic


if __name__ == "__main__":
    asyncio.run(main())

The if __name__ == "__main__" guard lets other modules import your functions without starting the loop. Call asyncio.run once. Calling it from inside a coroutine that is already running on a loop fails, because a thread can only run one loop at a time.

What happens to leftover tasks

At the end of asyncio.run, any task you forgot to finish is cancelled. This is a safety net, not a design: a background task should be awaited or explicitly cancelled by your own code. In a normal Python program, this script prints the three lines shown below it, because asyncio.run cancels the sleeper when main() ends:

Python
import asyncio


async def background():
    try:
        print("background started")
        await asyncio.sleep(10)
        print("background finished")      # never printed
    except asyncio.CancelledError:
        print("background was cancelled during shutdown")
        raise


async def main():
    asyncio.create_task(background())
    await asyncio.sleep(0.1)
    print("main is done")


asyncio.run(main())
TEXT
background started
main is done
background was cancelled during shutdown

This is read-only because the editor on this site already owns the event loop, so shutdown cleanup behaves differently here. You can still try the same cancellation by doing it yourself:

Python Cancelling a leftover task yourself

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Explicit cleanup like this is what real programs should do. Cancellation is a normal control-flow tool and gets its own chapter, Timeouts and Cancellation (see the track page).

Exceptions escape asyncio.run

If main() raises, the exception propagates out of asyncio.run like from any function call, after cleanup. Catch it where you can handle it, or let the program crash with a traceback:

Python Handling a failing main

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

asyncio.Runner: several calls, one loop

Each asyncio.run builds and destroys a loop. If you need to run several top-level coroutines on the same loop (for example in tests, or to keep loop-bound objects alive between steps), use asyncio.Runner as a context manager (Python 3.11+):

Python
import asyncio

counter = 0


async def bump():
    global counter
    counter += 1
    await asyncio.sleep(0)
    return counter


with asyncio.Runner() as runner:
    print(runner.run(bump()))
    print(runner.run(bump()))
    print(runner.run(bump()))
    print("same loop:", runner.get_loop() is runner.get_loop())
TEXT
1
2
3
same loop: True

This example is read-only: Runner.run() starts a loop of its own, which is not allowed inside the editor's already-running loop. Copy it into a script on your computer to try it.

Runner also accepts debug=True, which turns on asyncio's debug mode (see debugging later for what it reports).

Notebooks, REPLs and top-level await

Jupyter notebooks, IPython and the python -m asyncio REPL already run an event loop for you. In those places you write await main() directly and must not call asyncio.run, because a loop is already running and Python would raise RuntimeError: asyncio.run() cannot be called from a running event loop.

This site's Python editor is similar: it runs your code inside an async-aware environment, so top-level await works. The following snippet is exactly equivalent to the earlier examples:

Python Top-level await

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In a normal script file on your computer, a bare top-level await is a SyntaxError. Use asyncio.run(main()) there. Every example in this course works with asyncio.run, so you can paste it into a script unchanged.

Rule of thumb: scripts use asyncio.run(main()); notebooks and async REPLs use await main(); frameworks (web servers, bots) start the loop themselves and call your coroutines.

Passing arguments and getting values out

asyncio.run takes a coroutine object, not a function. Call your function with its arguments to build the coroutine:

Python
asyncio.run(main(sys.argv[1:]))      # right: a coroutine object
# asyncio.run(main)                  # wrong: ValueError, a function is not a coroutine

Return values and exceptions come back through asyncio.run itself. To exit with a status code, return an integer from main and pass it on: raise SystemExit(asyncio.run(main())).

Debug mode

Setting the environment variable PYTHONASYNCIODEBUG=1, running python -X dev, or passing debug=True to asyncio.run makes asyncio log slow callbacks, never-awaited coroutines and calls from the wrong thread. It slows programs down, so use it while developing only. The debugging lesson shows what it prints.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does asyncio.run(main()) return?

    asyncio.run runs the coroutine to completion and returns its result, or raises its exception.
  2. 2. Which is correct in a normal .py script file?

    A normal script cannot use top-level await, and asyncio.run needs a coroutine object, so main() must be called.
  3. 3. You call asyncio.run() inside a Jupyter cell and get an error. Why?

    A running loop already exists in notebooks, and a thread cannot run two loops, so use top-level await.
  4. 4. What happens to tasks still running when asyncio.run finishes?

    asyncio.run cancels leftover tasks during shutdown. Finish or cancel your own tasks deliberately.

Summary

  • asyncio.run(main()) is the standard, once-per-program entry point.
  • It creates the loop, runs the coroutine, cancels leftovers and closes the loop.
  • asyncio.Runner lets several top-level coroutines share one loop.
  • Notebooks and async REPLs use await directly; never nest asyncio.run.
  • Pass a coroutine object (main()), not the function.

Next: asyncio versus threads and processes