CKTIS / Python
asyncio.wait_for
Attend une opération avec une limite en secondes ou sans limite avec None.
Version : Python 3.14; repository image, production runtime not attested
Syntaxe
await asyncio.wait_for(aw, timeout)Attend une opération avec une limite en secondes ou sans limite avec None.
À expiration demande l’annulation et attend son traitement, le nettoyage peut donc dépasser la limite. Une annulation propagée donne TimeoutError, mais si elle est interceptée et qu’une valeur est renvoyée, cette valeur peut être obtenue.
Ici zéro annule la tâche et le second appel renvoie 9.
import asyncio
async def main():
start = asyncio.Event()
async def recover():
start.set()
try:
await asyncio.Event().wait()
except asyncio.CancelledError:
return 7
t = asyncio.create_task(recover())
await start.wait()
assert await asyncio.wait_for(t, 0) == 7
assert await asyncio.wait_for(asyncio.sleep(0, result=9), None) == 9
asyncio.run(main())
Exemples
import asyncio
async def main():
task = asyncio.create_task(asyncio.Event().wait())
try:
await asyncio.wait_for(task, timeout=0)
except TimeoutError:
print(task.cancelled())
print(await asyncio.wait_for(asyncio.sleep(0, result=9), timeout=5))
asyncio.run(main())
Résultat
True 9
Ici zéro annule la tâche et le second appel renvoie 9.