asyncio是Python中用于异步编程的标准库,它提供了基于协程的并发框架。异步编程旨在提高程序的并发性,使得程序在IO密集型任务中更高效。以下是asyncio的一些基本用法:
import asyncio
# 异步函数
async def my_async_function():
print("Async function start")
await asyncio.sleep(1) # 模拟耗时操作
print("Async function end")
# 启动事件循环
asyncio.run(my_async_function())
import asyncio
# 异步函数
async def task_one():
print("Task One start")
await asyncio.sleep(1) # 模拟耗时操作
print("Task One end")
async def task_two():
print("Task Two start")
await asyncio.sleep(2) # 模拟耗时操作
print("Task Two end")
# 启动事件循环 q
async def main():
await asyncio.gather(task_one(), task_two())
asyncio.run(main())
asyncio.create_task创建任务:import asyncio
async def task_one():
print("Task One start")
await asyncio.sleep(1) # 模拟耗时操作
print("Task One end")
async def task_two():
print("Task Two start")
await asyncio.sleep(2) # 模拟耗时操作
print("Task Two end")
async def main():
# 使用create_task创建任务
task1 = asyncio.create_task(task_one())
task2 = asyncio.create_task(task_two())
# 等待所有任务完成
await asyncio.gather(task1, task2)
asyncio.run(main())
import asyncio
async def read_file(file_path):
print(f"Reading file: {file_path}")
await asyncio.sleep(1) # 模拟文件读取操作
print("File read complete")
async def write_file(file_path, content):
print(f"Writing to file: {file_path}")
await asyncio.sleep(2) # 模拟文件写入操作
print("File write complete")
async def main():
file_path = "example.txt"
content = "Hello, asyncio!"
# 同时执行文件读取和写入操作
await asyncio.gather(read_file(file_path), write_file(file_path, content))
asyncio.run(main())
在异步代码中,如果需要调用阻塞的同步代码,可以使用loop.run_in_executor将其包装在一个线程池中执行。
import asyncio
import requests
async def fetch_url(url):
loop = asyncio.get_event_loop()
# 使用线程池执行阻塞代码
response = await loop.run_in_executor(None, requests.get, url)
print(f"Response from {url}: {response.text[:100]}")
async def main():
urls = ["<https://www.example.com>", "<https://www.example.org>", "<https://www.example.net>"]
# 异步并发获取多个URL的内容
await asyncio.gather(*(fetch_url(url) for url in urls))
asyncio.run(main())
asyncio提供了强大的工具来简化异步编程,包括async/await语法、协程、事件循环等。通过使用asyncio,可以更容易地编写高效的异步代码,特别适用于IO密集型任务。