檔案(File)物件¶
These APIs are a minimal emulation of the Python 2 C API for built-in file
objects, which used to rely on the buffered I/O (FILE*
) support
from the C standard library. In Python 3, files and streams use the new
io
module, which defines several layers over the low-level unbuffered
I/O of the operating system. The functions described below are
convenience C wrappers over these new APIs, and meant mostly for internal
error reporting in the interpreter; third-party code is advised to access
the io
APIs instead.
-
PyFile_FromFd
(int fd, const char *name, const char *mode, int buffering, const char *encoding, const char *errors, const char *newline, int closefd)¶ - Return value: New reference.
根据已打开文件 fd 的文件描述符创建一个 Python 文件对象。 参数 name, encoding, errors 和 newline 可以为
NULL
表示使用默认值;buffering 可以为 -1 表示使用默认值。 name 会被忽略仅保留用于向下兼容。 失败时返回NULL
。 有关参数的更全面描述,请参阅io.open()
函数的文档。警告
Since Python streams have their own buffering layer, mixing them with OS-level file descriptors can produce various issues (such as unexpected ordering of data).
3.2 版更變: 忽略 name 屬性。
-
int
PyObject_AsFileDescriptor
(PyObject *p)¶ Return the file descriptor associated with p as an
int
. If the object is an integer, its value is returned. If not, the object'sfileno()
method is called if it exists; the method must return an integer, which is returned as the file descriptor value. Sets an exception and returns-1
on failure.
-
PyObject*
PyFile_GetLine
(PyObject *p, int n)¶ - Return value: New reference.
Equivalent to
p.readline([n])
, this function reads one line from the object p. p may be a file object or any object with areadline()
method. If n is0
, exactly one line is read, regardless of the length of the line. If n is greater than0
, no more than n bytes will be read from the file; a partial line can be returned. In both cases, an empty string is returned if the end of the file is reached immediately. If n is less than0
, however, one line is read regardless of length, butEOFError
is raised if the end of the file is reached immediately.
-
int
PyFile_SetOpenCodeHook
(Py_OpenCodeHookFunction handler)¶ 重载
io.open_code()
的正常行为,将其形参通过所提供的处理程序来传递。处理程序是一个类型为
PyObject *(*)(PyObject *path, void *userData)
的函数,其中 path 确保为PyUnicodeObject
。userData 指针会被传入钩子函数。 因于钩子函数可能由不同的运行时调用,该指针不应直接指向 Python 状态。
鉴于这个钩子专门在导入期间使用的,请避免在新模块执行期间进行导入操作,除非已知它们为冻结状态或者是在
sys.modules
中可用。一旦钩子被设定,它就不能被移除或替换,之后对
PyFile_SetOpenCodeHook()
的调用也将失败,如果解释器已经被初始化,函数将返回 -1 并设置一个异常。此函数可以安全地在
Py_Initialize()
之前调用。3.8 版新加入.