Base de connaissancesCentre d’examen
FRFrançais
Choisir la langue13

CKTIS / Python

asyncio.wait

Prend une collection non vide de tâches ou de Future.

Version : Python 3.14; repository image, production runtime not attested

Syntaxe

await asyncio.wait(aws, *, timeout=None, return_when=asyncio.ALL_COMPLETED)

Prend une collection non vide de tâches ou de Future.

Les objets coroutines nus sont refusés. return_when choisit le premier achèvement, la première exception ou tous les achèvements. À expiration les ensembles done et pending sont renvoyés sans TimeoutError ni annulation.

Dans l’exemple une tâche a terminé et l’autre attend le signal.

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())

Exemples

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())

Résultat

1 1 False

Dans l’exemple une tâche a terminé et l’autre attend le signal.

Sources