KennisbankExamencentrum
NL · NLNederlands (Nederland)
Taal kiezen13

CKTIS / Python

asyncio.run

Start asynchrone code vanuit een synchroon toegangspunt en geeft het resultaat terug.

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

Syntax

asyncio.run(coro, *, debug=None, loop_factory=None)

Start asynchrone code vanuit een synchroon toegangspunt en geeft het resultaat terug.

debug=True zet de foutopsporingsmodus aan, False zet die uit en None volgt de globale instelling. Bij afsluiten wordt de standaardexecutor van de lus gestopt. Vanaf 3.14 is ieder object dat await ondersteunt toegestaan. De runner rondt asynchrone generators af en sluit de executor en de lus die loop_factory kan maken. Nesten in een draaiende lus op dezelfde thread geeft RuntimeError.

Het voorbeeld berekent 11.

import asyncio
class Ready:
    def __await__(self):
        if False:
            yield
        return 11
assert asyncio.run(Ready()) == 11
async def main():
    try:
        asyncio.run(Ready())
    except RuntimeError:
        return True
assert asyncio.run(main()) is True
async def debug_state():
    return asyncio.get_running_loop().get_debug()
assert asyncio.run(debug_state(), debug=True)
assert not asyncio.run(debug_state(), debug=False)

Voorbeelden

import asyncio
async def total():
    await asyncio.sleep(0)
    return 3 + 8

print(asyncio.run(total()))

Resultaat

11

Het voorbeeld berekent 11.

Bronnen