asyncio.run
- Python course
- Advanced
- Lesson 26/83
- 5 min
Learn the event loop with asyncio.run.
asyncio.run
asyncio.run runs a coroutine from the top level. It opens a new event loop, awaits the coroutine and closes the loop.
import asyncio
async def main():
return 42
asyncio.run(main()) # 42asyncio.run is called once in a program; typically it runs the main() coroutine. Inside the same loop, other coroutines are run with await.
Python 3.7+ standardized this; it replaces the old loop.run_until_complete pattern.
Event loop lifecycle
asyncio.run creates an event loop behind the scenes. The loop runs pending coroutines in turn; when one hits an await point, the loop moves to others.
When the program ends, the loop is closed; remaining resources are cleaned up. Calling asyncio.run multiple times is impractical; better to organize work inside a single main coroutine.
You cannot nest asyncio.run; trying to open a new loop while one is already running raises an error.
Practice Run main with asyncio.run
Start with import asyncio. The function async def main() returns 42. Add the call print(asyncio.run(main())).
Starter code
# import the asyncio module
# declare a coroutine named main; return the value 42
# print the result of main via asyncio.runSample solution
import asyncio
async def main():
return 42
print(asyncio.run(main()))Expected output
42
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 asyncio.run call
import asyncio
async def main():
return 42
print(____(main()))
import asyncio
async def main():
return 42
print(asyncio.run(main()))
Explanation: asyncio.run(main()) runs the main coroutine from the top.
2 Match the asyncio.run pieces
| Term | Meaning |
|---|---|
asyncio.run(main()) |
Top-level call |
main() |
Coroutine object |
event loop |
Running loop |
await |
Waiting point |
3 How often is asyncio.run called in a program?
- Usually once, at the top Correct answer
- Once per coroutine
- Unlimited, nested
- Never, only await is used
Explanation: asyncio.run is usually called once at the top for main().