> For the complete documentation index, see [llms.txt](https://treasuremaster.gitbook.io/python-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://treasuremaster.gitbook.io/python-docs/moduli-standartnoi-biblioteki-1/setevoe-i-mezhprocessnoe-vzaimodeistvie/socket/obekty-soketov/socket.makefile.md).

# socket.makefile ()

### socket.makefile ( *mode='r'*, *buffering=None*, *\**, *encoding=None*, *errors=None*, *newline=None* )

Возвращает объект файла, связанный с сокетом. Точный возвращаемый тип зависит от аргументов, переданных **makefile ()**. Эти аргументы интерпретируются так же, как и встроенной функцией [open ()](/python-docs/vstroennye-obekty/vstroennye-funkcii/open.md), за исключением того, что поддерживаются только значения режима `'r'` (по умолчанию), `'w'` и `'b'`.

Сокет должен находиться в режиме блокировки; у него может быть тайм-аут, но внутренний буфер файлового объекта может оказаться в несогласованном состоянии, если произойдет тайм-аут.

Закрытие файлового объекта, возвращенного **makefile ()**, не приведет к закрытию исходного сокета, если все остальные файловые объекты не были закрыты и для объекта сокета не был вызван [socket.close ()](/python-docs/moduli-standartnoi-biblioteki-1/setevoe-i-mezhprocessnoe-vzaimodeistvie/socket/funkcii-soketov/socket.close.md).

{% hint style="info" %}
В Windows файловый объект, созданный **makefile ()**, не может использоваться там, где ожидается файловый объект с файловым дескриптором, например потоковые аргументы [subprocess.Popen ()](/python-docs/moduli-standartnoi-biblioteki-1/parallelnoe-vypolnenie/subprocess/subprocess.popen.md).
{% endhint %}

*Изменено в версии 3.5:* если системный вызов прерывается и обработчик сигнала не вызывает исключения, метод теперь повторяет системный вызов вместо того, чтобы вызывать исключение InterruptedError (объяснение см. в [PEP 475](https://www.python.org/dev/peps/pep-0475/)).

{% hint style="success" %}
*Преобразование двоичных данных в текст.* Простые сокеты передают данные в виде строк двоичных байтов, но благодаря тому, что файлы-обертки открываются в текстовом режиме, при выполнении операций ввода-вывода их содержимое автоматически преобразуется в текст. Файлы-обертки должны открываться в текстовом режиме, когда доступ к ним осуществляется с применением инструментов для работы со стандартными потоками ввода-вывода, таких как встроенная функция print, которая выводит текстовые строки (файлы, открытые в двоичном режиме, напротив, работают со строками байтов). Однако при непосредственном использовании сокетов, текст по-прежнему требуется кодировать в строки байтов вручную.
{% endhint %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://treasuremaster.gitbook.io/python-docs/moduli-standartnoi-biblioteki-1/setevoe-i-mezhprocessnoe-vzaimodeistvie/socket/obekty-soketov/socket.makefile.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
