Python asyncio force timeout

前端 未结 3 1656
旧时难觅i
旧时难觅i 2020-12-10 05:17

Using asyncio a coroutine can be executed with a timeout so it gets cancelled after the timeout:

@asyncio.coroutine
def coro():
    yield from asyncio.sleep(         


        
3条回答
  •  暖寄归人
    2020-12-10 06:13

    Thx @dano for your answer. If running a coroutine is not a hard requirement, here is a reworked, more compact version

    import asyncio, time
    
    timeout = 0.5
    loop = asyncio.get_event_loop()
    future = asyncio.wait_for(loop.run_in_executor(None, time.sleep, 2), timeout)
    try:
        loop.run_until_complete(future)
        print('Thx for letting me sleep')
    except asyncio.exceptions.TimeoutError:
        print('I need more sleep !')
    

    For the curious, a little debugging in my Python 3.8.2 showed that passing None as an executor results in the creation of a _default_executor, as follows:

    self._default_executor = concurrent.futures.ThreadPoolExecutor()
    

提交回复
热议问题