Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lernen Running Coroutines with asyncio.run() | The Asyncio Foundation
Python Asyncio in Depth

Running Coroutines with asyncio.run()

Swipe um das Menü anzuzeigen

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.

1234567891011121314
import 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
Note
Note

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.

123456789101112
import 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():

123456789101112
import 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():

1234567891011121314151617181920
import 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.

question mark

Where should asyncio.run() be called in a typical asyncio program?

Wählen Sie die richtige Antwort aus

War alles klar?

Wie können wir es verbessern?

Danke für Ihr Feedback!

Abschnitt 1. Kapitel 5

Fragen Sie AI

expand

Fragen Sie AI

ChatGPT

Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen

Abschnitt 1. Kapitel 5
some-alt