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.
Python code
11 linesimport asyncio
async def main():
print("Hello from async main")
await asyncio.sleep(0.1)
print("Done")
if __name__ == "__main__":
asyncio.run(main())
Output
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
- Use `await main()` inside an already-running loop, such as in a Jupyter notebook.
- 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
More from Concurrency & performance
- Benchmark list.append vs deque.append in Python medium
- Build a Python Performance Profiler That Generates Readable Reports medium
- Graceful Shutdown Executor Context Manager in Python medium
- How to Build a Producer-Consumer Pattern with asyncio.Queue in Python medium
- How to Cancel an asyncio Task with Graceful Cleanup in Python medium
- How to Convert Data in Parallel with ThreadPoolExecutor in Python easy
Keep learning
Related tutorials and quizzes for this topic.