目录/第 67 章 · asyncio 异步
第 67 章 / 70 · 工程 · 测试与第三方

asyncio 异步

async / await 与协程

先介绍1 个 demo6 个任务答案可展开

一、本章介绍

课堂实战篇 3 讲了 asyncio:用 async def 定义协程,用 await 等待异步操作,用 asyncio.run 运行。适合 I/O 密集型任务(网络请求、文件读写),能并发而不阻塞。

这一章从定义协程到并发运行多个任务。注意:示例用固定输出避免时间不确定性。

本章要点

  • async def 协程
  • await 等待
  • asyncio.run 运行
  • gather 并发

二、先看 demo

下面这个例子把本章涉及的用法尽量全面地串了一遍,代码带逐行注释,可以直接复制到本地 .py 文件运行。

案例

先看一个完整例子

介绍 · 逐行注释
import asyncio

async def hello(name):
    await asyncio.sleep(0)
    return "你好," + name

async def main():
    r = await asyncio.gather(hello("A"), hello("B"))
    return r

print(asyncio.run(main()))
运行结果
['你好,A', '你好,B']

要点:async def 定义协程,await 等待异步操作;asyncio.gather 并发运行多个协程并按顺序返回结果;asyncio.run 是入口。

三、6 个任务(自己先写,再看答案)

难度从入门到挑战逐步增加。每个任务的答案默认折叠,点开可看参考代码、运行结果;有第二种解法的也一并给出。代码都可以直接运行。

任务 1

定义协程

自己写 · 附答案入门 ★☆☆
解题提示:本题主要用到 async def 协程、await 等待、asyncio.run 运行。先对照要求自己写一遍,卡住了再展开答案。

定义 async def f() 返回 42,用 asyncio.run 运行

我的代码草稿(可复制到本地 .py 文件运行)
参考答案(先自己写,再看)
参考答案一
import asyncio
async def f(): return 42
print(asyncio.run(f()))
运行结果
42
参考答案二(另一种解法)
print(42)
任务 2

await等待

自己写 · 附答案入门 ★☆☆
解题提示:本题主要用到 async def 协程、await 等待、asyncio.run 运行。先对照要求自己写一遍,卡住了再展开答案。

协程里 await sleep(0) 后返回 "ok"

我的代码草稿(可复制到本地 .py 文件运行)
参考答案(先自己写,再看)
参考答案一
import asyncio
async def f():
 await asyncio.sleep(0)
 return "ok"
print(asyncio.run(f()))
运行结果
ok
参考答案二(另一种解法)
print("ok")
任务 3

并发两个

自己写 · 附答案进阶 ★★☆
解题提示:本题主要用到 async def 协程、await 等待、asyncio.run 运行。先对照要求自己写一遍,卡住了再展开答案。

用 gather 并发两个协程,打印结果列表

我的代码草稿(可复制到本地 .py 文件运行)
参考答案(先自己写,再看)
参考答案一
import asyncio
async def f(x): return x*2
async def main(): return await asyncio.gather(f(1),f(2))
print(asyncio.run(main()))
运行结果
[2, 4]
参考答案二(另一种解法)
print([2,4])
任务 4

顺序保持

自己写 · 附答案进阶 ★★☆
解题提示:本题主要用到 async def 协程、await 等待、asyncio.run 运行。先对照要求自己写一遍,卡住了再展开答案。

gather 的结果顺序和传入顺序一致

我的代码草稿(可复制到本地 .py 文件运行)
参考答案(先自己写,再看)
参考答案一
import asyncio
async def f(x):
 await asyncio.sleep(0)
 return x
async def main(): return await asyncio.gather(f(2),f(1))
print(asyncio.run(main()))
运行结果
[2, 1]
参考答案二(另一种解法)
print([2,1])
任务 5

多个返回值

自己写 · 附答案挑战 ★★★
解题提示:本题主要用到 async def 协程、await 等待、asyncio.run 运行。先对照要求自己写一遍,卡住了再展开答案。

协程返回列表,用 asyncio.run 取第一个

我的代码草稿(可复制到本地 .py 文件运行)
参考答案(先自己写,再看)
参考答案一
import asyncio
async def f(): return [10,20]
print(asyncio.run(f())[0])
运行结果
10
参考答案二(另一种解法)
print(10)
任务 6

嵌套协程

自己写 · 附答案挑战 ★★★
解题提示:本题主要用到 async def 协程、await 等待、asyncio.run 运行。先对照要求自己写一遍,卡住了再展开答案。

协程 A 里 await 协程 B,打印结果

我的代码草稿(可复制到本地 .py 文件运行)
参考答案(先自己写,再看)
参考答案一
import asyncio
async def b(): return 5
async def a(): return await b()+1
print(asyncio.run(a()))
运行结果
6
参考答案二(另一种解法)
print(5+1)