What is the basic pattern for running an async function using asyncio.run()?
Short answer
Define your entry-point coroutine with 'async def', then call asyncio.run(coroutine()) from regular (synchronous) code — this creates a new event loop, runs the coroutine to completion, and closes the loop, serving as the standard top-level entry point for an asyncio program.
Advertisement
AModel answer
Define your entry-point coroutine with 'async def', then call asyncio.run(coroutine()) from regular (synchronous) code — this creates a new event loop, runs the coroutine to completion, and closes the loop, serving as the standard top-level entry point for an asyncio program.
import asyncio
async def main():
print("Start")
await asyncio.sleep(1)
print("End")
asyncio.run(main())Real-world example
Running an async web scraper or API client script as the top-level entry point of a standalone Python program.
Likely follow-ups
- Why should asyncio.run() typically only be called ONCE, at the very top level of a program?
Related topics