Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python asyncio Module

Python asyncio Module

asyncio is a module in the Python standard library for writing asynchronous I/O code.

asyncio provides an efficient way to handle concurrent tasks, especially suited to I/O-bound operations such as network requests and file reads and writes.

By using asyncio, you can handle multiple tasks concurrently in a single thread without using multiple threads or processes.

Why do we need asyncio?

In traditional synchronous programming, when a task has to wait for an I/O operation (such as a network request) to complete, the program blocks until the operation finishes. This makes the program inefficient, especially when many I/O operations must be handled.

asyncio By introducing an asynchronous programming model, a program can keep executing other tasks while waiting for I/O operations, improving concurrency and efficiency.

Imagine you are running a restaurant:

  • Synchronous mode (ordinary functions): You have only one chef. Customer A orders a steak and the chef starts frying it (which takes 5 minutes). During those 5 minutes the chef is fully occupied and can do nothing else - even if customer B only wants a glass of water, they have to wait.
  • Asynchronous mode (asyncio): You have several chefs (actually still one, but a very smart one). After the chef starts frying customer A's steak and realizes it needs waiting, he immediately marks it as waiting and turns to pour water for customer B. When he comes back he checks whether the steak is almost done; if not, he can go handle customer C's order. This way, during the time spent waiting for I/O (frying a steak, network requests, reading and writing files), the chef (CPU) keeps working efficiently.
  • asyncio is the standard library Python provides for this smart working pattern. It lets you write single-threaded concurrent code, especially suited to I/O-bound scenarios such as web crawlers, web servers and microservices.

    Its core is the event loop, coroutines and tasks.


    Core concepts of asyncio

    1. Coroutine

    A coroutine is asyncio 's core concepts. It is a special function that can pause during execution and resume later. Coroutines are defined with the async def keyword and pause execution with the await keyword, waiting for an asynchronous operation to complete.

    Example

    import

    asyncio

    async

    def

    say_hello

    (

    )

    :

       

    print

    (

    "Hello"

    )

        await asyncio.

    sleep

    (

    1

    )

       

    print

    (

    "World"

    )

    2. Event loop

    The event loop is asyncio 's core component and is responsible for scheduling and executing coroutines. It continually checks whether any task needs to run and invokes the corresponding callback when a task completes.

    Example

    async

    def

    main

    (

    )

    :

        await say_hello

    (

    )

    asyncio.

    run

    (

    main

    (

    )

    )

    3. Task

    A task is a wrapper around a coroutine, representing a coroutine that is running or about to run. You can use the asyncio.create_task() function to create a task and add it to the event loop.

    Example

    async

    def

    main

    (

    )

    :

        task

    =

    asyncio.

    create_task

    (

    say_hello

    (

    )

    )

        await task

    4. Future

    Future is an object representing the result of an asynchronous operation. It is usually used by low-level APIs to represent an operation that has not completed yet. You can wait for await with the keyword to wait for Future to complete.

    Example

    async

    def

    main

    (

    )

    :

        future

    =

    asyncio.

    Future

    (

    )

        await future

    Basic usage and code examples

    Let's understand these concepts through a classic example that concurrently fetches several URLs.

    Suppose we need to fetch the content of three different URLs. The synchronous approach runs sequentially, and the total time is the sum of the three request times. Using asyncio, we can issue all three requests at the same time, and the total time is close to the slowest single request.

    Synchronous version (for comparison)

    Example

    import

    time

    import

    requests

    def

    fetch_url

    (

    url

    )

    :

       

    """Simulate a time-consuming network request (synchronous version)"""

       

    print

    (

    f

    "Starting fetch: {url}"

    )

       

    time

    .

    sleep

    (

    2

    )

     

    Simulate a 2-second network delay

       

    print

    (

    f

    "Finished fetch: {url}"

    )

       

    return

    f

    "Data from {url}"

    def

    main_sync

    (

    )

    :

        urls

    =

    [

    'https://example.

    com

    /

    1

    '

    ,

    'https://example.

    com

    /

    2

    '

    ,

    'https://example.

    com

    /

    3

    '

    ]

        results

    =

    [

    ]

        start

    =

    time

    .

    time

    (

    )

       

       

    for

    url

    in

    urls:

            result

    =

    fetch_url

    (

    url

    )

     

    Must wait for the previous one to finish before starting the next

            results.

    append

    (

    result

    )

       

        end

    =

    time

    .

    time

    (

    )

       

    print

    (

    f

    "Total time for the synchronous version: {end - start:.2f} seconds"

    )

       

    print

    (

    f

    "Results: {results}"

    )

    if

    name

    ==

    "main"

    :

        main_sync

    (

    )

    Expected output:

    开始获取: https://example.com/1
    完成获取: https://example.com/1
    开始获取: https://example.com/2
    完成获取: https://example.com/2
    开始获取: https://example.com/3
    完成获取: https://example.com/3
    同步版本总耗时: 6.00 秒
    结果: [‘来自 https://example.com/1 的数据‘, ‘来自 https://example.com/2 的数据‘, ‘来自 https://example.com/2 的数据‘]
    

    It took about 6 seconds in total.

    Asynchronous version (using asyncio)

    We need to use the aiohttp library instead of requests for asynchronous HTTP requests. Install it first:pip install aiohttp。

    Example

    import

    asyncio

    import

    aiohttp

    import

    time

    async

    def

    fetch_url_async

    (

    session

    ,

    url

    )

    :

       

    """Simulate a time-consuming network request (asynchronous version)"""

       

    print

    (

    f

    "Starting async fetch: {url}"

    )

       

    Note: here we use aiohttp's asynchronous get method and await it

        async

    with

    session.

    get

    (

    url

    )

    as

    response:

           

    Simulate that processing the response also takes time

            await asyncio.

    sleep

    (

    2

    )

     

    Use asyncio.sleep to simulate the I/O wait; it does not block the thread

            text

    =

    await response.

    text

    (

    )

           

    print

    (

    f

    "Finished async fetch: {url}"

    )

           

    return

    f

    "Data from {url} (length: {len(text)})"

    async

    def

    main_async

    (

    )

    :

        urls

    =

    [

    'https://httpbin.

    org

    /get'

    ,

    'https://httpbin.

    org

    /delay/

    1

    '

    ,

    'https://httpbin.

    org

    /headers'

    ]

       

        async

    with

    aiohttp.

    ClientSession

    (

    )

    as

    session:  

    Create an asynchronous HTTP session

           

    Create a task for each URL

            tasks

    =

    [

    ]

           

    for

    url

    in

    urls:

               

    create_task adds the coroutine to the event loop and starts scheduling immediately

                task

    =

    asyncio.

    create_task

    (

    fetch_url_async

    (

    session

    ,

    url

    )

    )

                tasks.

    append

    (

    task

    )

           

           

    print

    (

    "All tasks created, starting concurrent execution..."

    )

           

           

    Use asyncio.gather to run all tasks concurrently and wait for all of them to finish

           

    gather returns a list of results in the same order as the tasks passed in

            results

    =

    await asyncio.

    gather

    (

    *tasks

    )

           

           

    return

    results

    if

    name

    ==

    "main"

    :

        start

    =

    time

    .

    time

    (

    )

       

    asyncio.run() is a convenient way to start the event loop and run a top-level coroutine

        final_results

    =

    asyncio.

    run

    (

    main_async

    (

    )

    )

        end

    =

    time

    .

    time

    (

    )

       

       

    print

    (

    f

    "\nTotal time for the asynchronous version: {end - start:.2f} seconds"

    )

       

    for

    res

    in

    final_results:

           

    print

    (

    res

    )

    Expected output:

    所有任务已创建,开始并发执行...
    开始异步获取: https://httpbin.org/get
    开始异步获取: https://httpbin.org/delay/1
    开始异步获取: https://httpbin.org/headers
    (大约 2 秒后,所有请求几乎同时完成)
    完成异步获取: https://httpbin.org/headers
    完成异步获取: https://httpbin.org/get
    完成异步获取: https://httpbin.org/delay/1
    
    异步版本总耗时: 2.10 秒  # 注意!总耗时远小于 6 秒
    来自 https://httpbin.org/get 的数据 (长度: 274)
    来自 https://httpbin.org/delay/1 的数据 (长度: 392)
    来自 https://httpbin.org/headers 的数据 (长度: 177)
    

    Code Analysis:

    Key functions and parameters

    The table below lists asyncio several of the most commonly used high-level functions:

    function Main purpose Common parameters
    asyncio.run(coro, *, debug=False) Run a top-level coroutine and manage the event loop's lifetime. This is the program's main entry point. coro: the coroutine object to run.
    debug: set to True to enable the event loop's debug mode.
    asyncio.create_task(coro, *, name=None) Wrap a coroutine into a Task object and queue it in the event loop for scheduling. This is the main way to achieve concurrency. coro: the coroutine object to wrap.
    name: (Python 3.8+) assign a name to the task for easier debugging.
    asyncio.gather(*aws, return_exceptions=False) Concurrently runmultiple asynchronous tasks (aws accepts coroutines, tasks, etc.), wait for all of them to finish, and return a list of results. *aws: variadic; pass multiple asynchronous objects.
    return_exceptions: defaults to False; any exception raised by a task propagates immediately to gather 's caller. When set to True , exceptions are returned as part of the results.
    asyncio.sleep(delay, result=None) Asynchronouslysleep for the specified number of seconds. This is the key difference from time.sleep(blocking). delay: the number of seconds to sleep.
    result: the value returned after sleeping.
    asyncio.wait(aws, *, timeout=None, return_when=ALL_COMPLETED) Run tasks concurrently and wait until the specified condition is met. Returns two sets, (done, pending), namely the completed and the pending tasks. aws: a collection of asynchronous objects.
     `timeout`: 超时时间(秒)。       
     `return_when`: 决定何时返回,可选:`FIRST_COMPLETED`(第一个完成)、`FIRST_EXCEPTION`(第一个异常)、`ALL_COMPLETED`(全部完成,默认)。 |
    

    | asyncio.to_thread(func, /, *args, **kwargs) | (Python 3.9+) runs an ordinary, possibly blocking synchronous function in a separate thread and returns an awaitable await coroutine. Used for CPU-intensive or blocking I/O. | func: the synchronous function to run in the thread.
    *args, **kwargs: the arguments passed to the function. |

    Visual understanding: asynchronous task scheduling flow

    Diagram explanation: this flowchart shows how the event loop works like a dispatcher. It maintains a task queue; when a task reaches await(for example, waiting for a network response), it is suspended and the event loop immediately picks the next runnable (ready) task from the queue to execute. When the suspended task's I/O operation completes, the event loop is notified, marks the task as ready again, and resumes it at some later point. In this way the CPU is fully utilized during I/O waits to execute other tasks, achieving concurrency within a single thread.


    Basic usage of asyncio

    1. Run a coroutine

    To run a coroutine, you can use the asyncio.run() function. It creates an event loop and runs the specified coroutine.

    Example

    import

    asyncio

    async

    def

    main

    (

    )

    :

       

    print

    (

    "Start"

    )

        await asyncio.

    sleep

    (

    1

    )

       

    print

    (

    "End"

    )

    asyncio.

    run

    (

    main

    (

    )

    )

    2. Execute multiple tasks concurrently

    You can use the asyncio.gather() function to execute multiple coroutines concurrently and wait for all of them to finish.

    Example

    import

    asyncio

    async

    def

    task1

    (

    )

    :

       

    print

    (

    "Task 1 started"

    )

        await asyncio.

    sleep

    (

    1

    )

       

    print

    (

    "Task 1 finished"

    )

    async

    def

    task2

    (

    )

    :

       

    print

    (

    "Task 2 started"

    )

        await asyncio.

    sleep

    (

    2

    )

       

    print

    (

    "Task 2 finished"

    )

    async

    def

    main

    (

    )

    :

        await asyncio.

    gather

    (

    task1

    (

    )

    ,

    task2

    (

    )

    )

    asyncio.

    run

    (

    main

    (

    )

    )

    3. Timeout control

    You can use the asyncio.wait_for() The function sets a timeout for a coroutine. If the coroutine does not finish within the specified time, a asyncio.TimeoutError exception.

    Example

    import

    asyncio

    async

    def

    long_task

    (

    )

    :

        await asyncio.

    sleep

    (

    10

    )

       

    print

    (

    "Task finished"

    )

    async

    def

    main

    (

    )

    :

       

    try

    :

            await asyncio.

    wait_for

    (

    long_task

    (

    )

    ,

    timeout

    =

    5

    )

       

    except

    asyncio.

    TimeoutError

    :

           

    print

    (

    "Task timed out"

    )

    asyncio.

    run

    (

    main

    (

    )

    )


    Application scenarios for asyncio

    asyncio It is especially suitable for the following scenarios:

    1. Network requests: such as HTTP requests and WebSocket communication.
    2. File I/O: such as asynchronous file reads and writes.
    3. Database operations: such as asynchronous database access.
    4. Real-time data processing: such as real-time message queue processing.

    Common classes, methods and functions

    1. Core functions

    Method/function Description Example
    asyncio.run(coro) Run an asynchronous main function (Python 3.7+) asyncio.run(main())
    asyncio.create_task(coro) Create a task and add it to the event loop task = asyncio.create_task(fetch_data())
    asyncio.gather(*coros) Run multiple coroutines concurrently await asyncio.gather(task1, task2)
    asyncio.sleep(delay) Asynchronous wait (non-blocking) await asyncio.sleep(1)
    asyncio.wait(coros) Control how tasks are awaited as they complete done, pending = await asyncio.wait([task1, task2])

    2. Event loop

    Method Description Example
    loop.run_until_complete(future) Run until the task completes loop.run_until_complete(main())
    loop.run_forever() Run the event loop forever loop.run_forever()
    loop.stop() Stop the event loop loop.stop()
    loop.close() Close the event loop loop.close()
    loop.call_soon(callback) Schedule a callback for immediate execution loop.call_soon(print, "Hello")
    loop.call_later(delay, callback) Execute a callback after a delay loop.call_later(5, callback)

    3. Coroutines and tasks

    Method/decorator Description Example
    @asyncio.coroutine Coroutine decorator (legacy, Python 3.4-3.7) @asyncio.coroutine
    def old_coro():
    async def Define a coroutine (Python 3.5+) async def fetch():
    task.cancel() Cancel a task task.cancel()
    task.done() Check whether a task is done if task.done():
    task.result() Get the task result (task must be done) data = task.result()

    4. Synchronization primitives (similar tothreading)

    class Description Example
    asyncio.Lock() Asynchronous mutex lock lock = asyncio.Lock()
    async with lock:
    asyncio.Event() Event notification event = asyncio.Event()
    await event.wait()
    asyncio.Queue() Asynchronous queue queue = asyncio.Queue()
    await queue.put(item)
    asyncio.Semaphore() Semaphore sem = asyncio.Semaphore(5)
    async with sem:

    5. Networking and subprocesses

    Method/class Description Example
    asyncio.open_connection() Establish a TCP connection reader, writer = await asyncio.open_connection('host', 80)
    asyncio.start_server() Create a TCP server server = await asyncio.start_server(handle, '0.0.0.0', 8888)
    asyncio.create_subprocess_exec() Create a subprocess proc = await asyncio.create_subprocess_exec('ls')

    6. Utilities

    Method Description Example
    asyncio.current_task() Get the current task task = asyncio.current_task()
    asyncio.all_tasks() Get all tasks tasks = asyncio.all_tasks()
    asyncio.shield(coro) Shield a task from cancellation await asyncio.shield(critical_task)
    asyncio.wait_for(coro, timeout) Wait with a timeout try: await asyncio.wait_for(task, 5)

    Example

    1. Basic coroutine example

    Example

    import

    asyncio

    async

    def

    hello

    (

    )

    :

       

    print

    (

    "Hello"

    )

        await asyncio.

    sleep

    (

    1

    )

       

    print

    (

    "World"

    )

    asyncio.

    run

    (

    hello

    (

    )

    )

     

    Python 3.7+

    1. Execute tasks concurrently

    Example

    async

    def

    fetch

    (

    url

    )

    :

       

    print

    (

    f

    "Fetching {url}"

    )

        await asyncio.

    sleep

    (

    2

    )

       

    return

    f

    "Data from {url}"

    async

    def

    main

    (

    )

    :

        results

    =

    await asyncio.

    gather

    (

            fetch

    (

    "url1.com"

    )

    ,

            fetch

    (

    "url2.com"

    )

       

    )

       

    print

    (

    results

    )

    asyncio.

    run

    (

    main

    (

    )

    )

    1. Use an asynchronous queue

    Example

    async

    def

    producer

    (

    queue

    )

    :

       

    for

    i

    in

    range

    (

    5

    )

    :

            await queue.

    put

    (

    i

    )

            await asyncio.

    sleep

    (

    0.1

    )

    async

    def

    consumer

    (

    queue

    )

    :

       

    while

    True

    :

            item

    =

    await queue.

    get

    (

    )

           

    print

    (

    f

    "Consumed {item}"

    )

            queue.

    task_done

    (

    )

    async

    def

    main

    (

    )

    :

        queue

    =

    asyncio.

    Queue

    (

    )

        await asyncio.

    gather

    (

            producer

    (

    queue

    )

    ,

            consumer

    (

    queue

    )

       

    )


    Notes

    1. Python version: some features require Python 3.7+ (such asasyncio.run())。

    2. Blocking operations: avoid synchronous blocking code in coroutines (such astime.sleep())。

    3. Debugging: set thePYTHONASYNCIODEBUG=1environment variable to enable debug mode.

    4. Cancel a task: a cancelled task raisesCancelledErrorand must be handled properly.