Running Coroutines with asyncio.run()
Desliza para mostrar el menú
A coroutine defined with async def does nothing on its own. To actually execute it, you need an entry point – a way to start the event loop and hand it the coroutine. That entry point is asyncio.run().
What asyncio.run() Does
asyncio.run(coroutine) does three things in sequence:
- creates a new event loop;
- runs the given coroutine until it completes;
- closes the loop and cleans up resources.
It is the standard way to run the top-level coroutine in any asyncio program.
1234567891011121314import asyncio import httpx import nest_asyncio nest_asyncio.apply() # Fetching the number of posts from a public API async def count_posts(): async with httpx.AsyncClient() as client: response = await client.get("https://jsonplaceholder.typicode.com/posts") posts = response.json() print(f"Total posts: {len(posts)}") asyncio.run(count_posts()) # Starting the event loop
In a regular .py script there is no pre-existing event loop, so asyncio.run() works without any patches. The import nest_asyncio and nest_asyncio.apply() lines that appear throughout this course are only needed on this platform. You can safely remove them when running code locally.
One Entry Point Per Program
asyncio.run() is designed to be called once – at the top level of your script. Calling it from inside a running event loop raises a RuntimeError.
123456789101112import asyncio import nest_asyncio nest_asyncio.apply() async def inner(): print("Inner coroutine") async def outer(): asyncio.run(inner()) # RuntimeError: cannot be called from a running event loop asyncio.run(outer())
To call one coroutine from another, use await – not asyncio.run():
123456789101112import asyncio import nest_asyncio nest_asyncio.apply() async def inner(): print("Inner coroutine") async def outer(): await inner() # Correct way to call a coroutine from another coroutine asyncio.run(outer())
Structuring an Asyncio Program
The standard pattern for any asyncio script is to define a main() coroutine as the program's entry point and pass it to asyncio.run():
1234567891011121314151617181920import asyncio import httpx import nest_asyncio nest_asyncio.apply() # Fetching titles of the first three posts async def fetch_title(client, post_id): url = f"https://jsonplaceholder.typicode.com/posts/{post_id}" response = await client.get(url) data = response.json() return data["title"] async def main(): async with httpx.AsyncClient() as client: for post_id in range(1, 4): title = await fetch_title(client, post_id) print(f"Post {post_id}: {title}") asyncio.run(main())
All async logic lives inside main(). asyncio.run() only appears once, at the bottom of the file.
¡Gracias por tus comentarios!
Pregunte a AI
Pregunte a AI
Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla