Python 协程异步IO asyncio 模块介绍
asyncio模块在Python3.4标准库中引入,实现使用协程构建异步并发功能
介绍
- 相关扩展:进程、线程、协程的作用和区别
asyncio的编程模型核心事件循环(Event Loop),本质是一个无限的死循环- 程序把函数注册到
事件循环(Event Loop)上 - 当满足事件的条件时,调用相应的协程函数,实现异步 IO
- 程序把函数注册到
- 关键字
- 函数名前加
async关键字 await表示在这个地方等待子函数执行完成,再往下执行- 在并发操作中,把程序控制权教给主程序,让他分配其他协程执行
await只能在带有async关键字的函数中运行
- 函数名前加
使用场景
一般用在 IO 密集型任务
- 网络请求,比如
爬虫、aiohttp - 文件读取
aiofile - web 框架
aiohttp、fastapi - 数据库查询
asyncpg等
Future
asyncio.Futures 代表还未完成的结果(有可能是一个 Exception),代表还没有做完的事情
import asyncio
future = asyncio.Future()常见方法:
cancel()取消 future 的执行,调度回调函数result()返回 future 代表的结果exception()返回 future 中的 Exceptionadd_done_callback(fn)添加一个回调函数,当 future 执行的时候会调用这个回调函数remove_done_callback(fn)从call whten done列表中移除所有 callback 的实例set_result(result)将 future 标为执行完成,并且设置 result 的值set_exception(exception)将 future 标为执行完成,并设置 Exception
Task
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
import asyncio
async def hello_world():
print("Hello World!")
asyncio.run(hello_world())说明:
async def声明异步协程函数,通过asyncio.run()管理事件循环并执行协程。
Coroutine displaying the current date
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
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 配合协程
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 函数
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())