Meaning
Creates a new asyncio event loop, runs the supplied coroutine to completion, then closes the loop — serving as the standard bridge from synchronous to asynchronous execution. Solves the bootstrapping problem where async code cannot run without an event loop but synchronous entry points have no loop running. Reach for this at any script's top level when you need to kick off an async program.
Primary Function
Running async coroutines
Communicative Purpose
Starts an asynchronous program from synchronous code.
Pattern
asyncio.run(coroutine)
Core Structure
asyncio.run(...)
Função primária
Running async coroutines
Propósito comunicativo
Starts an asynchronous program from synchronous code.
Situações de gatilho
CLI scripts: needing to execute an async main function from a synchronous entry point; Web scraping: running async HTTP fetchers from a standalone script; Data pipelines: orchestrating concurrent async tasks from a top-level runner
Contextos
Python asyncio applications, CLI tools, async web servers, scripts using async/await.
Padrão
asyncio.run(coroutine)
Estrutura central
asyncio.run(...)
Slots de substituição
coroutine: awaitable object (e.g., main() or another async function)
Colocados típicos
- async def main(): ...
- await statements
- asyncio.create_task
- asyncio.gather
Substituições comuns
- Using loop = asyncio.new_event_loop()
- loop.run_until_complete(main())
- loop.close() (older way) or asyncio.run(main()
- debug=True)
Erros comuns
Calling asyncio.run inside an already running event loop (nested loops); passing a regular function instead of a coroutine; forgetting to await inside main.
Similar / contraste
asyncio.create_task() (schedules a coroutine concurrently); asyncio.run_until_complete() (manual loop management). Distinction: asyncio.run creates a new loop and closes it.
Interferências
Coming from languages with threaded concurrency (e.g., Java): may expect asyncio.run to spawn threads; actually it runs single-threaded event loop.
Família do chunk
- asyncio event loop management
- async def main
- await
- asyncio.gather
Nuance
Cannot be called when another event loop is running (e.g., inside Jupyter notebooks or async GUI applications); in such contexts use await main() or nest_asyncio.
Efeito pragmático
Ensures proper cleanup of the asyncio event loop and resources, preventing resource leaks.
Dica de memória
Like pressing the ignition button on an async engine — it creates the event loop, runs your coroutine, then shuts everything down cleanly.
Nota
Only available in Python 3.7+; earlier versions require manual loop management via asyncio.new_event_loop() and loop.run_until_complete().
Upgrade path
asyncio.run(main(), debug=True) or using asyncio.TaskGroup in Python 3.11+
Log in to save chunks.