有没有办法找到多个定时器中的哪一个引发异常?

时间:2016-05-21 09:39:20

标签: python python-3.x python-asyncio aiohttp

 15     lxc_container:
 16       name: "{{item}}"
 17     with_items:
 18         - "{{container_list}}"
 19       container_command: |
 20         df -h
 21     register: memory_check
 22   - debug: msg="{{memory_check.stdout}}"

由于两个计时器都有相同的超时,因此它们都可以提升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()) 。我想知道哪一个做了。有可能吗?

1 个答案:

答案 0 :(得分:4)

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

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