DuckQueen
DuckQueen

Reputation: 800

Await only for some time in Python

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?

Upvotes: 8

Views: 6955

Answers (3)

BenVida
BenVida

Reputation: 2312

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.")

Upvotes: 5

darren
darren

Reputation: 5734

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.

Upvotes: 0

Yann Vernier
Yann Vernier

Reputation: 15887

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.

Upvotes: 8

Related Questions