Python 异步编程指南

什么是异步编程?

传统的同步编程中,代码按顺序执行,遇到 I/O 操作时会阻塞。异步编程允许在等待 I/O 时执行其他任务。

asyncio 基础

协程

import asyncio

async def hello():
    print("Hello")
    await asyncio.sleep(1)
    print("World")

asyncio.run(hello())

并发执行

async def fetch_data(url):
    await asyncio.sleep(2)  # 模拟网络请求
    return f"data from {url}"

async def main():
    # 并发执行多个协程
    results = await asyncio.gather(
        fetch_data("url1"),
        fetch_data("url2"),
        fetch_data("url3"),
    )
    print(results)

asyncio.run(main())

异步 HTTP 请求

使用 aiohttp

import aiohttp
import asyncio

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

async def main():
    html = await fetch("https://example.com")
    print(html[:100])

asyncio.run(main())

注意事项

  1. 不要在协程中使用阻塞调用 — 会阻塞整个事件循环
  2. CPU 密集任务用 ProcessPoolExecutor — 异步不适合 CPU 密集场景
  3. 合理使用信号量 — 控制并发数量,避免资源耗尽

总结

异步编程是 Python 处理高并发 I/O 场景的利器,但也要合理使用,不要为了异步而异步。

Python