Python脚本如何等待协程全部执行完毕

wen python案例 29

本文目录导读:

Python脚本如何等待协程全部执行完毕

  1. 使用 asyncio.gather()
  2. 使用 asyncio.wait()
  3. 使用 asyncio.as_completed()
  4. 创建任务并等待所有任务
  5. 批量处理任务列表
  6. 错误处理
  7. 完整示例
  8. 选择建议

在Python中,有多种方法可以等待多个协程全部执行完毕,以下是常用的几种方式:

使用 asyncio.gather()

最常用和推荐的方式:

import asyncio
async def task1():
    await asyncio.sleep(2)
    return "Task 1 done"
async def task2():
    await asyncio.sleep(1)
    return "Task 2 done"
async def main():
    # 等待所有协程完成
    results = await asyncio.gather(task1(), task2())
    print(results)  # ['Task 1 done', 'Task 2 done']
asyncio.run(main())

使用 asyncio.wait()

更灵活,可以设置超时或等待所有完成:

async def main():
    tasks = [task1(), task2()]
    # 等待所有任务完成
    done, pending = await asyncio.wait(tasks, timeout=None)
    # 获取结果
    for task in done:
        print(task.result())
asyncio.run(main())

使用 asyncio.as_completed()

按完成顺序处理结果:

async def main():
    tasks = [task1(), task2()]
    # 当每个协程完成时立即处理
    for coro in asyncio.as_completed(tasks):
        result = await coro
        print(f"Got result: {result}")
asyncio.run(main())

创建任务并等待所有任务

async def main():
    # 创建任务
    task1_obj = asyncio.create_task(task1())
    task2_obj = asyncio.create_task(task2())
    # 等待所有任务完成
    results = await asyncio.gather(task1_obj, task2_obj)
    print(results)
asyncio.run(main())

批量处理任务列表

async def main():
    # 创建多个任务
    tasks = [task1(), task2(), task1(), task2()]
    # 批量等待所有任务完成
    results = await asyncio.gather(*tasks)
    print(results)
asyncio.run(main())

错误处理

async def task_with_error():
    await asyncio.sleep(0.5)
    raise ValueError("Something went wrong")
async def main():
    try:
        # 如果有任何任务失败,会抛出异常
        results = await asyncio.gather(task1(), task_with_error(), return_exceptions=False)
    except Exception as e:
        print(f"Error occurred: {e}")
    # 或者捕获异常而不中断其他任务
    results = await asyncio.gather(
        task1(), 
        task_with_error(), 
        return_exceptions=True  # 异常作为结果返回
    )
    print(results)  # ['Task 1 done', ValueError('Something went wrong')]
asyncio.run(main())

完整示例

import asyncio
import time
async def worker(name, delay):
    print(f"Worker {name} started")
    await asyncio.sleep(delay)
    print(f"Worker {name} finished")
    return f"Result from {name}"
async def main():
    start = time.time()
    # 创建多个协程
    tasks = [
        worker("A", 2),
        worker("B", 1),
        worker("C", 3),
        worker("D", 1.5)
    ]
    # 等待所有完成
    results = await asyncio.gather(*tasks)
    print(f"All tasks completed in {time.time() - start:.2f} seconds")
    print(f"Results: {results}")
# 运行
asyncio.run(main())

选择建议

  • asyncio.gather(): 最常用,简单直接
  • asyncio.wait(): 需要超时控制或精细控制时
  • asyncio.as_completed(): 需要按完成顺序处理结果时
  • asyncio.create_task() + gather(): 当需要在创建任务后做其他操作时

在异步函数中,你必须使用 await 来等待协程完成,否则协程不会被执行。

抱歉,评论功能暂时关闭!