檔案物件 (File Objects)

這些 API 是用於內建檔案物件的 Python 2 C API 的最小模擬 (minimal emulation),它過去依賴於 C 標準函式庫對於緩衝 I/O (FILE*) 的支援。在 Python 3 中,檔案和串流使用新的io 模組,它在作業系統的低階無緩衝 I/O 上定義了多個層級。下面描述的函式是這些新 API 的便捷 C 包裝器,主要用於直譯器中的內部錯誤報告;建議第三方程式碼改為存取io API。

PyObject*PyFile_FromFd(intfd,constchar*name,constchar*mode,intbuffering,constchar*encoding,constchar*errors,constchar*newline,intclosefd)
回傳值:新的參照。穩定 ABI 的一部分.

Create a Python file object from the file descriptor of an alreadyopened filefd. The argumentsname,encoding,errors andnewlinecan beNULL to use the defaults;buffering can be-1 to use thedefault.name is ignored and kept for backward compatibility. ReturnNULL on failure. For a more comprehensive description of the arguments,please refer to theio.open() function documentation.

警告

由於 Python 串流有自己的緩衝層,將它們與作業系統層級檔案描述器混合使用會產生各種問題(例如資料的排序不符合預期)。

在 3.2 版的變更:忽略name 屬性。

intPyObject_AsFileDescriptor(PyObject*p)
穩定 ABI 的一部分.

回傳與p 關聯的檔案描述器作為int。如果物件是整數,則回傳其值。如果不是整數,則呼叫物件的fileno() 方法(如果存在);該方法必須回傳一個整數,它作為檔案描述器值回傳。設定例外並在失敗時回傳-1

PyObject*PyFile_GetLine(PyObject*p,intn)
回傳值:新的參照。穩定 ABI 的一部分.

Equivalent top.readline([n]), this function reads one line from theobjectp.p may be a file object or any object with areadline()method. Ifn is0, exactly one line is read, regardless of the length ofthe line. Ifn is greater than0, no more thann bytes will be readfrom the file; a partial line can be returned. In both cases, an empty stringis returned if the end of the file is reached immediately. Ifn is less than0, however, one line is read regardless of length, butEOFError israised if the end of the file is reached immediately.

intPyFile_SetOpenCodeHook(Py_OpenCodeHookFunctionhandler)

覆蓋io.open_code() 的正常行為以透過提供的處理程式 (handler) 傳遞其參數。

Thehandler is a function of type:

typedefPyObject*(*Py_OpenCodeHookFunction)(PyObject*,void*)

Equivalent ofPyObject*(*)(PyObject*path,void*userData), wherepath is guaranteed to bePyUnicodeObject.

userData 指標被傳遞到掛鉤函式 (hook function) 中。由於可能會從不同的執行環境 (runtime) 呼叫掛鉤函式,因此該指標不應直接指向 Python 狀態。

由於此掛鉤函式是在導入期間有意使用的,因此請避免在其執行期間導入新模組,除非它們已知有被凍結或在sys.modules 中可用。

Once a hook has been set, it cannot be removed or replaced, and later calls toPyFile_SetOpenCodeHook() will fail. On failure, the function returns-1 and sets an exception if the interpreter has been initialized.

Py_Initialize() 之前呼叫此函式是安全的。

不帶引數地引發一個稽核事件 (auditing event)setopencodehook

在 3.8 版被加入.

intPyFile_WriteObject(PyObject*obj,PyObject*p,intflags)
穩定 ABI 的一部分.

將物件obj 寫入檔案物件pflags 唯一支援的旗標是Py_PRINT_RAW;如果有給定,則寫入物件的str() 而不是repr()。在成功回傳0 或在失敗回傳-1;將設定適當的例外。

intPyFile_WriteString(constchar*s,PyObject*p)
穩定 ABI 的一部分.

寫入字串s 到 檔案物件p。當成功時回傳 0,而當失敗時回傳 -1,並會設定合適的例外狀況。