Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 709
DuckQueen Avatar asked Jun 17 '26 09:06

DuckQueen


2 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.

like image 199
Yann Vernier Avatar answered Jun 19 '26 00:06

Yann Vernier


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.")
like image 45
BenVida Avatar answered Jun 18 '26 22:06

BenVida