オペレーティングシステム関連のユーティリティ

PyObject* PyOS_FSPath(PyObject *path)
Return value: New reference.

path のファイルシステム表現を返します。オブジェクトが strbytes の場合は、その参照カウンタがインクリメントされます。オブジェクトが os.PathLike インターフェースを実装している場合、__fspath__() が呼び出され、その結果が strbytes であればその値が返されます。さもなければ、TypeError が送出され、NULL が返されます。

バージョン 3.6 で追加.

int Py_FdIsInteractive(FILE *fp, const char *filename)

filename という名前の標準 I/O ファイル fp が対話的 (interactive) であると考えられる場合に真 (非ゼロ) を返します。これは isatty(fileno(fp)) が真になるファイルの場合です。グローバルなフラグ Py_InteractiveFlag が真の場合には、 filename ポインタが NULL か、名前が '<stdin>' または '???' のいずれかに等しい場合にも真を返します。

void PyOS_BeforeFork()

プロセスがフォークする前に、いくつかの内部状態を準備するための関数です。fork() や現在のプロセスを複製するその他の類似の関数を呼び出す前にこの関数を呼びださなければなりません。fork() が定義されているシステムでのみ利用できます。

警告

The C fork() call should only be made from the "main" thread (of the "main" interpreter). The same is true for PyOS_BeforeFork().

バージョン 3.7 で追加.

void PyOS_AfterFork_Parent()

プロセスがフォークした後に内部状態を更新するための関数です。 fork() や、現在のプロセスを複製するその他の類似の関数を呼び出した後に、プロセスの複製が成功したかどうかにかかわらず、親プロセスからこの関数を呼び出さなければなりません。fork() が定義されているシステムでのみ利用できます。

警告

The C fork() call should only be made from the "main" thread (of the "main" interpreter). The same is true for PyOS_AfterFork_Parent().

バージョン 3.7 で追加.

void PyOS_AfterFork_Child()

Function to update internal interpreter state after a process fork. This must be called from the child process after calling fork(), or any similar function that clones the current process, if there is any chance the process will call back into the Python interpreter. Only available on systems where fork() is defined.

警告

The C fork() call should only be made from the "main" thread (of the "main" interpreter). The same is true for PyOS_AfterFork_Child().

バージョン 3.7 で追加.

参考

os.register_at_fork() を利用すると PyOS_BeforeFork()PyOS_AfterFork_Parent() PyOS_AfterFork_Child() によって呼び出されるカスタムのPython関数を登録できます。

void PyOS_AfterFork()

プロセスが fork した後の内部状態を更新するための関数です; fork 後 Python インタプリタを使い続ける場合、新たなプロセス内でこの関数を呼び出さねばなりません。新たなプロセスに新たな実行可能物をロードする場合、この関数を呼び出す必要はありません。

バージョン 3.7 で非推奨: この関数は PyOS_AfterFork_Child() によって置き換えられました。

int PyOS_CheckStack()

インタプリタがスタック空間を使い尽くしたときに真を返します。このチェック関数には信頼性がありますが、 USE_STACKCHECK が定義されている場合 (現状では Microsoft Visual C++ コンパイラでビルドした Windows 版) にしか利用できません . USE_STACKCHECK は自動的に定義されます; 自前のコードでこの定義を変更してはなりません。

PyOS_sighandler_t PyOS_getsig(int i)

シグナル i に対する現在のシグナルハンドラを返します。この関数は sigaction() または signal() のいずれかに対する薄いラッパーです。 sigaction()signal() を直接呼び出してはなりません! PyOS_sighandler_tvoid (*)(int) の typedef による別名です。

PyOS_sighandler_t PyOS_setsig(int i, PyOS_sighandler_t h)

シグナル i に対する現在のシグナルハンドラを h に設定します; 以前のシグナルハンドラを返します。この関数は sigaction() または signal() のいずれかに対する薄いラッパーです。 sigaction()signal() を直接呼び出してはなりません! PyOS_sighandler_tvoid (*)(int) の typedef による別名です。

wchar_t* Py_DecodeLocale(const char* arg, size_t *size)

surrogateescape エラーハンドラ を使って、ロケールエンコーディングのバイト文字列をデコードします: デコードできないバイトは U+DC80 から U+DCFF までの範囲の文字としてデコードされます。 バイト列がサロゲート文字としてデコードされる場合は、そのままデコードするのではなく surrogateescape エラーハンドラを使ってバイト列をエスケープします。

エンコーディング(優先度の高い順から):

  • UTF-8 on macOS, Android, and VxWorks;

  • UTF-8 on Windows if Py_LegacyWindowsFSEncodingFlag is zero;

  • UTF-8 Python UTF-8モードが有効な場合

  • ASCII if the LC_CTYPE locale is "C", nl_langinfo(CODESET) returns the ASCII encoding (or an alias), and mbstowcs() and wcstombs() functions uses the ISO-8859-1 encoding.

  • 現在のロケールエンコーディング

新しくメモリ確保されたワイドキャラクター文字列へのポインタを返します。 このメモリを解放するのには PyMem_RawFree() を使ってください。 引数 size が NULL でない場合は、 null 文字以外のワイドキャラクターの数を *size へ書き込みます。

デコードもしくはメモリ確保でエラーが起きると NULL を返します。 sizeNULL でない場合は、メモリエラーのときは (size_t)-1 を、デコードでのエラーのときは (size_t)-2*size に設定します。

C ライブラリーにバグがない限り、デコードでのエラーは起こりえません。

キャラクター文字列をバイト文字列に戻すには Py_EncodeLocale() 関数を使ってください。

バージョン 3.5 で追加.

バージョン 3.7 で変更: この関数は、UTF-8モードではUTF-8エンコーディングを利用するようになりました。

バージョン 3.8 で変更: The function now uses the UTF-8 encoding on Windows if Py_LegacyWindowsFSEncodingFlag is zero;

char* Py_EncodeLocale(const wchar_t *text, size_t *error_pos)

surrogateescape エラーハンドラ を使って、ワイドキャラクター文字列をロケールエンコーディングにエンコードします: U+DC80 から U+DCFF までの範囲のサロゲート文字は 0x80 から 0xFF までのバイトに変換されます。

エンコーディング(優先度の高い順から):

  • UTF-8 on macOS, Android, and VxWorks;

  • UTF-8 on Windows if Py_LegacyWindowsFSEncodingFlag is zero;

  • UTF-8 Python UTF-8モードが有効な場合

  • ASCII if the LC_CTYPE locale is "C", nl_langinfo(CODESET) returns the ASCII encoding (or an alias), and mbstowcs() and wcstombs() functions uses the ISO-8859-1 encoding.

  • 現在のロケールエンコーディング

この関数は、Python UTF-8モードではUTF-8エンコーディングを使います。

Return a pointer to a newly allocated byte string, use PyMem_Free() to free the memory. Return NULL on encoding error or memory allocation error.

If error_pos is not NULL, *error_pos is set to (size_t)-1 on success, or set to the index of the invalid character on encoding error.

バイト文字列をワイドキャラクター文字列に戻すには Py_DecodeLocale() 関数を使ってください。

バージョン 3.5 で追加.

バージョン 3.7 で変更: この関数は、UTF-8モードではUTF-8エンコーディングを利用するようになりました。

バージョン 3.8 で変更: The function now uses the UTF-8 encoding on Windows if Py_LegacyWindowsFSEncodingFlag is zero.

システム関数

sys モジュールが提供している機能にCのコードからアクセスする関数です。すべての関数は現在のインタプリタスレッドの sys モジュールの辞書に対して動作します。この辞書は内部のスレッド状態構造体に格納されています。

PyObject *PySys_GetObject(const char *name)
Return value: Borrowed reference.

sys モジュールの name オブジェクトを返すか、存在しなければ例外を設定せずに NULL を返します。

int PySys_SetObject(const char *name, PyObject *v)

vNULL で無い場合、 sys モジュールの namev を設定します。 vNULL なら、 sys モジュールから name を削除します。成功したら 0 を、エラー時は -1 を返します。

void PySys_ResetWarnOptions()

Reset sys.warnoptions to an empty list. This function may be called prior to Py_Initialize().

void PySys_AddWarnOption(const wchar_t *s)

Append s to sys.warnoptions. This function must be called prior to Py_Initialize() in order to affect the warnings filter list.

void PySys_AddWarnOptionUnicode(PyObject *unicode)

sys.warnoptionsunicode を追加します。

Note: this function is not currently usable from outside the CPython implementation, as it must be called prior to the implicit import of warnings in Py_Initialize() to be effective, but can't be called until enough of the runtime has been initialized to permit the creation of Unicode objects.

void PySys_SetPath(const wchar_t *path)

sys.pathpath に含まれるパスの、リストオブジェクトに設定します。 path はプラットフォームの検索パスデリミタ(Unixでは :, Windows では ;) で区切られたパスのリストでなければなりません。

void PySys_WriteStdout(const char *format, ...)

format で指定された出力文字列を sys.stdout に出力します。切り詰めが起こった場合を含め、例外は一切発生しません (後述)。

format は、フォーマット後の出力文字列のトータルの大きさを1000バイト以下に抑えるべきです。-- 1000 バイト以降の出力文字列は切り詰められます。特に、制限のない "%s" フォーマットを使うべきではありません。"%.<N>s" のようにして N に10進数の値を指定し、<N> + その他のフォーマット後の最大サイズが1000を超えないように設定するべきです。同じように "%f" にも気を付ける必要があります。非常に大きい数値に対して、数百の数字を出力する可能性があります。

問題が発生したり、 sys.stdout が設定されていなかった場合、フォーマット後のメッセージは本物の(Cレベルの) stdout に出力されます。

void PySys_WriteStderr(const char *format, ...)

PySys_WriteStdout() と同じですが、 sys.stderr もしくは stderr に出力します。

void PySys_FormatStdout(const char *format, ...)

PySys_WriteStdout() に似た関数ですが、 PyUnicode_FromFormatV() を使ってメッセージをフォーマットし、メッセージを任意の長さに切り詰めたりはしません。

バージョン 3.2 で追加.

void PySys_FormatStderr(const char *format, ...)

PySys_FormatStdout() と同じですが、 sys.stderr もしくは stderr に出力します。

バージョン 3.2 で追加.

void PySys_AddXOption(const wchar_t *s)

Parse s as a set of -X options and add them to the current options mapping as returned by PySys_GetXOptions(). This function may be called prior to Py_Initialize().

バージョン 3.2 で追加.

PyObject *PySys_GetXOptions()
Return value: Borrowed reference.

sys._xoptions と同様、 -X オプションの現在の辞書を返します。エラーが起きると、 NULL が返され、例外がセットされます。

バージョン 3.2 で追加.

int PySys_Audit(const char *event, const char *format, ...)

Raise an auditing event with any active hooks. Return zero for success and non-zero with an exception set on failure.

If any hooks have been added, format and other arguments will be used to construct a tuple to pass. Apart from N, the same format characters as used in Py_BuildValue() are available. If the built value is not a tuple, it will be added into a single-element tuple. (The N format option consumes a reference, but since there is no way to know whether arguments to this function will be consumed, using it may cause reference leaks.)

Note that # format characters should always be treated as Py_ssize_t, regardless of whether PY_SSIZE_T_CLEAN was defined.

sys.audit() performs the same function from Python code.

バージョン 3.8 で追加.

バージョン 3.8.2 で変更: Require Py_ssize_t for # format characters. Previously, an unavoidable deprecation warning was raised.

int PySys_AddAuditHook(Py_AuditHookFunction hook, void *userData)

Append the callable hook to the list of active auditing hooks. Return zero on success and non-zero on failure. If the runtime has been initialized, also set an error on failure. Hooks added through this API are called for all interpreters created by the runtime.

userData ポインタはフック関数に渡されます。 フック関数は別なランタイムから呼び出されるかもしれないので、このポインタは直接 Python の状態を参照すべきではありません。

This function is safe to call before Py_Initialize(). When called after runtime initialization, existing audit hooks are notified and may silently abort the operation by raising an error subclassed from Exception (other errors will not be silenced).

The hook function is of type int (*)(const char *event, PyObject *args, void *userData), where args is guaranteed to be a PyTupleObject. The hook function is always called with the GIL held by the Python interpreter that raised the event.

See PEP 578 for a detailed description of auditing. Functions in the runtime and standard library that raise events are listed in the audit events table. Details are in each function's documentation.

引数無しで 監査イベント sys.addaudithook を送出します。

バージョン 3.8 で追加.

プロセス制御

void Py_FatalError(const char *message)

致命的エラーメッセージ (fatal error message) を出力してプロセスを強制終了 (kill) します。後始末処理は行われません。この関数は、Python インタプリタを使い続けるのが危険であるような状況が検出されたとき; 例えば、オブジェクト管理が崩壊していると思われるときにのみ、呼び出されるようにしなければなりません。Unixでは、標準 C ライブラリ関数 abort() を呼び出して core を生成しようと試みます。

The Py_FatalError() function is replaced with a macro which logs automatically the name of the current function, unless the Py_LIMITED_API macro is defined.

バージョン 3.9 で変更: Log the function name automatically.

void Py_Exit(int status)

現在のプロセスを終了します。Py_FinalizeEx() を呼び出した後、標準Cライブラリ関数の exit(status) を呼び出します。Py_FinalizeEx() がエラーになった場合、終了ステータスは 120に設定されます。

バージョン 3.6 で変更: 終了処理のエラーは無視されなくなりました。

int Py_AtExit(void (*func)())

Py_FinalizeEx() から呼び出される後始末処理を行う関数 (cleanup function) を登録します。後始末関数は引数無しで呼び出され、値を返しません。最大で 32 の後始末処理関数を登録できます。登録に成功すると、 Py_AtExit()0 を返します; 失敗すると -1 を返します。最後に登録した後始末処理関数から先に呼び出されます。各関数は高々一度しか呼び出されません。 Python の内部的な終了処理は後始末処理関数より以前に完了しているので、 func からはいかなる Python API も呼び出してはなりません。