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?
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.
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.")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With