How to Run an Async Main with asyncio.run in Python

Show the canonical entry point for an asyncio program: define an async main, then launch it with asyncio.run.

Easy Python 3.9+ Aug 9, 2026 Concurrency & performance 16 views 0 copies

Python code

11 lines
Python 3.9+
import asyncio


async def main():
    print("Hello from async main")
    await asyncio.sleep(0.1)
    print("Done")


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

Output

stdout
Hello from async main
Done

How it works

asyncio.run() is the standard way to start a top-level coroutine: it creates a new event loop, runs the coroutine until completion, and then closes the loop. The if __name__ == '__main__': guard prevents the async code from running when the module is imported elsewhere. Inside main, await asyncio.sleep(0.1) yields control to the event loop, allowing other tasks to run. Since there are no other tasks here, it simply waits 0.1 seconds before printing 'Done'.

Common mistakes

  • Calling `asyncio.run()` inside a running event loop, which raises an error.
  • Forgetting the `if __name__ == '__main__':` guard and running the async main on import.
  • Using `loop.run_until_complete()` instead of the simpler `asyncio.run()` in modern code.

Variations

  1. Use `await main()` inside an already-running loop, such as in a Jupyter notebook.
  2. Wrap the call with `asyncio.run(main())` inside a `try` block if you need cleanup on error.

Real-world use cases

  • Bootstrap an async web scraper or API client from a CLI script.
  • Run an ETL pipeline that awaits multiple I/O-bound operations concurrently.
  • Start a long-running async worker or service from a `main()` entry point.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Concurrency & performance

Related tutorials and quizzes for this topic.