当前位置: 首页 > Python编程 > Python编程实战技能 > Python编程技术分享 > 深究Python中的asyncio库-shield函数

深究Python中的asyncio库-shield函数

发布时间:2020年09月27日 08:36:16 来源: 点击量:652

【摘要】shieldasyncio shield,用它可以屏蔽取消操作。一直到这里,我们还没有见识过Task的取消。看一个例子:In:loop=asyncio get_event_loop() In

shield

asyncio.shield,用它可以屏蔽取消操作。一直到这里,我们还没有见识过Task的取消。

看一个例子:

In : loop = asyncio.get_event_loop()
In : task1 = loop.create_task(a())
In : task2 = loop.create_task(b())
In : task1.cancel()
Out: True
In : await asyncio.gather(task1, task2)
Suspending a
Suspending b
---------------------------------------------------------------------------
CancelledError                            Traceback (most recent call last)
cell_name in async-def-wrapper()
CancelledError:

在上面的例子中,task1被取消了后再用asyncio.gather收集结果,直接抛CancelledError错误了。这里有个细节,gather支持return_exceptions参数:

In : await asyncio.gather(task1, task2, return_exceptions=True)
Out: [concurrent.futures._base.CancelledError(), 'B']

可以看到,task2依然会执行完成,但是task1的返回值是一个CancelledError错误,也就是任务被取消了。如果一个创建后就不希望被任何情况取消,可以使用asyncio.shield保护任务能顺利完成。不过要注意一个陷阱,先看错误的写法:

In : task1 = asyncio.shield(a())
In : task2 = loop.create_task(b())
In : task1.cancel()
Out: True
In : await asyncio.gather(task1, task2, return_exceptions=True)
Suspending a
Suspending b
Resuming b
Out: [concurrent.futures._base.CancelledError(), 'B']

可以看到依然是CancelledError错误,且协程a未执行完成,正确的用法是这样的:

In : task1 = asyncio.shield(a())
In : task2 = loop.create_task(b())
In : ts = asyncio.gather(task1, task2, return_exceptions=True)
In : task1.cancel()
Out: True
In : await ts
Suspending a
Suspending b
Resuming a
Resuming b
Out: [concurrent.futures._base.CancelledError(), 'B']

可以看到虽然结果是一个CancelledError错误,但是看输出能确认协程实际上是执行了的。所以正确步骤是:

先创建 GatheringFuture 对象 ts

取消任务

await ts

asynccontextmanager

如果你了解Python,之前可能听过或者用过contextmanager ,一个上下文管理器。通过一个计时的例子就理解它的作用:

from contextlib import contextmanager
async def a():
    await asyncio.sleep(3)
    return 'A'
async def b():
    await asyncio.sleep(1)
    return 'B'
async def s1():
    return await asyncio.gather(a(), b())
@contextmanager
def timed(func):
    start = time.perf_counter()
    yield asyncio.run(func())
    print(f'Cost: {time.perf_counter() - start}')

timed函数用了contextmanager装饰器,把协程的运行结果yield出来,执行结束后还计算了耗时:

In : from contextmanager import *
In : with timed(s1) as rv:
...:     print(f'Result: {rv}')
...:
Result: ['A', 'B']
Cost: 3.0052654459999992

大家先体会一下。在Python 3.7添加了asynccontextmanager,也就是异步版本的contextmanager,适合异步函数的执行,上例可以这么改:

@asynccontextmanager
async def async_timed(func):
    start = time.perf_counter()
    yield await func()
    print(f'Cost: {time.perf_counter() - start}')
async def main():
    async with async_timed(s1) as rv:
        print(f'Result: {rv}')
In : asyncio.run(main())
Result: ['A', 'B']
Cost: 3.00414147500004

async版本的with要用async with,另外要注意yield await func()这句,相当于yield + await func()

PS: contextmanager 和 asynccontextmanager 最好的理解方法是去看源码注释

下一节:深究Python中的asyncio库-函数的回调与调度

分享到: 编辑:wangmin

就业培训申请领取
您的姓名
您的电话
意向课程
点击领取

环球青藤

官方QQ

扫描上方二维码或点击一键加群,免费领取大礼包,加群暗号:青藤。 一键加群

绑定手机号

应《中华人民共和国网络安全法》加强实名认证机制要求,同时为更加全面的体验产品服务,烦请您绑定手机号.

预约成功

本直播为付费学员的直播课节

请您购买课程后再预约

环球青藤移动课堂APP 直播、听课。职达未来!

安卓版

下载

iPhone版

下载
环球青藤官方微信服务平台

刷题看课 APP下载

免费直播 一键购课

代报名等人工服务

课程咨询 学员服务 公众号

扫描关注微信公众号

APP

扫描下载APP

返回顶部