> **Источник:** https://python-all.ru/3.5/library/asyncio.html
>
> «Документация Python на русском» – неофициальный перевод официальной документации Python: версии от 2.6 до 3.16, полнотекстовый поиск, английский оригинал рядом с переводом. Эта Markdown-версия страницы предназначена для работы с LLM: вставьте её в ChatGPT, Claude или Cursor.

---

# 18.5. [`asyncio`](https://python-all.ru/3.5/library/asyncio.html#module-asyncio) – Асинхронный ввод-вывод, цикл событий, корутины и задачи

Новое в версии 3.4.

**Исходный код:** [Lib/asyncio/](https://python-all.ru/src/3.5/Lib/asyncio)

> **Примечание**
>
> Пакет asyncio был включен в стандартную библиотеку на [временной основе](https://python-all.ru/3.5/glossary.html#term-provisional-package). Обратно несовместимые изменения (вплоть до удаления модуля) могут быть внесены, если основные разработчики сочтут это необходимым.

---

Этот модуль предоставляет инфраструктуру для написания однопоточного конкурентного кода с использованием корутин, мультиплексирования доступа к вводу-выводу через сокеты и другие ресурсы, запуска сетевых клиентов и серверов, а также других связанных примитивов. Ниже приведён более подробный список содержимого пакета:

- подключаемый [цикл событий](https://python-all.ru/3.5/library/asyncio-eventloop.html#asyncio-event-loop) с различными системно-зависимыми реализациями;
- [транспорт](https://python-all.ru/3.5/library/asyncio-protocol.html#asyncio-transport) и [протокол](https://python-all.ru/3.5/library/asyncio-protocol.html#asyncio-protocol) абстракции (аналогичные тем, что в [Twisted](https://python-all.ru/3.5/library/asyncio.html));
- конкретная поддержка TCP, UDP, SSL, каналов подпроцессов, отложенных вызовов и других (некоторые могут быть системно-зависимыми);
- класс [`Future`](https://python-all.ru/3.5/library/asyncio-task.html#asyncio.Future), который повторяет класс из модуля [`concurrent.futures`](https://python-all.ru/3.5/library/concurrent.futures.html#module-concurrent.futures), но адаптирован для использования с циклом событий;
- корутины и задачи на основе `yield from` ([**PEP 380**](https://python-all.ru/3.5/library/asyncio.html)), для написания конкурентного кода в последовательном стиле;
- поддержка отмены для [`Future`](https://python-all.ru/3.5/library/asyncio-task.html#asyncio.Future)s и корутин;
- [примитивы синхронизации](https://python-all.ru/3.5/library/asyncio-sync.html#asyncio-sync) для использования между корутинами в одном потоке, по аналогии с теми, что в модуле [`threading`](https://python-all.ru/3.5/library/threading.html#module-threading);
- интерфейс для передачи работы в пул потоков на случай, когда абсолютно необходимо использовать библиотеку, выполняющую блокирующие вызовы ввода-вывода.

Асинхронное программирование сложнее классического «последовательного» программирования: см. страницу [Разработка с asyncio](https://python-all.ru/3.5/library/asyncio-dev.html#asyncio-dev), где перечислены распространённые ловушки и объясняется, как их избежать. [Включите режим отладки](https://python-all.ru/3.5/library/asyncio-dev.html#asyncio-debug-mode) при разработке, чтобы выявлять типичные проблемы.

Содержание:

- [18.5.1. Базовый цикл событий](https://python-all.ru/3.5/library/asyncio-eventloop.html)

  - [18.5.1.1. Запуск цикла событий](https://python-all.ru/3.5/library/asyncio-eventloop.html#run-an-event-loop)
  - [18.5.1.2. Вызовы](https://python-all.ru/3.5/library/asyncio-eventloop.html#calls)
  - [18.5.1.3. Отложенные вызовы](https://python-all.ru/3.5/library/asyncio-eventloop.html#delayed-calls)
  - [18.5.1.4. Future](https://python-all.ru/3.5/library/asyncio-eventloop.html#futures)
  - [18.5.1.5. Задачи](https://python-all.ru/3.5/library/asyncio-eventloop.html#tasks)
  - [18.5.1.6. Создание подключений](https://python-all.ru/3.5/library/asyncio-eventloop.html#creating-connections)
  - [18.5.1.7. Создание прослушивающих подключений](https://python-all.ru/3.5/library/asyncio-eventloop.html#creating-listening-connections)
  - [18.5.1.8. Наблюдение за файловыми дескрипторами](https://python-all.ru/3.5/library/asyncio-eventloop.html#watch-file-descriptors)
  - [18.5.1.9. Низкоуровневые операции с сокетами](https://python-all.ru/3.5/library/asyncio-eventloop.html#low-level-socket-operations)
  - [18.5.1.10. Разрешение имени хоста](https://python-all.ru/3.5/library/asyncio-eventloop.html#resolve-host-name)
  - [18.5.1.11. Подключение каналов](https://python-all.ru/3.5/library/asyncio-eventloop.html#connect-pipes)
  - [18.5.1.12. Сигналы UNIX](https://python-all.ru/3.5/library/asyncio-eventloop.html#unix-signals)
  - [18.5.1.13. Исполнитель](https://python-all.ru/3.5/library/asyncio-eventloop.html#executor)
  - [18.5.1.14. API обработки ошибок](https://python-all.ru/3.5/library/asyncio-eventloop.html#error-handling-api)
  - [18.5.1.15. Режим отладки](https://python-all.ru/3.5/library/asyncio-eventloop.html#debug-mode)
  - [18.5.1.16. Сервер](https://python-all.ru/3.5/library/asyncio-eventloop.html#server)
  - [18.5.1.17. Handle](https://python-all.ru/3.5/library/asyncio-eventloop.html#handle)
  - [18.5.1.18. Примеры циклов событий](https://python-all.ru/3.5/library/asyncio-eventloop.html#event-loop-examples)

    - [18.5.1.18.1. Hello World с call\_soon()](https://python-all.ru/3.5/library/asyncio-eventloop.html#hello-world-with-call-soon)
    - [18.5.1.18.2. Отображение текущей даты с call\_later()](https://python-all.ru/3.5/library/asyncio-eventloop.html#display-the-current-date-with-call-later)
    - [18.5.1.18.3. Наблюдение за файловым дескриптором на события чтения](https://python-all.ru/3.5/library/asyncio-eventloop.html#watch-a-file-descriptor-for-read-events)
    - [18.5.1.18.4. Установка обработчиков сигналов SIGINT и SIGTERM](https://python-all.ru/3.5/library/asyncio-eventloop.html#set-signal-handlers-for-sigint-and-sigterm)
- [18.5.2. Циклы событий](https://python-all.ru/3.5/library/asyncio-eventloops.html)

  - [18.5.2.1. Функции цикла событий](https://python-all.ru/3.5/library/asyncio-eventloops.html#event-loop-functions)
  - [18.5.2.2. Доступные циклы событий](https://python-all.ru/3.5/library/asyncio-eventloops.html#available-event-loops)
  - [18.5.2.3. Поддержка платформ](https://python-all.ru/3.5/library/asyncio-eventloops.html#platform-support)

    - [18.5.2.3.1. Windows](https://python-all.ru/3.5/library/asyncio-eventloops.html#windows)
    - [18.5.2.3.2. Mac OS X](https://python-all.ru/3.5/library/asyncio-eventloops.html#mac-os-x)
  - [18.5.2.4. Политики цикла событий и политика по умолчанию](https://python-all.ru/3.5/library/asyncio-eventloops.html#event-loop-policies-and-the-default-policy)
  - [18.5.2.5. Интерфейс политики цикла событий](https://python-all.ru/3.5/library/asyncio-eventloops.html#event-loop-policy-interface)
  - [18.5.2.6. Доступ к глобальной политике цикла событий](https://python-all.ru/3.5/library/asyncio-eventloops.html#access-to-the-global-loop-policy)
- [18.5.3. Задачи и корутины](https://python-all.ru/3.5/library/asyncio-task.html)

  - [18.5.3.1. Корутины](https://python-all.ru/3.5/library/asyncio-task.html#coroutines)

    - [18.5.3.1.1. Пример: корутина «Hello World»](https://python-all.ru/3.5/library/asyncio-task.html#example-hello-world-coroutine)
    - [18.5.3.1.2. Пример: корутина, отображающая текущую дату](https://python-all.ru/3.5/library/asyncio-task.html#example-coroutine-displaying-the-current-date)
    - [18.5.3.1.3. Пример: цепочка корутин](https://python-all.ru/3.5/library/asyncio-task.html#example-chain-coroutines)
  - [18.5.3.2. InvalidStateError](https://python-all.ru/3.5/library/asyncio-task.html#invalidstateerror)
  - [18.5.3.3. TimeoutError](https://python-all.ru/3.5/library/asyncio-task.html#timeouterror)
  - [18.5.3.4. Future](https://python-all.ru/3.5/library/asyncio-task.html#future)

    - [18.5.3.4.1. Пример: Future с run\_until\_complete()](https://python-all.ru/3.5/library/asyncio-task.html#example-future-with-run-until-complete)
    - [18.5.3.4.2. Пример: Future с run\_forever()](https://python-all.ru/3.5/library/asyncio-task.html#example-future-with-run-forever)
  - [18.5.3.5. Задача](https://python-all.ru/3.5/library/asyncio-task.html#task)

    - [18.5.3.5.1. Пример: параллельное выполнение задач](https://python-all.ru/3.5/library/asyncio-task.html#example-parallel-execution-of-tasks)
  - [18.5.3.6. Функции задач](https://python-all.ru/3.5/library/asyncio-task.html#task-functions)
- [18.5.4. Транспорты и протоколы (API на основе колбэков)](https://python-all.ru/3.5/library/asyncio-protocol.html)

  - [18.5.4.1. Транспорты](https://python-all.ru/3.5/library/asyncio-protocol.html#transports)

    - [18.5.4.1.1. BaseTransport](https://python-all.ru/3.5/library/asyncio-protocol.html#basetransport)
    - [18.5.4.1.2. ReadTransport](https://python-all.ru/3.5/library/asyncio-protocol.html#readtransport)
    - [18.5.4.1.3. WriteTransport](https://python-all.ru/3.5/library/asyncio-protocol.html#writetransport)
    - [18.5.4.1.4. DatagramTransport](https://python-all.ru/3.5/library/asyncio-protocol.html#datagramtransport)
    - [18.5.4.1.5. BaseSubprocessTransport](https://python-all.ru/3.5/library/asyncio-protocol.html#basesubprocesstransport)
  - [18.5.4.2. Протоколы](https://python-all.ru/3.5/library/asyncio-protocol.html#protocols)

    - [18.5.4.2.1. Классы протоколов](https://python-all.ru/3.5/library/asyncio-protocol.html#protocol-classes)
    - [18.5.4.2.2. Колбэки соединения](https://python-all.ru/3.5/library/asyncio-protocol.html#connection-callbacks)
    - [18.5.4.2.3. Потоковые протоколы](https://python-all.ru/3.5/library/asyncio-protocol.html#streaming-protocols)
    - [18.5.4.2.4. Протоколы датаграмм](https://python-all.ru/3.5/library/asyncio-protocol.html#datagram-protocols)
    - [18.5.4.2.5. Колбэки управления потоком](https://python-all.ru/3.5/library/asyncio-protocol.html#flow-control-callbacks)
    - [18.5.4.2.6. Корутины и протоколы](https://python-all.ru/3.5/library/asyncio-protocol.html#coroutines-and-protocols)
  - [18.5.4.3. Примеры протоколов](https://python-all.ru/3.5/library/asyncio-protocol.html#protocol-examples)

    - [18.5.4.3.1. Протокол TCP-эхо-клиента](https://python-all.ru/3.5/library/asyncio-protocol.html#tcp-echo-client-protocol)
    - [18.5.4.3.2. Протокол TCP-эхо-сервера](https://python-all.ru/3.5/library/asyncio-protocol.html#tcp-echo-server-protocol)
    - [18.5.4.3.3. Протокол UDP-эхо-клиента](https://python-all.ru/3.5/library/asyncio-protocol.html#udp-echo-client-protocol)
    - [18.5.4.3.4. Протокол UDP-эхо-сервера](https://python-all.ru/3.5/library/asyncio-protocol.html#udp-echo-server-protocol)
    - [18.5.4.3.5. Регистрация открытого сокета для ожидания данных через протокол](https://python-all.ru/3.5/library/asyncio-protocol.html#register-an-open-socket-to-wait-for-data-using-a-protocol)
- [18.5.5. Потоки данных (API на корутинах)](https://python-all.ru/3.5/library/asyncio-stream.html)

  - [18.5.5.1. Функции потоков данных](https://python-all.ru/3.5/library/asyncio-stream.html#stream-functions)
  - [18.5.5.2. StreamReader](https://python-all.ru/3.5/library/asyncio-stream.html#streamreader)
  - [18.5.5.3. StreamWriter](https://python-all.ru/3.5/library/asyncio-stream.html#streamwriter)
  - [18.5.5.4. StreamReaderProtocol](https://python-all.ru/3.5/library/asyncio-stream.html#streamreaderprotocol)
  - [18.5.5.5. IncompleteReadError](https://python-all.ru/3.5/library/asyncio-stream.html#incompletereaderror)
  - [18.5.5.6. LimitOverrunError](https://python-all.ru/3.5/library/asyncio-stream.html#limitoverrunerror)
  - [18.5.5.7. Примеры с потоками данных](https://python-all.ru/3.5/library/asyncio-stream.html#stream-examples)

    - [18.5.5.7.1. TCP-эхо-клиент с использованием потоков данных](https://python-all.ru/3.5/library/asyncio-stream.html#tcp-echo-client-using-streams)
    - [18.5.5.7.2. TCP-эхо-сервер с использованием потоков данных](https://python-all.ru/3.5/library/asyncio-stream.html#tcp-echo-server-using-streams)
    - [18.5.5.7.3. Получение HTTP-заголовков](https://python-all.ru/3.5/library/asyncio-stream.html#get-http-headers)
    - [18.5.5.7.4. Регистрация открытого сокета для ожидания данных через потоки данных](https://python-all.ru/3.5/library/asyncio-stream.html#register-an-open-socket-to-wait-for-data-using-streams)
- [18.5.6. Подпроцессы](https://python-all.ru/3.5/library/asyncio-subprocess.html)

  - [18.5.6.1. Цикл событий Windows](https://python-all.ru/3.5/library/asyncio-subprocess.html#windows-event-loop)
  - [18.5.6.2. Создание подпроцесса: высокоуровневый API с использованием процесса](https://python-all.ru/3.5/library/asyncio-subprocess.html#create-a-subprocess-high-level-api-using-process)
  - [18.5.6.3. Создание подпроцесса: низкоуровневый API с использованием subprocess.Popen](https://python-all.ru/3.5/library/asyncio-subprocess.html#create-a-subprocess-low-level-api-using-subprocess-popen)
  - [18.5.6.4. Константы](https://python-all.ru/3.5/library/asyncio-subprocess.html#constants)
  - [18.5.6.5. Процесс](https://python-all.ru/3.5/library/asyncio-subprocess.html#process)
  - [18.5.6.6. Подпроцессы и потоки](https://python-all.ru/3.5/library/asyncio-subprocess.html#subprocess-and-threads)
  - [18.5.6.7. Примеры с подпроцессами](https://python-all.ru/3.5/library/asyncio-subprocess.html#subprocess-examples)

    - [18.5.6.7.1. Подпроцесс с использованием транспорта и протокола](https://python-all.ru/3.5/library/asyncio-subprocess.html#subprocess-using-transport-and-protocol)
    - [18.5.6.7.2. Подпроцесс с использованием потоков данных](https://python-all.ru/3.5/library/asyncio-subprocess.html#subprocess-using-streams)
- [18.5.7. Примитивы синхронизации](https://python-all.ru/3.5/library/asyncio-sync.html)

  - [18.5.7.1. Блокировки](https://python-all.ru/3.5/library/asyncio-sync.html#locks)

    - [18.5.7.1.1. Блокировка](https://python-all.ru/3.5/library/asyncio-sync.html#lock)
    - [18.5.7.1.2. Event](https://python-all.ru/3.5/library/asyncio-sync.html#event)
    - [18.5.7.1.3. Condition](https://python-all.ru/3.5/library/asyncio-sync.html#condition)
  - [18.5.7.2. Семафоры](https://python-all.ru/3.5/library/asyncio-sync.html#semaphores)

    - [18.5.7.2.1. Semaphore](https://python-all.ru/3.5/library/asyncio-sync.html#semaphore)
    - [18.5.7.2.2. BoundedSemaphore](https://python-all.ru/3.5/library/asyncio-sync.html#boundedsemaphore)
- [18.5.8. Очереди](https://python-all.ru/3.5/library/asyncio-queue.html)

  - [18.5.8.1. Очередь](https://python-all.ru/3.5/library/asyncio-queue.html#queue)
  - [18.5.8.2. PriorityQueue](https://python-all.ru/3.5/library/asyncio-queue.html#priorityqueue)
  - [18.5.8.3. LifoQueue](https://python-all.ru/3.5/library/asyncio-queue.html#lifoqueue)

    - [18.5.8.3.1. Исключения](https://python-all.ru/3.5/library/asyncio-queue.html#exceptions)
- [18.5.9. Разработка с asyncio](https://python-all.ru/3.5/library/asyncio-dev.html)

  - [18.5.9.1. Режим отладки asyncio](https://python-all.ru/3.5/library/asyncio-dev.html#debug-mode-of-asyncio)
  - [18.5.9.2. Отмена](https://python-all.ru/3.5/library/asyncio-dev.html#cancellation)
  - [18.5.9.3. Конкурентность и многопоточность](https://python-all.ru/3.5/library/asyncio-dev.html#concurrency-and-multithreading)
  - [18.5.9.4. Корректная обработка блокирующих функций](https://python-all.ru/3.5/library/asyncio-dev.html#handle-blocking-functions-correctly)
  - [18.5.9.5. Логирование](https://python-all.ru/3.5/library/asyncio-dev.html#logging)
  - [18.5.9.6. Обнаружение объектов корутин, которые никогда не были запланированы](https://python-all.ru/3.5/library/asyncio-dev.html#detect-coroutine-objects-never-scheduled)
  - [18.5.9.7. Обнаружение необработанных исключений](https://python-all.ru/3.5/library/asyncio-dev.html#detect-exceptions-never-consumed)
  - [18.5.9.8. Правильное связывание корутин](https://python-all.ru/3.5/library/asyncio-dev.html#chain-coroutines-correctly)
  - [18.5.9.9. Уничтожение ожидающих задач](https://python-all.ru/3.5/library/asyncio-dev.html#pending-task-destroyed)
  - [18.5.9.10. Закрытие транспортов и циклов событий](https://python-all.ru/3.5/library/asyncio-dev.html#close-transports-and-event-loops)

> **См. также**
>
> Модуль [`asyncio`](https://python-all.ru/3.5/library/asyncio.html#module-asyncio) был спроектирован в [**PEP 3156**](https://python-all.ru/3.5/library/asyncio.html). Для начального ознакомления с транспортами и протоколами см. [**PEP 3153**](https://python-all.ru/3.5/library/asyncio.html).
