Await only for some time in Python

Question:

So waiting for server can bring pain:

    import asyncio 
    #...
    greeting = await websocket.recv() # newer ends

I want to have something like

    greeting = await websocket.recv() for seconds(10)

So how to await only for a limited amount of time in Python?

Asked By: DuckQueen

||

Answers:

await expressions don’t have a timeout parameter, but the asyncio.wait_for (thanks to AChampion) function does. My guess is that this is so that the await expression, tied to coroutine definition in the language itself, does not rely on having clocks or a specific event loop. That functionality is left to the asyncio module of the standard library.

Answered By: Yann Vernier

I use this in a try: except: block,

time_seconds = 60
try:
    result = await asyncio.wait_for(websocket.recv(), timeout=time_seconds)
    print(result)
    
except Exception as e:
    if str(type(e)) == "<class 'asyncio.exceptions.TimeoutError'>": 
        print('specifically a asyncio TimeoutError') 
    else:
        Print('different error:', e)

if the timeout occurs before the message is received, then one gets a TimeoutError error.

The timeout error is this:

<class 'asyncio.exceptions.TimeoutError'>

which you can then handle differently from other genuine errors.

Answered By: D.L

There’s actually an official way to accomplish a timeout for a co-routine without any hacking.

It’s described here: https://docs.python.org/3/library/asyncio-task.html?highlight=wait_for#asyncio.timeout

try:
    async with asyncio.timeout(10):
        result=await long_running_task()
except TimeoutError:
    print("The long operation timed out, but we've handled it.")
Answered By: BenVida
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.