Async (异步)
下面是一份 Python async / await 最清晰、最实用、最容易理解的入门 + 进阶指南,适合你整体掌握异步编程体系。
Python 异步编程主要基于:
- async(定义异步函数)
- await(等待异步结果)
- asyncio(事件循环 + 协程调度)
- Task(并发执行)
它主要用于:
- 网络 IO(HTTP 请求)
- 数据库异步操作(SQLAlchemy async / aiomysql)
- 高并发任务处理
- 爬虫、服务端、Web 框架(FastAPI)
async def fetch_data():
return 123
result = await fetch_data()
⚠️ await 只能在 async 函数中使用。
🔥 一个线程里在等待 IO 时不阻塞,可以做别的事。
示例:
async def download():
await asyncio.sleep(2)
print("done")
sleep() 在等待 -> 程序可以去做别的任务(真正的并发)
import asyncio
async def hello():
print("Hello")
await asyncio.sleep(1)
print("World")
asyncio.run(hello())
| 类型 | 返回 |
|---|---|
| def | 直接返回值 |
| async def | 返回 协程对象(coroutine),需要 await |
例子:
async def foo():
return 100
print(foo())
# <coroutine object foo at 0x...>
不能直接拿到结果,必须:
result = await foo()
或:
asyncio.run(foo())
如果你想 同时执行多个异步任务,用 Task:
import asyncio
async def download(i):
print(f"Start {i}")
await asyncio.sleep(1)
print(f"End {i}")
async def main():
tasks = [asyncio.create_task(download(i)) for i in range(3)]
await asyncio.gather(*tasks)
asyncio.run(main())
输出(并行执行):
Start 0
Start 1
Start 2
End 0
End 1
End 2
sleep() 是异步 IO 的代表:
await asyncio.sleep(1)
它告诉事件循环:
我在等待,不占用 CPU,你可以先去执行别的任务。
使用 aiohttp:
import aiohttp
import asyncio
async def fetch(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as resp:
return await resp.text()
如:
- async SQLAlchemy
- aiomysql
- aioredis
result = await async_session.execute(query)
import aiofiles
async with aiofiles.open("data.txt") as f:
text = await f.read()
| 类型 | 最适合 |
|---|---|
| async | 大量 IO(HTTP、DB、文件、Socket) |
| thread | 同时跑多个函数,混合 IO 和轻 CPU |
| process | CPU 密集型(计算、模型) |
示例:FastAPI 就是典型的 async IO。
核心思想:
事件循环管理协程 -> 协程在遇到 await 时让出控制权 -> 事件循环调度其他任务 -> 等待完成后继续执行
一般不会自己操作 event loop,但可以:
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
现代写法是 asyncio.run(main())。
async def task():
try:
await something()
except Exception as e:
print("error", e)
- async 定义异步函数
- await 等待耗时 IO
- 协程本身不会自动执行(需要 asyncio.run)
- 想并发用 create_task / gather
- async 适合 I/O 密集型任务
- 不适合 CPU 密集任务(那是多进程的领域)
async/await
│
├── async 定义协程 -> 返回 coroutine,不会自动执行
├── await 等待协程 -> 挂起当前任务
│
├── asyncio.run(main) -> 启动整个异步程序
├── asyncio.create_task -> 创建并发任务
├── asyncio.gather -> 并发等待多个协程
│
└── 适合 I/O:
- 网络请求
- DB 查询
- 文件操作
- FastAPI