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方法获取协程的执行结果。
相关推荐
段一凡-华北理工大学2 小时前
工业智能体:从Codex/Claude到项目实战~系列文章05:从“AI助手“到“工业智能体“:能力跃迁与落地范式
人工智能·python·claude·codex·工业智能体·高炉炼铁智能化
独泪了无痕2 小时前
探索Pinyin4j-Java中的拼音转换利器
java·后端
深蓝AI2 小时前
ContextVar 到线程池就丢了?asyncio.to_thread 和 run_in_executor 实测
python
道尔柯南3 小时前
C++ string 类详解:从常用接口到深拷贝,彻底掌握字符串处理
android·java·c++
岁月宁静3 小时前
什么是 Agent:从"会聊天"到"会做事"
人工智能·python
岁月宁静4 小时前
AI 应用开发工程师简历怎么写:HR 初筛、技术复筛、面试追问,三道关卡各看什么?
人工智能·python·面试
来让爷抱一个4 小时前
Python 异步里混用同步库,事件循环被卡住的全过程
开发语言·python
kingx34 小时前
Bugku 3122 谷歌小恐龙题解:纯离线逆向 Vault 的 AES-GCM 加密资源(附 Python 解密器)
java·逆向·ctf·bugku·aes-gcm
小肝一下6 小时前
3.基础语法(3)
python
DevOpenClub6 小时前
职教高考控制线 API:招生类别枚举、筛选与空分数含义
java·数据库·高考