Python 异步编程
Python asyncio 与异步编程模型。
#type / concept
#status / growing
#resource / python
#tech / lang / python
[!info] related notes
- 所属 MOC: python-moc
- 前置概念: python函数与装饰器
- 并列概念: python类与面向对象, python数据类型与数据结构
- 关系笔记: python
- 应用: celery
Python 异步编程
Python 通过 asyncio 库和 async/await 语法支持异步编程,适用于 I/O 密集型任务。
核心机制
协程定义
import asyncio
async def fetch_data(url: str) -> str:
print(f"Fetching {url}")
await asyncio.sleep(1) # 模拟 I/O 操作
return f"Data from {url}"
运行协程
# 方式 1: asyncio.run()
async def main():
result = await fetch_data("https://example.com")
print(result)
asyncio.run(main())
# 方式 2: 在 Jupyter 中
# await main()
并发执行
async def main():
# 并发执行多个协程
results = await asyncio.gather(
fetch_data("url1"),
fetch_data("url2"),
fetch_data("url3")
)
print(results) # ['Data from url1', 'Data from url2', 'Data from url3']
任务管理
async def main():
task1 = asyncio.create_task(fetch_data("url1"))
task2 = asyncio.create_task(fetch_data("url2"))
# 等待第一个完成
done, pending = await asyncio.wait(
[task1, task2],
return_when=asyncio.FIRST_COMPLETED
)
# 取消未完成的任务
for task in pending:
task.cancel()
异步上下文管理器
class AsyncDatabaseConnection:
async def __aenter__(self):
self.conn = await create_connection()
return self.conn
async def __aexit__(self, exc_type, exc_val, exc_tb):
await self.conn.close()
async def main():
async with AsyncDatabaseConnection() as conn:
await conn.execute("SELECT * FROM users")
常见误解或边界
- 不是多线程: asyncio 是单线程事件循环,不会并行执行 CPU 密集型任务
- 阻塞操作: 普通阻塞调用会阻塞整个事件循环,需用
asyncio.to_thread()包装 - 协程 vs 线程: 协程切换开销远小于线程,适合大量 I/O 操作