Asyncio 是 Python 3.4 引入的异步 I/O 框架,支持通过协程(coroutine)实现高并发网络程序。以下为高级用法详解:

1. 协程与事件循环

  • 创建协程:使用 async def 定义异步函数

    async def hello():
        print("Hello")
    
    coroutine
  • 运行事件循环:通过 asyncio.run() 启动

    asyncio.run(hello())
    

2. 任务调度

  • 创建任务:使用 asyncio.create_task()

    task
  • 并发执行

    async def main():
        task1 = asyncio.create_task(hello())
        task2 = asyncio.create_task(hello())
        await task1
        await task2
    

3. 异步 IO 操作

  • 文件读写

    async with aiofiles.open("file.txt", mode="r") as f:
        content = await f.read()
    
    async_io
  • 网络请求

    async def fetch():
        async with aiohttp.ClientSession() as session:
            async with await session.get("https://example.com") as resp:
                return await resp.text()
    

4. 高级技巧

  • 异步生成器

    async def count():
        for i in range(5):
            yield i
    
    async_generator
  • 取消任务

    task = asyncio.create_task(hello())
    task.cancel()
    

5. 扩展阅读

如需了解 asyncio 基础知识,可访问 asyncio_basic