gpt4 book ai didi

python - 有没有办法找到多个计时器中的哪一个引发了异常?

转载 作者:行者123 更新时间:2023-11-28 22:36:30 25 4
gpt4 key购买 nike

import asyncio
from aiohttp import Timeout


async def main():
try:
with Timeout(1) as t1:
with Timeout(1) as t2:
await asyncio.sleep(2)
except asyncio.TimeoutError as exc:

# Which one of timers raised this `exc`?
# Something like:

# get_caller(exc) is t1 -> False
# get_caller(exc) is t2 -> True

pass


if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(main())

因为两个计时器都有相同的超时时间,所以它们都可以引发 TimeoutError。我想知道是哪一个做的。可能吗?

最佳答案

async def main_async():
try:
with NamedTimeout('outer', 0.5) as t1:
with NamedTimeout('inner', 0.3) as t2:
await asyncio.sleep(2)
except asyncio.TimeoutError as e:
print(e.timeout_name)

class NamedTimeout(Timeout):
def __init__(self, name, timeout, *, loop=None):
super().__init__(timeout, loop=loop)
self.name = name

def __exit__(self, exc_type, exc_val, exc_tb):
try:
super().__exit__(exc_type, exc_val, exc_tb)
except asyncio.TimeoutError as e:
e.timeout_name = self.name
raise

如果您改变超时值,您会看到它总是打印出较短超时的名称。

关于python - 有没有办法找到多个计时器中的哪一个引发了异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37361240/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com