File objects

이 API는 C 표준 라이브러리의 버퍼링 된 I/O (FILE*) 지원에 의존하는 내장 파일 객체에 대한 파이썬 2 C API의 최소 에뮬레이션입니다. 파이썬 3에서, 파일과 스트림은 새로운 io 모듈을 사용합니다. 이 모듈은 운영 체제의 저수준 버퍼링 되지 않은 I/O 위에 여러 계층을 정의합니다. 아래에서 설명하는 함수는 이러한 새로운 API에 대한 편리한 C 래퍼이며, 주로 인터프리터의 내부 오류 보고를 위한 것입니다; 제삼자 코드는 대신 io API에 액세스하는 것이 좋습니다.

PyObject *PyFile_FromFd(int fd, const char *name, const char *mode, int buffering, const char *encoding, const char *errors, const char *newline, int closefd)
반환값: 새 참조. Part of the 안정 ABI.

이미 열려있는 파일의 파일 기술자 fd로 파이썬 파일 객체를 만듭니다. 인자 name, encoding, errors 및 newline은 기본값을 사용하기 위해 NULL 일 수 있습니다; buffering은 기본값을 사용하기 위해 -1 일 수 있습니다. name은 무시되고, 이전 버전과의 호환성을 위해 유지됩니다. 실패 시 NULL을 반환합니다. 인자에 대한 더 자세한 설명은 io.open() 함수 설명서를 참조하십시오.

경고

파이썬 스트림이 자체적인 버퍼링 계층을 가지고 있으므로, OS 수준의 파일 기술자와 혼합하면 여러 예기치 못한 문제가 발생할 수 있습니다 (가령 데이터의 예상치 못한 순서).

버전 3.2에서 변경: name 어트리뷰트를 무시합니다.

int PyObject_AsFileDescriptor(PyObject *p)
Part of the 안정 ABI.

p와 관련된 파일 기술자를 int로 반환합니다. 객체가 정수면, 값이 반환됩니다. 그렇지 않으면 객체의 fileno() 메서드가 있으면 호출됩니다; 메서드는 반드시 정수를 반환해야 하고, 그 값이 파일 기술자 값으로 반환됩니다. 실패하면 예외를 설정하고 -1을 반환합니다.

PyObject *PyFile_GetLine(PyObject *p, int n)
반환값: 새 참조. Part of the 안정 ABI.

p.readline([n])과 동등합니다. 이 함수는 객체 p에서 한 줄을 읽습니다. p는 파일 객체나 readline() 메서드가 있는 임의의 객체일 수 있습니다. n이 0이면, 줄의 길이와 관계없이 정확히 한 줄을 읽습니다. n이 0보다 크면, n 바이트 이상을 파일에서 읽지 않습니다; 불완전한 줄이 반환될 수 있습니다. 두 경우 모두, 파일 끝에 즉시 도달하면 빈 문자열이 반환됩니다. 그러나 n이 0보다 작으면, 길이와 관계없이 한 줄을 읽지만, 파일 끝에 즉시 도달하면 EOFError가 발생합니다.

char *Py_UniversalNewlineFgets(char *buf, int n, FILE *stream, PyObject *fobj)

Read a line from the C stream stream into the buffer buf, like the C standard library function fgets(), but treating all of \n, \r and \r\n as line endings (see universal newlines). Any \r or \r\n read from the stream is stored in buf as a single \n.

At most n - 1 characters are stored in buf; reading stops after a newline has been stored or when the end of the file is reached. The result is always null-terminated. stream should be opened in binary mode, so that the C library does not perform its own newline translation.

Return buf on success. Return NULL if no characters could be read, because stream is at end of file, a read error occurred, or n is less than 2. Like fgets(), this function does not distinguish between end of file and a read error, and it does not set an exception.

fobj exists only for backward compatibility and must be NULL.

int PyFile_SetOpenCodeHook(Py_OpenCodeHookFunction handler)

제공된 handler를 통해 매개 변수를 전달하도록 io.open_code()의 일반적인 동작을 재정의합니다.

handler는 다음과 같은 형의 함수입니다:

typedef PyObject *(*Py_OpenCodeHookFunction)(PyObject*, void*)

PyObject *(*)(PyObject *path, void *userData)와 동등합니다. 여기서 path는 PyUnicodeObject 임이 보장됩니다.

userData 포인터는 훅 함수로 전달됩니다. 훅 함수는 다른 런타임에서 호출될 수 있으므로, 이 포인터는 파이썬 상태를 직접 참조하면 안 됩니다.

이 훅은 의도적으로 임포트 중에 사용되므로, 고정되었거나(frozen) sys.modules에 있다고 알려진 경우가 아니라면 훅 실행 중에 새로운 모듈을 임포트하는 것을 피하십시오.

일단 훅이 설정되면, 제거하거나 교체할 수 없으며, 이후의 PyFile_SetOpenCodeHook()에 대한 호출은 실패합니다. 실패 시, 함수는 -1을 반환하고 인터프리터가 초기화되었으면 예외를 설정합니다.

이 함수는 Py_Initialize() 전에 호출해도 안전합니다.

인자 없이 감사 이벤트 setopencodehook을 발생시킵니다.

Added in version 3.8.

PyObject *PyFile_OpenCodeObject(PyObject *path)

Open path with the mode 'rb'. path must be a Python str object. The behavior of this function may be overridden by PyFile_SetOpenCodeHook() to allow for some preprocessing of the text.

This is analogous to io.open_code() in Python.

On success, this function returns a strong reference to a Python file object. On failure, this function returns NULL with an exception set.

Added in version 3.8.

PyObject *PyFile_OpenCode(const char *path)

Similar to PyFile_OpenCodeObject(), but path is a UTF-8 encoded const char*.

Added in version 3.8.

int PyFile_WriteObject(PyObject *obj, PyObject *p, int flags)
Part of the 안정 ABI.

Write object obj to file object p. The only supported flag for flags is Py_PRINT_RAW; if given, the str() of the object is written instead of the repr().

If obj is NULL, write the string "<NULL>".

Return 0 on success or -1 on failure; the appropriate exception will be set.

int PyFile_WriteString(const char *s, PyObject *p)
Part of the 안정 ABI.

문자열 s를 파일 객체 p에 씁니다. 성공하면 0을 반환하고, 실패하면 -1을 반환합니다; 적절한 예외가 설정됩니다.

Soft-deprecated API

These are APIs that were included in Python’s C API by mistake. They are documented solely for completeness; use other PyFile* APIs instead.

PyObject *PyFile_NewStdPrinter(int fd)

Use PyFile_FromFd() with defaults (fd, NULL, "w", -1, NULL, NULL, NULL, 0) instead.

Soft deprecated since version 3.15.

PyTypeObject PyStdPrinter_Type

Type of file-like objects used internally at Python startup when io is not yet available. Use Python open() or PyFile_FromFd() to create file objects instead.

Soft deprecated since version 3.15.

PY_STDIOTEXTMODE

The string literal "b", used to open files in binary mode. Exposed for backwards compatibility only.

Soft deprecated since version 3.15.1 (unreleased).