python异步编程,协程

python异步编程,协程

Python的协程通过在单线程事件循环中碰到await关键字切换执行以最大化的利用资源,避免阻塞等待,且避免了线程和进程上下文切换带来的资源消耗,且无需考虑临界互斥问题。

针对python异步编程中几个常用的api做了总结梳理。

python 复制代码
import asyncio
import random
import traceback
from asyncio import Task
from typing import TypeVar, Union, Tuple, Set

T = TypeVar('T')


async def exception_task(val):
    await asyncio.sleep(random.randint(1, 10))
    if val % 2:
        raise ValueError(val)
    return val


async def as_completed():
    coroutines = [asyncio.create_task(exception_task(_)) for _ in range(10)]
    # as_completed返回一个生成器,一旦有协程执行完毕即返回,不保证顺序
    for coroutine in asyncio.as_completed(coroutines, timeout=20):
        try:
            result = await coroutine
            print(result)
        except BaseException:
            traceback.print_exc()


async def gather():
    # 如果列表中的协程没有await, 不会报警告
    coroutines = [asyncio.create_task(exception_task(_)) for _ in range(10)]

    # 如果列表中的协程没有await, 报警告, 除非手动close
    coroutines = [exception_task(i) for i in coroutines]
    # 手动close
    # for i in coroutines:
    #     i.close()

    # 按顺序返回协程运行的结果
    # return_exception为False, 协程中的异常直接抛出到此行代码,如果想要程序不崩溃,需要try该行代码
    results: Tuple[T, ...] = await asyncio.gather(*coroutines, return_exceptions=False)

    # 返回结果可能是异常对象和协程执行结果
    results: Tuple[Union[T, BaseException], ...] = await asyncio.gather(*coroutines, return_exceptions=True)
    for result in results:
        if isinstance(result, BaseException):
            print(result)
        else:
            print(result)


async def wait_return_fisrt():
    coroutines = [asyncio.create_task(exception_task(_)) for _ in range(10)]

    # 第一个协程执行完开始返回,返回结果为Future
    while True:
        status = await asyncio.wait(coroutines, return_when=asyncio.FIRST_COMPLETED)
        done: Set[Task[T]] = status[0]
        pending: Set[Task[T]] = status[1]
        print(len(pending), len(done))
        if len(pending) == 0:
            break

    for x in done:
        # 如果发生异常,必须调用此函数,否则未处理异常会被抛出
        if x.exception():
            print(f'Exception: {x.exception()}')
        else:
            print(x.result())


async def wait_first_exception():
    coroutines = [asyncio.create_task(exception_task(_)) for _ in range(10)]
    while True:
        done, pending = await asyncio.wait(coroutines, return_when=asyncio.FIRST_EXCEPTION)
        print(len(done), len(pending))
        if len(pending) == 0:
            break
    for x in done:
        if x.exception():
            print(f'Exception: {x.exception()}')
        else:
            print(x.result())


async def wait_all_completed():
    coroutines = [asyncio.create_task(exception_task(_)) for _ in range(10)]
    done, _ = await asyncio.wait(coroutines, return_when=asyncio.ALL_COMPLETED)
    for x in done:
        if x.exception():
            print(f'Exception: {x.exception()}')
        else:
            print(x.result())


if __name__ == '__main__':
    try:
        asyncio.run(wait_first_exception())
    except KeyboardInterrupt:
        print('Interrupted')
    except Exception as e:
        print('Exception')
        raise e
  1. 无法在协程中捕获KeyboardInterrupt异常,只能在协程外捕获,捕获之后可以做一些清理工作,比如将没有await的协程close。
  2. gather方法的封装层次较高,用于仅关心协程执行结果的情况,返回结果是按原顺序的
    • return_exceptions为False,任一协程抛出异常后无法拿到任何协程的执行结果,且需要在协程外捕获异常,否则程序崩溃。
    • return_exceptions为True,返回结果为Tuple[Union[T, BaseException]],需要判断返回结果的类型。
  3. as_completed,返回一个生成器,该生成器尽快地返回已经执行完的Future对象,没有顺序,可设置超时时间。
  4. wait,返回结果为Tuple[Set[Task[T]],Set[Task[T]]],可被多次调用,不断更新已完成的协程集合和未完成的协程集合,不保证顺序,可设置超时时间。
    • return_when=ALL_COMPLETED,所有协程执行完毕后返回,此时未完成的协程集合一定为空,需要使用result方法或者exception方法获取协程的执行结果。
    • return_when=FIRST_COMPLETED,当有协程执行完毕后返回,重复调用wait方法不断更新两个集合,需要使用result方法或者exception方法获取协程的执行结果。
    • return_when=FIRST_EXCEPTION,当有协程抛出异常后返回,否则直到所有协程执行完毕后返回,重复调用wait方法不断更新两个集合,需要使用result方法或者exception方法获取协程的执行结果。
相关推荐
专注API从业者9 分钟前
Open Claw 京东商品监控选品实战:一键抓取、实时监控、高效选品
java·服务器·数据库
CHANG_THE_WORLD25 分钟前
python 批量终止进程exe
开发语言·python
摇滚侠26 分钟前
DBeaver 导入数据库 导入 SQL 文件 MySQL 备份恢复
java·数据库·mysql
古城小栈27 分钟前
从 cargo-whero 库中,找到提升 rust 的契机
开发语言·后端·rust
liann11932 分钟前
3.2_红队攻击框架--MITRE ATT&CK‌
python·网络协议·安全·网络安全·系统安全·信息与通信
云天AI实战派42 分钟前
AI 智能体问题排查指南:ChatGPT、API 调用到 Agent 上线失灵的全流程修复手册
大数据·人工智能·python·chatgpt·aigc
keep one's resolveY1 小时前
SpringBoot实现重试机制的四种方案
java·spring boot·后端
我的xiaodoujiao1 小时前
API 接口自动化测试详细图文教程学习系列15--项目实战演练2
python·学习·测试工具·pytest
天空属于哈夫克31 小时前
企业微信API常见的错误和解决方案
java·数据库·企业微信
Gary Studio2 小时前
安卓HAL C++基础-智能指针
开发语言·c++