Документация Python неофициальный перевод

ipc.md

227 строк · 23.6 КБ · обычная страница · сырой текст · скачать

1> **Источник:** https://python-all.ru/3.4/library/ipc.html2>3> «Документация Python на русском» – неофициальный перевод официальной документации Python: версии от 2.6 до 3.16, полнотекстовый поиск, английский оригинал рядом с переводом. Эта Markdown-версия страницы предназначена для работы с LLM: вставьте её в ChatGPT, Claude или Cursor.45---67# 18. Межпроцессное взаимодействие и сети89Модули, описанные в этой главе, предоставляют механизмы для взаимодействия разных процессов.1011Некоторые модули работают только для двух процессов на одной машине, например [`signal`](https://python-all.ru/3.4/library/signal.html#module-signal) и [`mmap`](https://python-all.ru/3.4/library/mmap.html#module-mmap). Другие модули поддерживают сетевые протоколы которые два или более процессов могут использовать для обмена данными между машинами.1213Список модулей, описанных в этой главе:1415- [18.1. `socket` – низкоуровневый сетевой интерфейс](https://python-all.ru/3.4/library/socket.html)1617  - [18.1.1. Семейства сокетов](https://python-all.ru/3.4/library/socket.html#socket-families)18  - [18.1.2. Содержимое модуля](https://python-all.ru/3.4/library/socket.html#module-contents)1920    - [18.1.2.1. Исключения](https://python-all.ru/3.4/library/socket.html#exceptions)21    - [18.1.2.2. Константы](https://python-all.ru/3.4/library/socket.html#constants)22    - [18.1.2.3. Функции](https://python-all.ru/3.4/library/socket.html#functions)2324      - [18.1.2.3.1. Создание сокетов](https://python-all.ru/3.4/library/socket.html#creating-sockets)25      - [18.1.2.3.2. Прочие функции](https://python-all.ru/3.4/library/socket.html#other-functions)26  - [18.1.3. Объекты сокетов](https://python-all.ru/3.4/library/socket.html#socket-objects)27  - [18.1.4. Примечания о тайм-аутах сокетов](https://python-all.ru/3.4/library/socket.html#notes-on-socket-timeouts)2829    - [18.1.4.1. Тайм-ауты и метод `connect`](https://python-all.ru/3.4/library/socket.html#timeouts-and-the-connect-method)30    - [18.1.4.2. Тайм-ауты и метод `accept`](https://python-all.ru/3.4/library/socket.html#timeouts-and-the-accept-method)31  - [18.1.5. Пример](https://python-all.ru/3.4/library/socket.html#example)32- [18.2. `ssl` – обёртка TLS/SSL для объектов сокетов](https://python-all.ru/3.4/library/ssl.html)3334  - [18.2.1. Функции, константы и исключения](https://python-all.ru/3.4/library/ssl.html#functions-constants-and-exceptions)3536    - [18.2.1.1. Создание сокетов](https://python-all.ru/3.4/library/ssl.html#socket-creation)37    - [18.2.1.2. Создание контекста](https://python-all.ru/3.4/library/ssl.html#context-creation)38    - [18.2.1.3. Генерация случайных чисел](https://python-all.ru/3.4/library/ssl.html#random-generation)39    - [18.2.1.4. Обработка сертификатов](https://python-all.ru/3.4/library/ssl.html#certificate-handling)40    - [18.2.1.5. Константы](https://python-all.ru/3.4/library/ssl.html#constants)41  - [18.2.2. SSL-сокеты](https://python-all.ru/3.4/library/ssl.html#ssl-sockets)42  - [18.2.3. SSL-контексты](https://python-all.ru/3.4/library/ssl.html#ssl-contexts)43  - [18.2.4. Сертификаты](https://python-all.ru/3.4/library/ssl.html#certificates)4445    - [18.2.4.1. Цепочки сертификатов](https://python-all.ru/3.4/library/ssl.html#certificate-chains)46    - [18.2.4.2. Сертификаты удостоверяющих центров](https://python-all.ru/3.4/library/ssl.html#ca-certificates)47    - [18.2.4.3. Совмещённый ключ и сертификат](https://python-all.ru/3.4/library/ssl.html#combined-key-and-certificate)48    - [18.2.4.4. Самоподписанные сертификаты](https://python-all.ru/3.4/library/ssl.html#self-signed-certificates)49  - [18.2.5. Примеры](https://python-all.ru/3.4/library/ssl.html#examples)5051    - [18.2.5.1. Проверка поддержки SSL](https://python-all.ru/3.4/library/ssl.html#testing-for-ssl-support)52    - [18.2.5.2. Работа на стороне клиента](https://python-all.ru/3.4/library/ssl.html#client-side-operation)53    - [18.2.5.3. Работа на стороне сервера](https://python-all.ru/3.4/library/ssl.html#server-side-operation)54  - [18.2.6. Замечания о неблокирующих сокетах](https://python-all.ru/3.4/library/ssl.html#notes-on-non-blocking-sockets)55  - [18.2.7. Вопросы безопасности](https://python-all.ru/3.4/library/ssl.html#security-considerations)5657    - [18.2.7.1. Рекомендуемые настройки по умолчанию](https://python-all.ru/3.4/library/ssl.html#best-defaults)58    - [18.2.7.2. Настройка вручную](https://python-all.ru/3.4/library/ssl.html#manual-settings)5960      - [18.2.7.2.1. Проверка сертификатов](https://python-all.ru/3.4/library/ssl.html#verifying-certificates)61      - [18.2.7.2.2. Версии протоколов](https://python-all.ru/3.4/library/ssl.html#protocol-versions)62      - [18.2.7.2.3. Выбор шифров](https://python-all.ru/3.4/library/ssl.html#cipher-selection)63    - [18.2.7.3. Многопроцессорность](https://python-all.ru/3.4/library/ssl.html#multi-processing)64- [18.3. `select` – ожидание завершения ввода-вывода](https://python-all.ru/3.4/library/select.html)6566  - [18.3.1. `/dev/poll` – объекты опроса](https://python-all.ru/3.4/library/select.html#dev-poll-polling-objects)67  - [18.3.2. Объекты опроса по границе и уровню (epoll)](https://python-all.ru/3.4/library/select.html#edge-and-level-trigger-polling-epoll-objects)68  - [18.3.3. Объекты опроса](https://python-all.ru/3.4/library/select.html#polling-objects)69  - [18.3.4. Объекты Kqueue](https://python-all.ru/3.4/library/select.html#kqueue-objects)70  - [18.3.5. Объекты Kevent](https://python-all.ru/3.4/library/select.html#kevent-objects)71- [18.4. `selectors` – высокоуровневое мультиплексирование ввода-вывода](https://python-all.ru/3.4/library/selectors.html)7273  - [18.4.1. Введение](https://python-all.ru/3.4/library/selectors.html#introduction)74  - [18.4.2. Классы](https://python-all.ru/3.4/library/selectors.html#classes)75  - [18.4.3. Примеры](https://python-all.ru/3.4/library/selectors.html#examples)76- [18.5. `asyncio` – асинхронный ввод-вывод, цикл событий, корутины и задачи](https://python-all.ru/3.4/library/asyncio.html)7778  - [18.5.1. Базовый цикл событий](https://python-all.ru/3.4/library/asyncio-eventloop.html)7980    - [18.5.1.1. Запуск цикла событий](https://python-all.ru/3.4/library/asyncio-eventloop.html#run-an-event-loop)81    - [18.5.1.2. Вызовы](https://python-all.ru/3.4/library/asyncio-eventloop.html#calls)82    - [18.5.1.3. Отложенные вызовы](https://python-all.ru/3.4/library/asyncio-eventloop.html#delayed-calls)83    - [18.5.1.4. Задачи](https://python-all.ru/3.4/library/asyncio-eventloop.html#tasks)84    - [18.5.1.5. Создание подключений](https://python-all.ru/3.4/library/asyncio-eventloop.html#creating-connections)85    - [18.5.1.6. Создание прослушивающих подключений](https://python-all.ru/3.4/library/asyncio-eventloop.html#creating-listening-connections)86    - [18.5.1.7. Отслеживание файловых дескрипторов](https://python-all.ru/3.4/library/asyncio-eventloop.html#watch-file-descriptors)87    - [18.5.1.8. Низкоуровневые операции с сокетами](https://python-all.ru/3.4/library/asyncio-eventloop.html#low-level-socket-operations)88    - [18.5.1.9. Разрешение имени хоста](https://python-all.ru/3.4/library/asyncio-eventloop.html#resolve-host-name)89    - [18.5.1.10. Подключение каналов](https://python-all.ru/3.4/library/asyncio-eventloop.html#connect-pipes)90    - [18.5.1.11. Сигналы UNIX](https://python-all.ru/3.4/library/asyncio-eventloop.html#unix-signals)91    - [18.5.1.12. Исполнитель](https://python-all.ru/3.4/library/asyncio-eventloop.html#executor)92    - [18.5.1.13. API обработки ошибок](https://python-all.ru/3.4/library/asyncio-eventloop.html#error-handling-api)93    - [18.5.1.14. Режим отладки](https://python-all.ru/3.4/library/asyncio-eventloop.html#debug-mode)94    - [18.5.1.15. Сервер](https://python-all.ru/3.4/library/asyncio-eventloop.html#server)95    - [18.5.1.16. Handle](https://python-all.ru/3.4/library/asyncio-eventloop.html#handle)96    - [18.5.1.17. Примеры работы с циклом событий](https://python-all.ru/3.4/library/asyncio-eventloop.html#event-loop-examples)9798      - [18.5.1.17.1. Hello World с помощью call\_soon()](https://python-all.ru/3.4/library/asyncio-eventloop.html#hello-world-with-call-soon)99      - [18.5.1.17.2. Отображение текущей даты с помощью call\_later()](https://python-all.ru/3.4/library/asyncio-eventloop.html#display-the-current-date-with-call-later)100      - [18.5.1.17.3. Отслеживание файлового дескриптора на события чтения](https://python-all.ru/3.4/library/asyncio-eventloop.html#watch-a-file-descriptor-for-read-events)101      - [18.5.1.17.4. Установка обработчиков сигналов SIGINT и SIGTERM](https://python-all.ru/3.4/library/asyncio-eventloop.html#set-signal-handlers-for-sigint-and-sigterm)102  - [18.5.2. Циклы событий](https://python-all.ru/3.4/library/asyncio-eventloops.html)103104    - [18.5.2.1. Функции цикла событий](https://python-all.ru/3.4/library/asyncio-eventloops.html#event-loop-functions)105    - [18.5.2.2. Доступные циклы событий](https://python-all.ru/3.4/library/asyncio-eventloops.html#available-event-loops)106    - [18.5.2.3. Поддержка платформ](https://python-all.ru/3.4/library/asyncio-eventloops.html#platform-support)107108      - [18.5.2.3.1. Windows](https://python-all.ru/3.4/library/asyncio-eventloops.html#windows)109      - [18.5.2.3.2. Mac OS X](https://python-all.ru/3.4/library/asyncio-eventloops.html#mac-os-x)110    - [18.5.2.4. Политики цикла событий и политика по умолчанию](https://python-all.ru/3.4/library/asyncio-eventloops.html#event-loop-policies-and-the-default-policy)111    - [18.5.2.5. Интерфейс политики цикла событий](https://python-all.ru/3.4/library/asyncio-eventloops.html#event-loop-policy-interface)112    - [18.5.2.6. Доступ к глобальной политике цикла событий](https://python-all.ru/3.4/library/asyncio-eventloops.html#access-to-the-global-loop-policy)113  - [18.5.3. Задачи и корутины](https://python-all.ru/3.4/library/asyncio-task.html)114115    - [18.5.3.1. Корутины](https://python-all.ru/3.4/library/asyncio-task.html#coroutines)116117      - [18.5.3.1.1. Пример: корутина «Hello World»](https://python-all.ru/3.4/library/asyncio-task.html#example-hello-world-coroutine)118      - [18.5.3.1.2. Пример: корутина, отображающая текущую дату](https://python-all.ru/3.4/library/asyncio-task.html#example-coroutine-displaying-the-current-date)119      - [18.5.3.1.3. Пример: цепочка корутин](https://python-all.ru/3.4/library/asyncio-task.html#example-chain-coroutines)120    - [18.5.3.2. InvalidStateError](https://python-all.ru/3.4/library/asyncio-task.html#invalidstateerror)121    - [18.5.3.3. TimeoutError](https://python-all.ru/3.4/library/asyncio-task.html#timeouterror)122    - [18.5.3.4. Future](https://python-all.ru/3.4/library/asyncio-task.html#future)123124      - [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)125      - [18.5.3.4.2. Пример: Future с run\_forever()](https://python-all.ru/3.4/library/asyncio-task.html#example-future-with-run-forever)126    - [18.5.3.5. Задача](https://python-all.ru/3.4/library/asyncio-task.html#task)127128      - [18.5.3.5.1. Пример: параллельное выполнение задач](https://python-all.ru/3.4/library/asyncio-task.html#example-parallel-execution-of-tasks)129    - [18.5.3.6. Функции задач](https://python-all.ru/3.4/library/asyncio-task.html#task-functions)130  - [18.5.4. Транспорты и протоколы (API на основе колбэков)](https://python-all.ru/3.4/library/asyncio-protocol.html)131132    - [18.5.4.1. Транспорты](https://python-all.ru/3.4/library/asyncio-protocol.html#transports)133134      - [18.5.4.1.1. BaseTransport](https://python-all.ru/3.4/library/asyncio-protocol.html#basetransport)135      - [18.5.4.1.2. ReadTransport](https://python-all.ru/3.4/library/asyncio-protocol.html#readtransport)136      - [18.5.4.1.3. WriteTransport](https://python-all.ru/3.4/library/asyncio-protocol.html#writetransport)137      - [18.5.4.1.4. DatagramTransport](https://python-all.ru/3.4/library/asyncio-protocol.html#datagramtransport)138      - [18.5.4.1.5. BaseSubprocessTransport](https://python-all.ru/3.4/library/asyncio-protocol.html#basesubprocesstransport)139    - [18.5.4.2. Протоколы](https://python-all.ru/3.4/library/asyncio-protocol.html#protocols)140141      - [18.5.4.2.1. Классы протоколов](https://python-all.ru/3.4/library/asyncio-protocol.html#protocol-classes)142      - [18.5.4.2.2. Колбэки соединения](https://python-all.ru/3.4/library/asyncio-protocol.html#connection-callbacks)143      - [18.5.4.2.3. Потоковые протоколы](https://python-all.ru/3.4/library/asyncio-protocol.html#streaming-protocols)144      - [18.5.4.2.4. Протоколы датаграмм](https://python-all.ru/3.4/library/asyncio-protocol.html#datagram-protocols)145      - [18.5.4.2.5. Колбэки управления потоком](https://python-all.ru/3.4/library/asyncio-protocol.html#flow-control-callbacks)146      - [18.5.4.2.6. Корутины и протоколы](https://python-all.ru/3.4/library/asyncio-protocol.html#coroutines-and-protocols)147    - [18.5.4.3. Примеры протоколов](https://python-all.ru/3.4/library/asyncio-protocol.html#protocol-examples)148149      - [18.5.4.3.1. Протокол TCP-эхо-клиента](https://python-all.ru/3.4/library/asyncio-protocol.html#tcp-echo-client-protocol)150      - [18.5.4.3.2. Протокол TCP-эхо-сервера](https://python-all.ru/3.4/library/asyncio-protocol.html#tcp-echo-server-protocol)151      - [18.5.4.3.3. Протокол UDP-эхо-клиента](https://python-all.ru/3.4/library/asyncio-protocol.html#udp-echo-client-protocol)152      - [18.5.4.3.4. Протокол UDP-эхо-сервера](https://python-all.ru/3.4/library/asyncio-protocol.html#udp-echo-server-protocol)153      - [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)154  - [18.5.5. Потоки данных (API на корутинах)](https://python-all.ru/3.4/library/asyncio-stream.html)155156    - [18.5.5.1. Функции потоков данных](https://python-all.ru/3.4/library/asyncio-stream.html#stream-functions)157    - [18.5.5.2. StreamReader](https://python-all.ru/3.4/library/asyncio-stream.html#streamreader)158    - [18.5.5.3. StreamWriter](https://python-all.ru/3.4/library/asyncio-stream.html#streamwriter)159    - [18.5.5.4. StreamReaderProtocol](https://python-all.ru/3.4/library/asyncio-stream.html#streamreaderprotocol)160    - [18.5.5.5. IncompleteReadError](https://python-all.ru/3.4/library/asyncio-stream.html#incompletereaderror)161    - [18.5.5.6. Примеры работы с потоками](https://python-all.ru/3.4/library/asyncio-stream.html#stream-examples)162163      - [18.5.5.6.1. TCP-эхо-клиент с использованием потоков](https://python-all.ru/3.4/library/asyncio-stream.html#tcp-echo-client-using-streams)164      - [18.5.5.6.2. TCP-эхо-сервер с использованием потоков](https://python-all.ru/3.4/library/asyncio-stream.html#tcp-echo-server-using-streams)165      - [18.5.5.6.3. Получение HTTP-заголовков](https://python-all.ru/3.4/library/asyncio-stream.html#get-http-headers)166      - [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)167  - [18.5.6. Подпроцессы](https://python-all.ru/3.4/library/asyncio-subprocess.html)168169    - [18.5.6.1. Цикл событий Windows](https://python-all.ru/3.4/library/asyncio-subprocess.html#windows-event-loop)170    - [18.5.6.2. Создание подпроцесса: высокоуровневый API с использованием процесса](https://python-all.ru/3.4/library/asyncio-subprocess.html#create-a-subprocess-high-level-api-using-process)171    - [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)172    - [18.5.6.4. Константы](https://python-all.ru/3.4/library/asyncio-subprocess.html#constants)173    - [18.5.6.5. Процесс](https://python-all.ru/3.4/library/asyncio-subprocess.html#process)174    - [18.5.6.6. Подпроцессы и потоки](https://python-all.ru/3.4/library/asyncio-subprocess.html#subprocess-and-threads)175    - [18.5.6.7. Примеры с подпроцессами](https://python-all.ru/3.4/library/asyncio-subprocess.html#subprocess-examples)176177      - [18.5.6.7.1. Подпроцесс с использованием транспорта и протокола](https://python-all.ru/3.4/library/asyncio-subprocess.html#subprocess-using-transport-and-protocol)178      - [18.5.6.7.2. Подпроцесс с использованием потоков данных](https://python-all.ru/3.4/library/asyncio-subprocess.html#subprocess-using-streams)179  - [18.5.7. Примитивы синхронизации](https://python-all.ru/3.4/library/asyncio-sync.html)180181    - [18.5.7.1. Блокировки](https://python-all.ru/3.4/library/asyncio-sync.html#locks)182183      - [18.5.7.1.1. Блокировка](https://python-all.ru/3.4/library/asyncio-sync.html#lock)184      - [18.5.7.1.2. Event](https://python-all.ru/3.4/library/asyncio-sync.html#event)185      - [18.5.7.1.3. Condition](https://python-all.ru/3.4/library/asyncio-sync.html#condition)186    - [18.5.7.2. Семафоры](https://python-all.ru/3.4/library/asyncio-sync.html#semaphores)187188      - [18.5.7.2.1. Семафор](https://python-all.ru/3.4/library/asyncio-sync.html#semaphore)189      - [18.5.7.2.2. Ограниченный семафор](https://python-all.ru/3.4/library/asyncio-sync.html#boundedsemaphore)190  - [18.5.8. Очереди](https://python-all.ru/3.4/library/asyncio-queue.html)191192    - [18.5.8.1. Очередь](https://python-all.ru/3.4/library/asyncio-queue.html#queue)193    - [18.5.8.2. PriorityQueue](https://python-all.ru/3.4/library/asyncio-queue.html#priorityqueue)194    - [18.5.8.3. LifoQueue](https://python-all.ru/3.4/library/asyncio-queue.html#lifoqueue)195196      - [18.5.8.3.1. JoinableQueue](https://python-all.ru/3.4/library/asyncio-queue.html#joinablequeue)197      - [18.5.8.3.2. Исключения](https://python-all.ru/3.4/library/asyncio-queue.html#exceptions)198  - [18.5.9. Разработка с asyncio](https://python-all.ru/3.4/library/asyncio-dev.html)199200    - [18.5.9.1. Режим отладки asyncio](https://python-all.ru/3.4/library/asyncio-dev.html#debug-mode-of-asyncio)201    - [18.5.9.2. Отмена](https://python-all.ru/3.4/library/asyncio-dev.html#cancellation)202    - [18.5.9.3. Конкурентность и многопоточность](https://python-all.ru/3.4/library/asyncio-dev.html#concurrency-and-multithreading)203    - [18.5.9.4. Корректная обработка блокирующих функций](https://python-all.ru/3.4/library/asyncio-dev.html#handle-blocking-functions-correctly)204    - [18.5.9.5. Логирование](https://python-all.ru/3.4/library/asyncio-dev.html#logging)205    - [18.5.9.6. Обнаружение объектов корутин, которые никогда не были запланированы](https://python-all.ru/3.4/library/asyncio-dev.html#detect-coroutine-objects-never-scheduled)206    - [18.5.9.7. Обнаружение необработанных исключений](https://python-all.ru/3.4/library/asyncio-dev.html#detect-exceptions-never-consumed)207    - [18.5.9.8. Правильное связывание корутин](https://python-all.ru/3.4/library/asyncio-dev.html#chain-coroutines-correctly)208    - [18.5.9.9. Уничтожение ожидающих задач](https://python-all.ru/3.4/library/asyncio-dev.html#pending-task-destroyed)209    - [18.5.9.10. Закрытие транспортов и циклов событий](https://python-all.ru/3.4/library/asyncio-dev.html#close-transports-and-event-loops)210- [18.6. `asyncore` – Асинхронный обработчик сокетов](https://python-all.ru/3.4/library/asyncore.html)211212  - [18.6.1. Пример asyncore: базовый HTTP-клиент](https://python-all.ru/3.4/library/asyncore.html#asyncore-example-basic-http-client)213  - [18.6.2. Пример asyncore: базовый эхо-сервер](https://python-all.ru/3.4/library/asyncore.html#asyncore-example-basic-echo-server)214- [18.7. `asynchat` – Асинхронный обработчик команд/ответов через сокеты](https://python-all.ru/3.4/library/asynchat.html)215216  - [18.7.1. asynchat – Вспомогательные классы](https://python-all.ru/3.4/library/asynchat.html#asynchat-auxiliary-classes)217  - [18.7.2. Пример asynchat](https://python-all.ru/3.4/library/asynchat.html#asynchat-example)218- [18.8. `signal` – Установка обработчиков асинхронных событий](https://python-all.ru/3.4/library/signal.html)219220  - [18.8.1. Общие правила](https://python-all.ru/3.4/library/signal.html#general-rules)221222    - [18.8.1.1. Выполнение обработчиков сигналов Python](https://python-all.ru/3.4/library/signal.html#execution-of-python-signal-handlers)223    - [18.8.1.2. Сигналы и потоки](https://python-all.ru/3.4/library/signal.html#signals-and-threads)224  - [18.8.2. Содержимое модуля](https://python-all.ru/3.4/library/signal.html#module-contents)225  - [18.8.3. Пример](https://python-all.ru/3.4/library/signal.html#example)226- [18.9. `mmap` – Поддержка файлов, отображаемых в память](https://python-all.ru/3.4/library/mmap.html)227