知识分享空间

记录学习历程,分享技术心得

Python 异步编程入门指南

2026-07-01 | Python | 异步编程

Python 的异步编程是提升 IO 密集型应用性能的重要手段。本文将带你了解 asyncio 库的核心概念和基本用法。

什么是协程

协程(Coroutine)是一种可以在执行过程中暂停并恢复的函数。在 Python 中,使用 async def 关键字定义协程函数,调用它会返回一个协程对象,而不是立即执行。

import asyncio

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

asyncio.run(hello())

await 关键字

await 用于等待一个可等待对象完成。可等待对象包括协程、Task 和 Future。当执行 await 时,当前协程会暂停,让出控制权给事件循环。

创建并发任务

使用 asyncio.create_task() 可以创建并发执行的 Task,让多个协程同时运行。

async def fetch_data(url):
    print(f"Fetching {url}...")
    await asyncio.sleep(2)
    return f"Data from {url}"

async def main():
    task1 = asyncio.create_task(fetch_data("url1"))
    task2 = asyncio.create_task(fetch_data("url2"))
    result1 = await task1
    result2 = await task2
    print(result1, result2)

asyncio.run(main())

掌握异步编程能够显著提升爬虫、Web 服务等 IO 密集型场景的性能表现,是 Python 进阶的必备技能。