這些 API 是用於內建檔案物件的 Python 2 C API 的最小模擬 (minimal emulation),它過去依賴於 C 標準函式庫對於緩衝 I/O (FILE*) 的支援。在 Python 3 中,檔案和串流使用新的 io
模組,它在作業系統的低階無緩衝 I/O 上定義了多個層級。下面描述的函式是這些新 API 的便捷 C 包裝器,主要用於直譯器中的內部錯誤報告;建議第三方程式碼改為存取 io
API。
Create a Python file object from the file descriptor of an already
opened file fd. The arguments name, encoding, errors and newline
can be NULL
to use the defaults; buffering can be -1 to use the
default. name is ignored and kept for backward compatibility. Return
NULL
on failure. For a more comprehensive description of the arguments,
please refer to the io.open()
function documentation.
警告
由於 Python 串流有自己的緩衝層,將它們與作業系統層級檔案描述器混合使用會產生各種問題(例如資料的排序不符合預期)。
在 3.2 版的變更: 忽略 name 屬性。
回傳與 p 關聯的檔案描述器作為 int。如果物件是整數,則回傳其值。如果不是整數,則呼叫物件的 fileno()
方法(如果存在);該方法必須回傳一個整數,它作為檔案描述器值回傳。設定例外並在失敗時回傳 -1
。
Equivalent to p.readline([n])
, this function reads one line from the
object p. p may be a file object or any object with a
readline()
method. If n is 0
, exactly one line is read, regardless of the length of
the line. If n is greater than 0
, 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 than
0
, however, one line is read regardless of length, but EOFError
is
raised if the end of the file is reached immediately.
覆蓋 io.open_code()
的正常行為以透過提供的處理程式 (handler) 傳遞其參數。
The handler is a function of type:
Equivalent of PyObject *(*)(PyObject *path, void *userData), where path is guaranteed to be
PyUnicodeObject
.
userData 指標被傳遞到掛鉤函式 (hook function) 中。由於可能會從不同的執行環境 (runtime) 呼叫掛鉤函式,因此該指標不應直接指向 Python 狀態。
由於此掛鉤函式是在導入期間有意使用的,因此請避免在其執行期間導入新模組,除非它們已知有被凍結或在 sys.modules
中可用。
Once a hook has been set, it cannot be removed or replaced, and later calls to
PyFile_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 版被加入.
將物件 obj 寫入檔案物件 p。 flags 唯一支援的旗標是 Py_PRINT_RAW
;如果有給定,則寫入物件的 str()
而不是 repr()
。在成功回傳 0
或在失敗回傳 -1
;將設定適當的例外。
寫入字串 s 到 檔案物件 p。當成功時回傳 0,而當失敗時回傳 -1,並會設定合適的例外狀況。