Kevin Open

Python 异步编程:从 asyncio 到实战

2025-09-15 · Python

当应用需要同时处理大量 I/O 操作(网络请求、数据库查询、文件读写)时, 异步编程可以在单线程中实现高并发,避免线程切换的开销。

async / await 基础

import asyncio
import aiohttp

async def fetch(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as resp:
            return await resp.text()

async def main():
    urls = ["https://example.com", "https://httpbin.org/get"]
    tasks = [fetch(url) for url in urls]
    results = await asyncio.gather(*tasks)
    for r in results:
        print(len(r))

asyncio.run(main())

适用场景

注意事项

异步并不适用于 CPU 密集型任务。对于计算密集的操作, 应使用 concurrent.futures.ProcessPoolExecutor 或将任务交给后台 Worker 处理。 另外,避免在异步函数中调用阻塞式 I/O,否则会阻塞整个事件循环。