本文将深入探讨 Python 的 asyncio 库的高级特性,包括任务取消、并发网络请求、异步 I/O 操作等。
任务取消
在异步编程中,任务取消是一个重要的功能。asyncio
提供了 cancel()
方法来取消一个任务。
import asyncio
async def main():
task = asyncio.create_task(some_coroutine())
await task # 等待任务完成或取消
try:
task.cancel()
await task
except asyncio.CancelledError:
print("任务已被取消")
async def some_coroutine():
await asyncio.sleep(1)
print("任务正在执行")
asyncio.run(main())
并发网络请求
aiohttp
是一个流行的异步 HTTP 库,可以用于并发网络请求。
import aiohttp
import asyncio
async def fetch(session, url):
async with session.get(url) as response:
return await response.text()
async def main():
async with aiohttp.ClientSession() as session:
html = await asyncio.gather(
fetch(session, 'http://example.com'),
fetch(session, 'http://example.org'),
fetch(session, 'http://example.net')
)
print(html)
asyncio.run(main())
异步 I/O 操作
Python 的 asyncio
库提供了对异步 I/O 操作的支持,例如异步文件读写。
import asyncio
async def read_file(file_path):
async with aiofiles.open(file_path, mode='r') as file:
return await file.read()
async def write_file(file_path, content):
async with aiofiles.open(file_path, mode='w') as file:
await file.write(content)
async def main():
await write_file('example.txt', 'Hello, world!')
content = await read_file('example.txt')
print(content)
# 注意:aiofiles 需要单独安装,可以通过 pip install aiofiles 安装
asyncio.run(main())
更多关于 Python asyncio 的信息,请参阅Python asyncio 官方文档。
Python asyncio