asyncio.md
1> **Источник:** https://python-all.ru/3.4/library/asyncio.html2>3> «Документация Python на русском» – неофициальный перевод официальной документации Python: версии от 2.6 до 3.16, полнотекстовый поиск, английский оригинал рядом с переводом. Эта Markdown-версия страницы предназначена для работы с LLM: вставьте её в ChatGPT, Claude или Cursor.45---67# 18.5. [`asyncio`](https://python-all.ru/3.4/library/asyncio.html#module-asyncio) – Асинхронный ввод-вывод, цикл событий, корутины и задачи89> **Примечание**10>11> Пакет asyncio был включен в стандартную библиотеку на [*временной основе*](https://python-all.ru/3.4/glossary.html#term-provisional-package). Обратно несовместимые изменения (вплоть до удаления модуля) могут быть внесены, если основные разработчики сочтут это необходимым.1213Новое в версии 3.4.1415**Исходный код:** [Lib/asyncio/](https://python-all.ru/src/3.4/Lib/asyncio)1617---1819Этот модуль предоставляет инфраструктуру для написания однопоточного конкурентного кода с использованием корутин, мультиплексирования доступа к вводу-выводу через сокеты и другие ресурсы, запуска сетевых клиентов и серверов, а также других связанных примитивов. Ниже приведён более подробный список содержимого пакета:2021- подключаемый [*цикл событий*](https://python-all.ru/3.4/library/asyncio-eventloop.html#asyncio-event-loop) с различными системно-зависимыми реализациями;22- [*транспорт*](https://python-all.ru/3.4/library/asyncio-protocol.html#asyncio-transport) и [*протокол*](https://python-all.ru/3.4/library/asyncio-protocol.html#asyncio-protocol) абстракции (аналогичные тем, что в [Twisted](https://python-all.ru/3.4/library/asyncio.html));23- конкретная поддержка TCP, UDP, SSL, каналов подпроцессов, отложенных вызовов и других (некоторые могут быть системно-зависимыми);24- класс [`Future`](https://python-all.ru/3.4/library/asyncio-task.html#asyncio.Future), который имитирует одноимённый класс из модуля [`concurrent.futures`](https://python-all.ru/3.4/library/concurrent.futures.html#module-concurrent.futures), но адаптирован для использования с циклом событий;25- корутины и задачи, основанные на `yield from` ([**PEP 380**](https://python-all.ru/3.4/library/asyncio.html)), чтобы помочь писать конкурентный код в последовательном стиле;26- поддержка отмены для [`Future`](https://python-all.ru/3.4/library/asyncio-task.html#asyncio.Future) и корутин;27- [*примитивы синхронизации*](https://python-all.ru/3.4/library/asyncio-sync.html#asyncio-sync) для использования между корутинами в одном потоке, имитирующие те, что в модуле [`threading`](https://python-all.ru/3.4/library/threading.html#module-threading);28- интерфейс для передачи работы в пул потоков на случай, когда абсолютно необходимо использовать библиотеку, выполняющую блокирующие вызовы ввода-вывода.2930Асинхронное программирование сложнее классического «последовательного» программирования: см. страницу [*Разработка с asyncio*](https://python-all.ru/3.4/library/asyncio-dev.html#asyncio-dev), где перечислены распространённые ловушки и объясняется, как их избежать. [*Включите режим отладки*](https://python-all.ru/3.4/library/asyncio-dev.html#asyncio-debug-mode) при разработке, чтобы выявлять типичные проблемы.3132Содержание:3334- [18.5.1. Базовый цикл событий](https://python-all.ru/3.4/library/asyncio-eventloop.html)3536 - [18.5.1.1. Запуск цикла событий](https://python-all.ru/3.4/library/asyncio-eventloop.html#run-an-event-loop)37 - [18.5.1.2. Вызовы](https://python-all.ru/3.4/library/asyncio-eventloop.html#calls)38 - [18.5.1.3. Отложенные вызовы](https://python-all.ru/3.4/library/asyncio-eventloop.html#delayed-calls)39 - [18.5.1.4. Задачи](https://python-all.ru/3.4/library/asyncio-eventloop.html#tasks)40 - [18.5.1.5. Создание подключений](https://python-all.ru/3.4/library/asyncio-eventloop.html#creating-connections)41 - [18.5.1.6. Создание прослушивающих подключений](https://python-all.ru/3.4/library/asyncio-eventloop.html#creating-listening-connections)42 - [18.5.1.7. Отслеживание файловых дескрипторов](https://python-all.ru/3.4/library/asyncio-eventloop.html#watch-file-descriptors)43 - [18.5.1.8. Низкоуровневые операции с сокетами](https://python-all.ru/3.4/library/asyncio-eventloop.html#low-level-socket-operations)44 - [18.5.1.9. Разрешение имени хоста](https://python-all.ru/3.4/library/asyncio-eventloop.html#resolve-host-name)45 - [18.5.1.10. Подключение каналов](https://python-all.ru/3.4/library/asyncio-eventloop.html#connect-pipes)46 - [18.5.1.11. Сигналы UNIX](https://python-all.ru/3.4/library/asyncio-eventloop.html#unix-signals)47 - [18.5.1.12. Исполнитель](https://python-all.ru/3.4/library/asyncio-eventloop.html#executor)48 - [18.5.1.13. API обработки ошибок](https://python-all.ru/3.4/library/asyncio-eventloop.html#error-handling-api)49 - [18.5.1.14. Режим отладки](https://python-all.ru/3.4/library/asyncio-eventloop.html#debug-mode)50 - [18.5.1.15. Сервер](https://python-all.ru/3.4/library/asyncio-eventloop.html#server)51 - [18.5.1.16. Handle](https://python-all.ru/3.4/library/asyncio-eventloop.html#handle)52 - [18.5.1.17. Примеры работы с циклом событий](https://python-all.ru/3.4/library/asyncio-eventloop.html#event-loop-examples)5354 - [18.5.1.17.1. Hello World с помощью call\_soon()](https://python-all.ru/3.4/library/asyncio-eventloop.html#hello-world-with-call-soon)55 - [18.5.1.17.2. Отображение текущей даты с помощью call\_later()](https://python-all.ru/3.4/library/asyncio-eventloop.html#display-the-current-date-with-call-later)56 - [18.5.1.17.3. Отслеживание файлового дескриптора на события чтения](https://python-all.ru/3.4/library/asyncio-eventloop.html#watch-a-file-descriptor-for-read-events)57 - [18.5.1.17.4. Установка обработчиков сигналов SIGINT и SIGTERM](https://python-all.ru/3.4/library/asyncio-eventloop.html#set-signal-handlers-for-sigint-and-sigterm)58- [18.5.2. Циклы событий](https://python-all.ru/3.4/library/asyncio-eventloops.html)5960 - [18.5.2.1. Функции цикла событий](https://python-all.ru/3.4/library/asyncio-eventloops.html#event-loop-functions)61 - [18.5.2.2. Доступные циклы событий](https://python-all.ru/3.4/library/asyncio-eventloops.html#available-event-loops)62 - [18.5.2.3. Поддержка платформ](https://python-all.ru/3.4/library/asyncio-eventloops.html#platform-support)6364 - [18.5.2.3.1. Windows](https://python-all.ru/3.4/library/asyncio-eventloops.html#windows)65 - [18.5.2.3.2. Mac OS X](https://python-all.ru/3.4/library/asyncio-eventloops.html#mac-os-x)66 - [18.5.2.4. Политики цикла событий и политика по умолчанию](https://python-all.ru/3.4/library/asyncio-eventloops.html#event-loop-policies-and-the-default-policy)67 - [18.5.2.5. Интерфейс политики цикла событий](https://python-all.ru/3.4/library/asyncio-eventloops.html#event-loop-policy-interface)68 - [18.5.2.6. Доступ к глобальной политике цикла событий](https://python-all.ru/3.4/library/asyncio-eventloops.html#access-to-the-global-loop-policy)69- [18.5.3. Задачи и корутины](https://python-all.ru/3.4/library/asyncio-task.html)7071 - [18.5.3.1. Корутины](https://python-all.ru/3.4/library/asyncio-task.html#coroutines)7273 - [18.5.3.1.1. Пример: корутина «Hello World»](https://python-all.ru/3.4/library/asyncio-task.html#example-hello-world-coroutine)74 - [18.5.3.1.2. Пример: корутина, отображающая текущую дату](https://python-all.ru/3.4/library/asyncio-task.html#example-coroutine-displaying-the-current-date)75 - [18.5.3.1.3. Пример: цепочка корутин](https://python-all.ru/3.4/library/asyncio-task.html#example-chain-coroutines)76 - [18.5.3.2. InvalidStateError](https://python-all.ru/3.4/library/asyncio-task.html#invalidstateerror)77 - [18.5.3.3. TimeoutError](https://python-all.ru/3.4/library/asyncio-task.html#timeouterror)78 - [18.5.3.4. Future](https://python-all.ru/3.4/library/asyncio-task.html#future)7980 - [18.5.3.4.1. Пример: Future с run\_until\_complete()](https://python-all.ru/3.4/library/asyncio-task.html#example-future-with-run-until-complete)81 - [18.5.3.4.2. Пример: Future с run\_forever()](https://python-all.ru/3.4/library/asyncio-task.html#example-future-with-run-forever)82 - [18.5.3.5. Задача](https://python-all.ru/3.4/library/asyncio-task.html#task)8384 - [18.5.3.5.1. Пример: параллельное выполнение задач](https://python-all.ru/3.4/library/asyncio-task.html#example-parallel-execution-of-tasks)85 - [18.5.3.6. Функции задач](https://python-all.ru/3.4/library/asyncio-task.html#task-functions)86- [18.5.4. Транспорты и протоколы (API на основе колбэков)](https://python-all.ru/3.4/library/asyncio-protocol.html)8788 - [18.5.4.1. Транспорты](https://python-all.ru/3.4/library/asyncio-protocol.html#transports)8990 - [18.5.4.1.1. BaseTransport](https://python-all.ru/3.4/library/asyncio-protocol.html#basetransport)91 - [18.5.4.1.2. ReadTransport](https://python-all.ru/3.4/library/asyncio-protocol.html#readtransport)92 - [18.5.4.1.3. WriteTransport](https://python-all.ru/3.4/library/asyncio-protocol.html#writetransport)93 - [18.5.4.1.4. DatagramTransport](https://python-all.ru/3.4/library/asyncio-protocol.html#datagramtransport)94 - [18.5.4.1.5. BaseSubprocessTransport](https://python-all.ru/3.4/library/asyncio-protocol.html#basesubprocesstransport)95 - [18.5.4.2. Протоколы](https://python-all.ru/3.4/library/asyncio-protocol.html#protocols)9697 - [18.5.4.2.1. Классы протоколов](https://python-all.ru/3.4/library/asyncio-protocol.html#protocol-classes)98 - [18.5.4.2.2. Колбэки соединения](https://python-all.ru/3.4/library/asyncio-protocol.html#connection-callbacks)99 - [18.5.4.2.3. Потоковые протоколы](https://python-all.ru/3.4/library/asyncio-protocol.html#streaming-protocols)100 - [18.5.4.2.4. Протоколы датаграмм](https://python-all.ru/3.4/library/asyncio-protocol.html#datagram-protocols)101 - [18.5.4.2.5. Колбэки управления потоком](https://python-all.ru/3.4/library/asyncio-protocol.html#flow-control-callbacks)102 - [18.5.4.2.6. Корутины и протоколы](https://python-all.ru/3.4/library/asyncio-protocol.html#coroutines-and-protocols)103 - [18.5.4.3. Примеры протоколов](https://python-all.ru/3.4/library/asyncio-protocol.html#protocol-examples)104105 - [18.5.4.3.1. Протокол TCP-эхо-клиента](https://python-all.ru/3.4/library/asyncio-protocol.html#tcp-echo-client-protocol)106 - [18.5.4.3.2. Протокол TCP-эхо-сервера](https://python-all.ru/3.4/library/asyncio-protocol.html#tcp-echo-server-protocol)107 - [18.5.4.3.3. Протокол UDP-эхо-клиента](https://python-all.ru/3.4/library/asyncio-protocol.html#udp-echo-client-protocol)108 - [18.5.4.3.4. Протокол UDP-эхо-сервера](https://python-all.ru/3.4/library/asyncio-protocol.html#udp-echo-server-protocol)109 - [18.5.4.3.5. Регистрация открытого сокета для ожидания данных через протокол](https://python-all.ru/3.4/library/asyncio-protocol.html#register-an-open-socket-to-wait-for-data-using-a-protocol)110- [18.5.5. Потоки данных (API на корутинах)](https://python-all.ru/3.4/library/asyncio-stream.html)111112 - [18.5.5.1. Функции потоков данных](https://python-all.ru/3.4/library/asyncio-stream.html#stream-functions)113 - [18.5.5.2. StreamReader](https://python-all.ru/3.4/library/asyncio-stream.html#streamreader)114 - [18.5.5.3. StreamWriter](https://python-all.ru/3.4/library/asyncio-stream.html#streamwriter)115 - [18.5.5.4. StreamReaderProtocol](https://python-all.ru/3.4/library/asyncio-stream.html#streamreaderprotocol)116 - [18.5.5.5. IncompleteReadError](https://python-all.ru/3.4/library/asyncio-stream.html#incompletereaderror)117 - [18.5.5.6. Примеры работы с потоками](https://python-all.ru/3.4/library/asyncio-stream.html#stream-examples)118119 - [18.5.5.6.1. TCP-эхо-клиент с использованием потоков](https://python-all.ru/3.4/library/asyncio-stream.html#tcp-echo-client-using-streams)120 - [18.5.5.6.2. TCP-эхо-сервер с использованием потоков](https://python-all.ru/3.4/library/asyncio-stream.html#tcp-echo-server-using-streams)121 - [18.5.5.6.3. Получение HTTP-заголовков](https://python-all.ru/3.4/library/asyncio-stream.html#get-http-headers)122 - [18.5.5.6.4. Регистрация открытого сокета для ожидания данных с помощью потоков](https://python-all.ru/3.4/library/asyncio-stream.html#register-an-open-socket-to-wait-for-data-using-streams)123- [18.5.6. Подпроцессы](https://python-all.ru/3.4/library/asyncio-subprocess.html)124125 - [18.5.6.1. Цикл событий Windows](https://python-all.ru/3.4/library/asyncio-subprocess.html#windows-event-loop)126 - [18.5.6.2. Создание подпроцесса: высокоуровневый API с использованием процесса](https://python-all.ru/3.4/library/asyncio-subprocess.html#create-a-subprocess-high-level-api-using-process)127 - [18.5.6.3. Создание подпроцесса: низкоуровневый API с использованием subprocess.Popen](https://python-all.ru/3.4/library/asyncio-subprocess.html#create-a-subprocess-low-level-api-using-subprocess-popen)128 - [18.5.6.4. Константы](https://python-all.ru/3.4/library/asyncio-subprocess.html#constants)129 - [18.5.6.5. Процесс](https://python-all.ru/3.4/library/asyncio-subprocess.html#process)130 - [18.5.6.6. Подпроцессы и потоки](https://python-all.ru/3.4/library/asyncio-subprocess.html#subprocess-and-threads)131 - [18.5.6.7. Примеры с подпроцессами](https://python-all.ru/3.4/library/asyncio-subprocess.html#subprocess-examples)132133 - [18.5.6.7.1. Подпроцесс с использованием транспорта и протокола](https://python-all.ru/3.4/library/asyncio-subprocess.html#subprocess-using-transport-and-protocol)134 - [18.5.6.7.2. Подпроцесс с использованием потоков данных](https://python-all.ru/3.4/library/asyncio-subprocess.html#subprocess-using-streams)135- [18.5.7. Примитивы синхронизации](https://python-all.ru/3.4/library/asyncio-sync.html)136137 - [18.5.7.1. Блокировки](https://python-all.ru/3.4/library/asyncio-sync.html#locks)138139 - [18.5.7.1.1. Блокировка](https://python-all.ru/3.4/library/asyncio-sync.html#lock)140 - [18.5.7.1.2. Event](https://python-all.ru/3.4/library/asyncio-sync.html#event)141 - [18.5.7.1.3. Condition](https://python-all.ru/3.4/library/asyncio-sync.html#condition)142 - [18.5.7.2. Семафоры](https://python-all.ru/3.4/library/asyncio-sync.html#semaphores)143144 - [18.5.7.2.1. Semaphore](https://python-all.ru/3.4/library/asyncio-sync.html#semaphore)145 - [18.5.7.2.2. BoundedSemaphore](https://python-all.ru/3.4/library/asyncio-sync.html#boundedsemaphore)146- [18.5.8. Очереди](https://python-all.ru/3.4/library/asyncio-queue.html)147148 - [18.5.8.1. Очередь](https://python-all.ru/3.4/library/asyncio-queue.html#queue)149 - [18.5.8.2. PriorityQueue](https://python-all.ru/3.4/library/asyncio-queue.html#priorityqueue)150 - [18.5.8.3. LifoQueue](https://python-all.ru/3.4/library/asyncio-queue.html#lifoqueue)151152 - [18.5.8.3.1. JoinableQueue](https://python-all.ru/3.4/library/asyncio-queue.html#joinablequeue)153 - [18.5.8.3.2. Исключения](https://python-all.ru/3.4/library/asyncio-queue.html#exceptions)154- [18.5.9. Разработка с asyncio](https://python-all.ru/3.4/library/asyncio-dev.html)155156 - [18.5.9.1. Режим отладки asyncio](https://python-all.ru/3.4/library/asyncio-dev.html#debug-mode-of-asyncio)157 - [18.5.9.2. Отмена](https://python-all.ru/3.4/library/asyncio-dev.html#cancellation)158 - [18.5.9.3. Конкурентность и многопоточность](https://python-all.ru/3.4/library/asyncio-dev.html#concurrency-and-multithreading)159 - [18.5.9.4. Корректная обработка блокирующих функций](https://python-all.ru/3.4/library/asyncio-dev.html#handle-blocking-functions-correctly)160 - [18.5.9.5. Логирование](https://python-all.ru/3.4/library/asyncio-dev.html#logging)161 - [18.5.9.6. Обнаружение объектов корутин, которые никогда не были запланированы](https://python-all.ru/3.4/library/asyncio-dev.html#detect-coroutine-objects-never-scheduled)162 - [18.5.9.7. Обнаружение необработанных исключений](https://python-all.ru/3.4/library/asyncio-dev.html#detect-exceptions-never-consumed)163 - [18.5.9.8. Правильное связывание корутин](https://python-all.ru/3.4/library/asyncio-dev.html#chain-coroutines-correctly)164 - [18.5.9.9. Уничтожение ожидающих задач](https://python-all.ru/3.4/library/asyncio-dev.html#pending-task-destroyed)165 - [18.5.9.10. Закрытие транспортов и циклов событий](https://python-all.ru/3.4/library/asyncio-dev.html#close-transports-and-event-loops)166167> **См. также**168>169> Модуль [`asyncio`](https://python-all.ru/3.4/library/asyncio.html#module-asyncio) был спроектирован в [**PEP 3156**](https://python-all.ru/3.4/library/asyncio.html). Вводное руководство по транспортам и протоколам см. в [**PEP 3153**](https://python-all.ru/3.4/library/asyncio.html).170