Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

asyncio.run

Creates and manages an event loop for a top-level asynchronous computation and returns its result.

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

Syntax

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

Creates and manages an event loop for a top-level asynchronous computation and returns its result.

The runner closes its loop after completion. It cannot start a second event loop in a thread that is already running one.

Use run at a synchronous entry point to drive an awaitable to completion and return its value. Python 3.14 accepts any awaitable, not only a coroutine. The runner finalizes async generators and shuts down the executor and loop. loop_factory can select a loop implementation. Nesting it in an already running loop in the same thread raises RuntimeError. The sample's top-level result is 11. debug=True enables loop debugging, False disables it, and None honors the global configuration. Shutdown closes the loop's default executor.

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)

Examples

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

print(asyncio.run(total()))

Result

11

Use run at a synchronous entry point to drive an awaitable to completion and return its value. Python 3.14 accepts any awaitable, not only a coroutine. The runner finalizes async generators and shuts down the executor and loop. loop_factory can select a loop implementation. Nesting it in an already running loop in the same thread raises RuntimeError. The sample's top-level result is 11. debug=True enables loop debugging, False disables it, and None honors the global configuration. Shutdown closes the loop's default executor.

Sources