Asyncio Python的超时上下文管理器
aiotimeout的Python项目详细描述
艾奥蒂梅奥特
Asyncio Python的超时上下文管理器
用法
fromaiotimeoutimporttimeout# Will raise an asyncio.TimeoutErrorwithtimeout(1):awaitasyncio.sleep(1.5)# Will not raise anythingwithtimeout(1):awaitasyncio.sleep(0.5)
您可以通过捕获asyncio.TimeoutError
try:withtimeout(1):awaitasyncio.sleep(1.5)print('This line is not reached')exceptasyncio.TimeoutError:print('Timed out')
或者,您可以通过捕获asyncio.CancelledError
并重新引发来响应上下文中的超时。
try:withtimeout(1):try:awaitasyncio.sleep(1.5)exceptasyncio.CancelledErrorprint('Doing some cleanup')raiseexceptasyncio.TimeoutError:print('Timed out')
与备选方案的差异
asyncio.wait_for
不提供上下文管理器。在某些情况下,上下文管理器更清晰。asyncio.wait_for
创建/使用额外的任务。在某些情况下,这是不必要的,而且额外的任务在操作序列方面增加了非确定性。更清晰的内部代码[在作者看来]。使用contextlib.contextmanager而不是自定义类。