cpython/Doc/library/asyncio.rst

130 lines
3.2 KiB
ReStructuredText
Raw Normal View History

:mod:`!asyncio` --- Asynchronous I/O
====================================
.. module:: asyncio
:synopsis: Asynchronous I/O.
-------------------------------
.. sidebar:: Hello World!
::
import asyncio
async def main():
print('Hello ...')
await asyncio.sleep(1)
print('... World!')
asyncio.run(main())
asyncio is a library to write **concurrent** code using
the **async/await** syntax.
asyncio is used as a foundation for multiple Python asynchronous
frameworks 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-level
**structured** network code.
gh-137026: Add an explainer guide for asyncio (GH-137215) * - Add an explainer guide (aka HOWTO, not how-to) for asyncio. * Fix linter errors. * - Enforce max line length of roughly 79 chars. - Start sentences on new lines to minimize disruption of diffs. * Add reference to subinterpreters. * - Significantly reduce article size. Remove both example sections & "Which concurrency do I want" section. * Align section-header lengths with section names. * - Remove reference to deleted section. * - Fix a variety of rote style guide items like title-alignment, use of ie and $, and so forth. - Add links to other parts of the docs for keywords and objects like await, coro, task, future, etc. * - One last title alignment. * - Style nit. * - Rework a variety of I statements. * Lint fix. * - Firm up commentary on yield from in corotuines. * Update language comparing await and yield from. * - Remove await-ing Tasks and futures section * Update Doc/howto/a-conceptual-overview-of-asyncio.rst Co-authored-by: Peter Bierma <zintensitydev@gmail.com> * Update Doc/howto/a-conceptual-overview-of-asyncio.rst Co-authored-by: Peter Bierma <zintensitydev@gmail.com> * - Address comments related to style & writing flow. * per-thread event loop note. * Add section describing coroutines roots in generators. * Phrasing tweak. * Use asyncio.create_task instead of asyncio.Task * Update Doc/howto/a-conceptual-overview-of-asyncio.rst Co-authored-by: Peter Bierma <zintensitydev@gmail.com> * Update Doc/howto/a-conceptual-overview-of-asyncio.rst Co-authored-by: Peter Bierma <zintensitydev@gmail.com> * small phrasing. * Update Doc/howto/a-conceptual-overview-of-asyncio.rst Co-authored-by: Peter Bierma <zintensitydev@gmail.com> * phrasing nit. * style nits * Update Doc/howto/a-conceptual-overview-of-asyncio.rst Co-authored-by: Peter Bierma <zintensitydev@gmail.com> * phrasing nit * Fix misnaming of async generator. * phrasing nits. * Update Doc/howto/a-conceptual-overview-of-asyncio.rst Co-authored-by: Peter Bierma <zintensitydev@gmail.com> * Update Doc/howto/a-conceptual-overview-of-asyncio.rst Co-authored-by: Peter Bierma <zintensitydev@gmail.com> * consistent spacing * Update Doc/howto/a-conceptual-overview-of-asyncio.rst Co-authored-by: Peter Bierma <zintensitydev@gmail.com> * phrasing nits * Update Doc/howto/a-conceptual-overview-of-asyncio.rst Co-authored-by: Peter Bierma <zintensitydev@gmail.com> * Update Doc/howto/a-conceptual-overview-of-asyncio.rst Co-authored-by: Peter Bierma <zintensitydev@gmail.com> * Update Doc/howto/a-conceptual-overview-of-asyncio.rst Co-authored-by: Peter Bierma <zintensitydev@gmail.com> * Update Doc/howto/a-conceptual-overview-of-asyncio.rst Co-authored-by: Peter Bierma <zintensitydev@gmail.com> * add conclusion * nits * - Variety of style & grammar improvements thanks to ZeroIntensity's comments. * - Make all directives start with a 3 space indent. Then 4 thereafter. * - Use :linenos: instead of manually writing the line numbers. * - Fix label typo for article. * fix label link. * Apply suggestions from code review Co-authored-by: 🇺🇦 Sviatoslav Sydorenko (Святослав Сидоренко) <wk.cvs.github@sydorenko.org.ua> Co-authored-by: Carol Willing <carolcode@willingconsulting.com> Co-authored-by: Peter Bierma <zintensitydev@gmail.com> * - introduce async-sleep name * Phrasing * nit * ungendered octopus * teammates * jobs * rework fella to penguin * - remove byline; add seealso * Change ref from asyncio to use seealso block. * Remove typehints. Fix indentation in one code example. * Slight rephrase for clarity. * Make references point to asyncio. Wrap some long lines. * - Variety of style/phrasing improvements based on PR feedback. * phrasing. * phrasing nit. * Apply suggestions from code review Co-authored-by: Peter Bierma <zintensitydev@gmail.com> * Update Doc/howto/a-conceptual-overview-of-asyncio.rst Co-authored-by: Carol Willing <carolcode@willingconsulting.com> * nit * Apply suggestions from code review Co-authored-by: Carol Willing <carolcode@willingconsulting.com> * fix backticks. * nits * nit * add section on asyncio.run * title change under the hood. * modify task coro example. * howtos article link. * prefer await without backticks. * phrasing tweak. * Rework phrasing around how await tasks pauses and returns control in the await section. * move code block to beforfe explanation in coroutine under the hood. * phrasing. * link to yield from. * style nits * nit * - Modify language re: event-loop cycling endlessly. - Discuss why await was designed to not yield for coros. * - Add a note about debug=True on asyncio.run to await coro section. * clarity nit * - Add two other references in seealso block. * nit * Language simplification * Apply suggestions from code review Co-authored-by: Peter Bierma <zintensitydev@gmail.com> * nit * grammar fix. * fix * worker bees * rework event loop paragraph to significantly deemphasize queues * remove all references to queue besides the initial analogy. * add note about garbage collection of tasks * add practical note re: garbage collection * phrasing nits * re arrange note on task gc. * line wrap nit * Update Doc/howto/a-conceptual-overview-of-asyncio.rst Co-authored-by: Kumar Aditya <kumaraditya@python.org> * link to debug mode docs. * readd part2 prefix. * simplify title. * fix titles. tihnk I messed this up earlier. * avoid idiom in title. * fix titles once agian. * Apply suggestions from code review Co-authored-by: Stan Ulbrych <89152624+StanFromIreland@users.noreply.github.com> * rework task gc example. * phrasing tweak. * tewak. * nit * nit * nit * nit --------- Co-authored-by: Peter Bierma <zintensitydev@gmail.com> Co-authored-by: 🇺🇦 Sviatoslav Sydorenko (Святослав Сидоренко) <wk.cvs.github@sydorenko.org.ua> Co-authored-by: Carol Willing <carolcode@willingconsulting.com> Co-authored-by: Kumar Aditya <kumaraditya@python.org> Co-authored-by: Stan Ulbrych <89152624+StanFromIreland@users.noreply.github.com>
2025-08-08 22:29:51 -07:00
.. seealso::
:ref:`a-conceptual-overview-of-asyncio`
Explanation of the fundamentals of asyncio.
asyncio provides a set of **high-level** APIs to:
* :ref:`run Python coroutines <coroutine>` concurrently and
have full control over their execution;
* perform :ref:`network IO and IPC <asyncio-streams>`;
* control :ref:`subprocesses <asyncio-subprocess>`;
* distribute tasks via :ref:`queues <asyncio-queues>`;
* :ref:`synchronize <asyncio-sync>` concurrent code;
Additionally, there are **low-level** APIs for
*library and framework developers* to:
* create and manage :ref:`event loops <asyncio-event-loop>`, which
provide asynchronous APIs for :ref:`networking <loop_create_server>`,
running :ref:`subprocesses <loop_subprocess_exec>`,
handling :ref:`OS signals <loop_add_signal_handler>`, etc;
* implement efficient protocols using
:ref:`transports <asyncio-transports-protocols>`;
* :ref:`bridge <asyncio-futures>` callback-based libraries and code
with async/await syntax.
.. include:: ../includes/wasm-notavail.rst
.. _asyncio-cli:
.. rubric:: asyncio REPL
You can experiment with an ``asyncio`` concurrent context in the :term:`REPL`:
.. code-block:: pycon
$ python -m asyncio
asyncio REPL ...
Use "await" directly instead of "asyncio.run()".
Type "help", "copyright", "credits" or "license" for more information.
>>> import asyncio
>>> await asyncio.sleep(10, result='hello')
'hello'
.. audit-event:: cpython.run_stdin "" ""
.. versionchanged:: 3.12.5 (also 3.11.10, 3.10.15, 3.9.20, and 3.8.20)
Emits audit events.
.. versionchanged:: 3.13
Uses PyREPL if possible, in which case :envvar:`PYTHONSTARTUP` is
also executed. Emits audit events.
.. We use the "rubric" directive here to avoid creating
the "Reference" subsection in the TOC.
.. rubric:: Reference
.. toctree::
:caption: High-level APIs
:maxdepth: 1
asyncio-runner.rst
asyncio-task.rst
asyncio-stream.rst
asyncio-sync.rst
asyncio-subprocess.rst
2015-02-25 13:55:43 +01:00
asyncio-queue.rst
asyncio-exceptions.rst
asyncio-graph.rst
.. toctree::
:caption: Low-level APIs
:maxdepth: 1
asyncio-eventloop.rst
asyncio-future.rst
asyncio-protocol.rst
asyncio-policy.rst
asyncio-platforms.rst
asyncio-extending.rst
.. toctree::
:caption: Guides and Tutorials
:maxdepth: 1
asyncio-api-index.rst
asyncio-llapi-index.rst
asyncio-dev.rst
.. note::
The source code for asyncio can be found in :source:`Lib/asyncio/`.