Python 协程异步IO asyncio 模块介绍

发布时间: 更新时间: 总字数:898 阅读时间:2m 作者:IP:上海 网址

asyncio模块在Python3.4标准库中引入,实现使用协程构建异步并发功能

介绍

  • 相关扩展:进程、线程、协程的作用和区别
  • asyncio的编程模型核心 事件循环(Event Loop),本质是一个无限的死循环
    • 程序把函数注册到 事件循环(Event Loop) 上
    • 当满足事件的条件时,调用相应的协程函数,实现异步 IO
  • 关键字
    • 函数名前加 async 关键字
    • await 表示在这个地方等待子函数执行完成,再往下执行
      • 在并发操作中,把程序控制权教给主程序,让他分配其他协程执行
    • await 只能在带有 async 关键字的函数中运行

使用场景

一般用在 IO 密集型任务

  • 网络请求,比如爬虫、aiohttp
  • 文件读取 aiofile
  • web 框架 aiohttp、fastapi
  • 数据库查询 asyncpg 等

Future

asyncio.Futures 代表还未完成的结果(有可能是一个 Exception),代表还没有做完的事情

python
import asyncio
future = asyncio.Future()

常见方法:

  • cancel() 取消 future 的执行,调度回调函数
  • result() 返回 future 代表的结果
  • exception() 返回 future 中的 Exception
  • add_done_callback(fn) 添加一个回调函数,当 future 执行的时候会调用这个回调函数
  • remove_done_callback(fn) 从 call whten done 列表中移除所有 callback 的实例
  • set_result(result) 将 future 标为执行完成,并且设置 result 的值
  • set_exception(exception) 将 future 标为执行完成,并设置 Exception

Task

text
class asyncio.Task(coro, *, loop=None, name=None, context=None, eager_start=False)

Task 对象被用来在 事件循环 中运行协程。如果一个协程在等待一个 Future 对象,Task 对象会挂起该协程的执行并等待该 Future 对象完成。当该 Future 对象完成,被打包的协程将恢复执行

示例

注意:早期 Python(3.4~3.7)曾使用基于生成器的 @asyncio.coroutine 与 yield from 语法,该语法自 Python 3.8 起弃用、Python 3.11 中已正式移除。现代 Python 统一使用 async def 与 await 关键字,并推荐使用 asyncio.run() 启动事件循环。

Hello World

python
import asyncio

async def hello_world():
    print("Hello World!")

asyncio.run(hello_world())

说明:

  • async def 声明异步协程函数,通过 asyncio.run() 管理事件循环并执行协程。

Coroutine displaying the current date

python
import asyncio
import datetime

async def display_date():
    loop = asyncio.get_running_loop()
    end_time = loop.time() + 5.0
    while True:
        print(datetime.datetime.now())
        if (loop.time() + 1.0) >= end_time:
            break
        await asyncio.sleep(1)

asyncio.run(display_date())

说明:

  • asyncio.sleep(1) 也是一个协程,await 时当前协程会让出控制权,事件循环可调度执行其他就绪任务。

Parallel execution of tasks

python
import asyncio

async def factorial(name, number):
    f = 1
    for i in range(2, number + 1):
        print("Task %s: Compute factorial(%s)..." % (name, i))
        await asyncio.sleep(1)
        f *= i
    print("Task %s: factorial(%s) = %s" % (name, number, f))
    return f

async def main():
    # 通过 asyncio.gather 并发调度多个任务
    await asyncio.gather(
        factorial("A", 2),
        factorial("B", 3),
        factorial("C", 4),
    )

asyncio.run(main())

说明:

  • 通过 asyncio.gather 或 asyncio.wait 实现一组 task 的并发执行。

Future 配合协程

python
import asyncio

async def slow_operation(future):
    await asyncio.sleep(1)
    future.set_result('Future is done!')

async def main():
    loop = asyncio.get_running_loop()
    future = loop.create_future()
    asyncio.create_task(slow_operation(future))
    result = await future
    print(result)

asyncio.run(main())

同时调度多个 async 函数

python
import asyncio
import threading


async def hello(name):
    print("hi %s! (%s)" % (name, threading.get_ident()))
    await asyncio.sleep(1)
    print("hi %s again! (%s)" % (name, threading.get_ident()))
    return name


async def main():
    L = await asyncio.gather(hello("Bob"), hello("Alice"))
    print(L)


asyncio.run(main())

参考

  1. https://docs.python.org/3/library/asyncio.html
  2. https://docs.python.org/zh-cn/3/library/asyncio-task.html
  3. https://docs.python.org/3/library/asyncio-task.html
  4. https://zhuanlan.zhihu.com/p/59671241