python 协程任务结束,超时,多任务并行,异常

本文介绍了如何在Python中使用asyncio库进行异步编程,包括创建协程任务、取消未完成的任务、设置超时处理以及使用`asyncio.gather`并发执行任务并处理异常。
摘要由CSDN通过智能技术生成
import asyncio
from asyncio.exceptions import TimeoutError

async def play_music(music: str):
    print(f"{music} is started")
    await asyncio.sleep(3)
    print(f"{music} is finished")

    return music

async def call_api():
    print("call_api")
    raise Exception("it is a Exception")

# 将协程任务结束
async def my_cancel():
    task = asyncio.create_task(play_music("A music"))

    await asyncio.sleep(4)

    if not task.done():
        task.cancel()

# 协程任务超时退出 如果超时会抛出异常然后退出 TimeoutError 需要异常处理
async def my_cancel_timeout():
    task = asyncio.create_task(play_music("B music"))
    try:
        await asyncio.wait_for(task,timeout=2)
    except TimeoutError:
        print("timeout error!!")

# 协程任务超时抛出异常 但不退出任务继续执行 asyncio.shield函数保护task任务
async def my_timeout():
    task = asyncio.create_task(play_music("B music"))
    try:
        await asyncio.wait_for(asyncio.shield(task), timeout=2)
    except TimeoutError:
        print("timeout error!!")
        await task

# asyncio.gather 直接并行多个任务并等待结束,返回结果
async def my_gather():
    task = await asyncio.gather(play_music("A"),play_music("B"))
    print(task)

# 直接并行多个任务,并且并且捕捉异常,return_exceptions=True
async def my_gather_exception():
    task = await asyncio.gather(play_music("A"),play_music("B"),call_api(),return_exceptions=True)
    print(task)

if __name__ == "__main__":
    asyncio.run(my_gather_exception())

  • 10
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值