本文目录导读:

- 基础等待 - await
- 等待多个任务 - asyncio.gather()
- 等待第一个完成的任务 - asyncio.wait()
- 超时等待 - asyncio.wait_for()
- 等待特定的 Future 对象
- 使用事件循环等待
- 实际应用示例:并发下载
在Python中等待异步执行主要使用 async/await 语法,以下是几种常见方式:
基础等待 - await
import asyncio
async def fetch_data():
await asyncio.sleep(2) # 模拟耗时操作
return "数据获取完成"
async def main():
# 等待单个异步任务
result = await fetch_data()
print(result)
# 运行
asyncio.run(main())
等待多个任务 - asyncio.gather()
import asyncio
async def task1():
await asyncio.sleep(1)
return "任务1完成"
async def task2():
await asyncio.sleep(2)
return "任务2完成"
async def main():
# 并发执行多个任务,等待所有完成
results = await asyncio.gather(
task1(),
task2()
)
print(results) # ['任务1完成', '任务2完成']
asyncio.run(main())
等待第一个完成的任务 - asyncio.wait()
import asyncio
async def task1():
await asyncio.sleep(3)
return "慢任务"
async def task2():
await asyncio.sleep(1)
return "快任务"
async def main():
# 等待第一个完成的任务
done, pending = await asyncio.wait(
[task1(), task2()],
return_when=asyncio.FIRST_COMPLETED
)
# 取消未完成的任务
for task in pending:
task.cancel()
print(f"完成的任务: {done.pop().result()}")
asyncio.run(main())
超时等待 - asyncio.wait_for()
import asyncio
async def long_task():
await asyncio.sleep(5)
return "长时间任务"
async def main():
try:
# 设置超时时间
result = await asyncio.wait_for(long_task(), timeout=2)
print(result)
except asyncio.TimeoutError:
print("任务超时!")
asyncio.run(main())
等待特定的 Future 对象
import asyncio
async def main():
# 创建 Future
future = asyncio.Future()
# 模拟异步设置结果
async def set_result():
await asyncio.sleep(1)
future.set_result("Future 完成")
# 启动设置结果的任务
asyncio.create_task(set_result())
# 等待 Future
result = await future
print(result)
asyncio.run(main())
使用事件循环等待
import asyncio
async def coroutine():
await asyncio.sleep(1)
return "协程完成"
# 老式方法(Python 3.10之前)
loop = asyncio.get_event_loop()
result = loop.run_until_complete(coroutine())
print(result)
loop.close()
# 现代方法
result = asyncio.run(coroutine())
print(result)
实际应用示例:并发下载
import asyncio
import time
async def download_file(file_id):
print(f"开始下载文件 {file_id}")
await asyncio.sleep(file_id) # 模拟下载时间
print(f"文件 {file_id} 下载完成")
return f"文件{file_id}_内容"
async def main():
start_time = time.time()
# 并发下载3个文件
tasks = [download_file(1), download_file(2), download_file(3)]
# 方式1:等待所有完成
results = await asyncio.gather(*tasks)
print(f"所有文件下载结果: {results}")
# 方式2:逐步处理已完成的任务
for coro in asyncio.as_completed(tasks):
result = await coro
print(f"处理: {result}")
print(f"总耗时: {time.time() - start_time:.2f}秒")
asyncio.run(main())
- await: 等待单个协程/任务完成
- asyncio.gather(): 并发等待多个任务
- asyncio.wait(): 更灵活的任务等待(可设置等待条件)
- asyncio.wait_for(): 带超时的等待
- asyncio.run(): 运行顶层协程(现代方式)
- 事件循环: 管理异步任务的底层机制
选择哪种方式取决于你的具体需求:
- 简单等待 →
await - 多任务并发 →
gather() - 需要控制超时 →
wait_for() - 需取消未完成任务 →
wait()
版权声明:NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播