CKTIS / Python
asyncio.wait
Erwartet eine nichtleere Sammlung von Tasks oder Futures.
Version: Python 3.14; repository image, production runtime not attested
Syntax
await asyncio.wait(aws, *, timeout=None, return_when=asyncio.ALL_COMPLETED)Erwartet eine nichtleere Sammlung von Tasks oder Futures.
Bloße Koroutinenobjekte werden abgewiesen. return_when wählt ersten Abschluss, erste Ausnahme oder alle Abschlüsse. Beim Zeitlimit kommen die Mengen done und pending ohne TimeoutError und ohne Abbruch zurück.
Im Beispiel ist ein Task fertig, der zweite wartet auf die Freigabe.
import asyncio
async def main():
loop = asyncio.get_running_loop()
a, b = loop.create_future(), loop.create_future()
a.set_result(2)
done, pending = await asyncio.wait([a, b], return_when=asyncio.FIRST_COMPLETED)
assert done == {a} and pending == {b} and not b.cancelled()
b.cancel()
try:
await asyncio.wait([])
except ValueError:
pass
else:
raise AssertionError
asyncio.run(main())
Beispiele
import asyncio
async def main():
gate = asyncio.Event()
pending_task = asyncio.create_task(gate.wait())
finished = asyncio.create_task(asyncio.sleep(0, result=5))
await finished
done, pending = await asyncio.wait([finished, pending_task], timeout=0)
print(len(done), len(pending), pending_task.cancelled())
gate.set()
await pending_task
asyncio.run(main())
Ergebnis
1 1 False
Im Beispiel ist ein Task fertig, der zweite wartet auf die Freigabe.