Skip to main content

async-example

在Python中,async 关键字用于定义一个异步函数,而 await 关键字用于调用另一个异步函数。这使得你可以编写非阻塞的代码,这对于I/O密集型任务(如网络请求、文件读写等)特别有用。

下面是一些使用 asyncawait 的基本示例:

示例1:简单的异步函数

import asyncio

async def say_hello(name):
print(f"Hello, {name}!")
await asyncio.sleep(1) 模拟异步操作,例如网络请求
print(f"Goodbye, {name}!")

async def main():
await say_hello("Alice")
await say_hello("Bob")

运行异步主函数
asyncio.run(main())

示例2:使用 asyncio.gather 并发执行多个异步任务

import asyncio

async def fetch_data(url):
print(f"Fetching {url}")
await asyncio.sleep(2) 模拟网络请求
return f"Data from {url}"

async def main():
task1 = fetch_data("https://example.com/data1")
task2 = fetch_data("https://example.com/data2")
results = await asyncio.gather(task1, task2)
print(results)

运行异步主函数
asyncio.run(main())

示例3:使用 asyncawait 在循环中处理异步任务

import asyncio

async def fetch_data(url):
print(f"Fetching {url}")
await asyncio.sleep(1) 模拟网络请求
return f"Data from {url}"

async def main():
urls = ["https://example.com/data1", "https://example.com/data2", "https://example.com/data3"]
tasks = [fetch_data(url) for url in urls]
results = await asyncio.gather(*tasks)
for result in results:
print(result)

运行异步主函数
asyncio.run(main())

示例4:结合 asyncio.create_task 使用异步任务

import asyncio

async def fetch_data(url):
print(f"Fetching {url}")
await asyncio.sleep(1) 模拟网络请求
return f"Data from {url}"

async def main():
tasks = [asyncio.create_task(fetch_data(f"https://example.com/data{i}")) for i in range(1, 4)]
done, pending = await asyncio.wait(tasks)
for task in done:
print(task.result())

运行异步主函数
asyncio.run(main())

这些示例展示了如何使用Python的 asyncawait 关键字来编写异步代码。通过这些示例,你可以看到如何定义异步函数、如何等待异步操作完成、以及如何并发执行多个异步任务。