为什么需要异步?
在网络请求、文件 I/O 等场景中,同步代码会阻塞等待,浪费 CPU。异步编程允许在等待时执行其他任务,提高并发性能。
基本语法
import asyncio
async def say_hello():
print("Hello")
await asyncio.sleep(1)
print("World")
asyncio.run(say_hello())并发执行多个任务
async def main():
task1 = asyncio.create_task(say_hello())
task2 = asyncio.create_task(say_hello())
await task1
await task2
asyncio.run(main())常用库
aiohttp:异步 HTTP 客户端/服务端aiomysql:异步 MySQL 驱动aiofiles:异步文件操作
异步编程能显著提升 I/O 密集型应用的吞吐量,是 Python 高并发开发的必备技能。
