asyncio
— Asynchronous I/O¶
Hello World!
importasyncioasyncdefmain():print('Hello ...')awaitasyncio.sleep(1)print('... World!')asyncio.run(main())
asyncio is a library to writeconcurrent code usingtheasync/await syntax.
asyncio is used as a foundation for multiple Python asynchronousframeworks that provide high-performance network and web-servers,database connection libraries, distributed task queues, etc.
asyncio is often a perfect fit for IO-bound and high-levelstructured network code.
asyncio provides a set ofhigh-level APIs to:
run Python coroutines concurrently andhave full control over their execution;
performnetwork IO and IPC;
controlsubprocesses;
distribute tasks viaqueues;
synchronize concurrent code;
Additionally, there arelow-level APIs forlibrary and framework developers to:
create and manageevent loops, whichprovide asynchronous APIs fornetworking,runningsubprocesses,handlingOS signals, etc;
implement efficient protocols usingtransports;
bridge callback-based libraries and codewith async/await syntax.
Availability: not WASI.
This module does not work or is not available on WebAssembly. SeeWebAssembly platforms for more information.
asyncio REPL
You can experiment with anasyncio
concurrent context in theREPL:
$ python -m asyncioasyncio REPL ...Use "await" directly instead of "asyncio.run()".Type "help", "copyright", "credits" or "license" for more information.>>>importasyncio>>>awaitasyncio.sleep(10,result='hello')'hello'
Raises anauditing eventcpython.run_stdin
with no arguments.
Changed in version 3.12.5:(also 3.11.10, 3.10.15, 3.9.20, and 3.8.20)Emits audit events.
Changed in version 3.13:Uses PyREPL if possible, in which casePYTHONSTARTUP
isalso executed. Emits audit events.
Reference
High-level APIs
Guides and Tutorials
Note
The source code for asyncio can be found inLib/asyncio/.