初期化 (initialization)、終了処理 (finalization)、スレッド

Python 初期化設定 も参照してください。

Python 初期化以前

Python が埋め込まれているアプリケーションでは、他の Python/C API 関数を使う前に Py_Initialize() 関数を呼ばなければなりません。これには例外として、いくつかの関数と グローバルな設定変数 があります。

次の関数は Python の初期化の前でも安全に呼び出せます:

グローバルな設定変数

Python には、様々な機能やオプションを制御するグローバルな設定のための変数があります。 デフォルトでは、これらのフラグは コマンドラインオプション で制御されます。

オプションでフラグがセットされると、フラグの値はそのオプションがセットされた回数になります。 例えば、 -b では Py_BytesWarningFlag が 1 に設定され、 -bb では Py_BytesWarningFlag が 2 に設定されます。

int Py_BytesWarningFlag

This API is kept for backward compatibility: setting PyConfig.bytes_warning should be used instead, see Python Initialization Configuration.

bytes または bytearraystr と比較した場合、または、 bytesint と比較した場合に警告を発生させます。 2 以上の値を設定している場合は、エラーを発生させます。

-b オプションで設定します。

バージョン 3.12 で非推奨.

int Py_DebugFlag

This API is kept for backward compatibility: setting PyConfig.parser_debug should be used instead, see Python Initialization Configuration.

パーサーのデバッグ出力を有効にします。(専門家専用です。コンパイルオプションに依存します)。

-d オプションと PYTHONDEBUG 環境変数で設定します。

バージョン 3.12 で非推奨.

int Py_DontWriteBytecodeFlag

This API is kept for backward compatibility: setting PyConfig.write_bytecode should be used instead, see Python Initialization Configuration.

非ゼロに設定した場合、Python はソースモジュールのインポート時に .pyc ファイルの作成を試みません。

-B オプションと PYTHONDONTWRITEBYTECODE 環境変数で設定します。

バージョン 3.12 で非推奨.

int Py_FrozenFlag

This API is kept for backward compatibility: setting PyConfig.pathconfig_warnings should be used instead, see Python Initialization Configuration.

Py_GetPath() の中でモジュール検索パスを割り出しているときのエラーメッセージを抑制します。

_freeze_module プログラムと frozenmain プログラムが使用する非公開フラグです。

バージョン 3.12 で非推奨.

int Py_HashRandomizationFlag

This API is kept for backward compatibility: setting PyConfig.hash_seed and PyConfig.use_hash_seed should be used instead, see Python Initialization Configuration.

PYTHONHASHSEED 環境変数が空でない文字列に設定された場合に、 1 が設定されます。

フラグがゼロでない場合、 PYTHONHASHSEED 環境変数を読みシークレットハッシュシードを初期化します。

バージョン 3.12 で非推奨.

int Py_IgnoreEnvironmentFlag

This API is kept for backward compatibility: setting PyConfig.use_environment should be used instead, see Python Initialization Configuration.

Ignore all PYTHON* environment variables, e.g. PYTHONPATH and PYTHONHOME, that might be set.

-E オプションと -I オプションで設定します。

バージョン 3.12 で非推奨.

int Py_InspectFlag

This API is kept for backward compatibility: setting PyConfig.inspect should be used instead, see Python Initialization Configuration.

最初の引数にスクリプトが指定されたときや -c オプションが利用された際に、 sys.stdin がターミナルに出力されないときであっても、スクリプトかコマンドを実行した後にインタラクティブモードに入ります。

-i オプションと PYTHONINSPECT 環境変数で設定します。

バージョン 3.12 で非推奨.

int Py_InteractiveFlag

This API is kept for backward compatibility: setting PyConfig.interactive should be used instead, see Python Initialization Configuration.

-i オプションで設定します。

バージョン 3.12 で非推奨.

int Py_IsolatedFlag

This API is kept for backward compatibility: setting PyConfig.isolated should be used instead, see Python Initialization Configuration.

Python を隔離モードで実行します。 隔離モードでは sys.path はスクリプトのディレクトリやユーザのサイトパッケージのディレクトリを含みません。

-I オプションで設定します。

バージョン 3.4 で追加.

バージョン 3.12 で非推奨.

int Py_LegacyWindowsFSEncodingFlag

This API is kept for backward compatibility: setting PyPreConfig.legacy_windows_fs_encoding should be used instead, see Python Initialization Configuration.

If the flag is non-zero, use the mbcs encoding with replace error handler, instead of the UTF-8 encoding with surrogatepass error handler, for the filesystem encoding and error handler.

PYTHONLEGACYWINDOWSFSENCODING 環境変数が空でない文字列に設定された場合に、 1 に設定されます。

より詳しくは PEP 529 を参照してください。

利用可能な環境: Windows 。

バージョン 3.12 で非推奨.

int Py_LegacyWindowsStdioFlag

This API is kept for backward compatibility: setting PyConfig.legacy_windows_stdio should be used instead, see Python Initialization Configuration.

If the flag is non-zero, use io.FileIO instead of io._WindowsConsoleIO for sys standard streams.

PYTHONLEGACYWINDOWSSTDIO 環境変数が空でない文字列に設定された場合に、 1 に設定されます。

より詳しくは PEP 528 を参照してください。

利用可能な環境: Windows 。

バージョン 3.12 で非推奨.

int Py_NoSiteFlag

This API is kept for backward compatibility: setting PyConfig.site_import should be used instead, see Python Initialization Configuration.

site モジュールの import と、そのモジュールが行なっていた site ごとの sys.path への操作を無効にします。後で site を明示的に import しても、これらの操作は実行されません (実行したい場合は、 site.main() を呼び出してください)。

-S オプションで設定します。

バージョン 3.12 で非推奨.

int Py_NoUserSiteDirectory

This API is kept for backward compatibility: setting PyConfig.user_site_directory should be used instead, see Python Initialization Configuration.

ユーザのサイトパッケージのディレクトリsys.path に追加しません。

-s オプション、 -IPYTHONNOUSERSITE 環境変数で設定します。

バージョン 3.12 で非推奨.

int Py_OptimizeFlag

This API is kept for backward compatibility: setting PyConfig.optimization_level should be used instead, see Python Initialization Configuration.

-O オプションと PYTHONOPTIMIZE 環境変数で設定します。

バージョン 3.12 で非推奨.

int Py_QuietFlag

This API is kept for backward compatibility: setting PyConfig.quiet should be used instead, see Python Initialization Configuration.

インタラクティブモードでも copyright とバージョンのメッセージを表示しません。

-q オプションで設定します。

バージョン 3.2 で追加.

バージョン 3.12 で非推奨.

int Py_UnbufferedStdioFlag

This API is kept for backward compatibility: setting PyConfig.buffered_stdio should be used instead, see Python Initialization Configuration.

標準出力と標準エラーをバッファリングしないように強制します。

-u オプションと PYTHONUNBUFFERED 環境変数で設定します。

バージョン 3.12 で非推奨.

int Py_VerboseFlag

This API is kept for backward compatibility: setting PyConfig.verbose should be used instead, see Python Initialization Configuration.

モジュールが初期化されるたびにメッセージを出力し、それがどこ (ファイル名やビルトインモジュール) からロードされたのかを表示します。 値が 2 以上の場合は、モジュールを検索するときにチェックしたファイルごとにメッセージを出力します。また、終了時のモジュールクリーンアップに関する情報も提供します。

-v オプションと PYTHONVERBOSE 環境変数で設定します。

バージョン 3.12 で非推奨.

インタープリタの初期化と終了処理

void Py_Initialize()
Part of the Stable ABI.

Python インタープリタを初期化します。 Python の埋め込みを行うアプリケーションでは、他のあらゆる Python/C API を使用するよりも前にこの関数を呼び出さなければなりません。いくつかの例外については Python 初期化以前 を参照してください。

この関数はロード済みモジュールのテーブル (sys.modules) を初期化し、基盤となるモジュール群、 builtins, __main__, sys を生成します。また、モジュール検索パス (sys.path) も初期化します。 sys.argv の設定は行いません。設定するには、 PySys_SetArgvEx() を使ってください。この関数を (Py_FinalizeEx() を呼ばずに) 再度呼び出しても何も行いません。戻り値はありません。初期化が失敗すれば、それは致命的なエラーです。

Use the Py_InitializeFromConfig() function to customize the Python Initialization Configuration.

注釈

Windows では O_TEXT から O_BINARY へコンソールモードが変更されますが、これはその C ランタイムを使っているコンソールでの Python 以外の使い勝手にも影響を及ぼします。

void Py_InitializeEx(int initsigs)
Part of the Stable ABI.

initsigs1 を指定した場合、この関数は Py_Initialize() と同じように動作します。 initsigs0 を指定した場合、初期化時のシグナルハンドラの登録をスキップすることができ、これは Python の埋め込みで便利でしょう。

Use the Py_InitializeFromConfig() function to customize the Python Initialization Configuration.

int Py_IsInitialized()
Part of the Stable ABI.

Python インタプリタが初期化済みであれば真(非ゼロ)を、さもなければ偽(ゼロ)を返します。Py_FinalizeEx() を呼び出した後は、Py_Initialize() を再び呼び出すまで、この関数は偽を返します。

int Py_FinalizeEx()
Part of the Stable ABI since version 3.6.

Py_Initialize() とそれ以後の Python/C API 関数で行った全ての初期化処理を取り消し、最後の Py_Initialize() 呼び出し以後に Python インタプリタが生成した全てのサブインタプリタ (sub-interpreter, 下記の Py_NewInterpreter() を参照) を消去します。 理想的な状況では、この関数によって Python インタプリタが確保したメモリは全て解放されます。 この関数を (Py_Initialize() を呼ばずに) 再度呼び出しても何も行いません。 通常は返り値は 0 です。終了処理中 (バッファリングされたデータの書き出し) のエラーがあった場合は -1 が返されます。

この関数が提供されている理由はいくつかあります。Python の埋め込みを行っているアプリケーションでは、アプリケーションを再起動することなく Python を再起動したいことがあります。また、動的ロード可能イブラリ (あるいは DLL) から Python インタプリタをロードするアプリケーションでは、DLL をアンロードする前に Python が確保したメモリを全て解放したいと考えるかもしれません。アプリケーション内で起きているメモリリークを追跡する際に、開発者は Python が確保したメモリをアプリケーションの終了前に解放させたいと思う場合もあります。

Bugs and caveats: The destruction of modules and objects in modules is done in random order; this may cause destructors (__del__() methods) to fail when they depend on other objects (even functions) or modules. Dynamically loaded extension modules loaded by Python are not unloaded. Small amounts of memory allocated by the Python interpreter may not be freed (if you find a leak, please report it). Memory tied up in circular references between objects is not freed. Some memory allocated by extension modules may not be freed. Some extensions may not work properly if their initialization routine is called more than once; this can happen if an application calls Py_Initialize() and Py_FinalizeEx() more than once.

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

バージョン 3.6 で追加.

void Py_Finalize()
Part of the Stable ABI.

この関数は Py_FinalizeEx() の後方互換性バージョンで、戻り値がありません。

プロセスワイドのパラメータ

int Py_SetStandardStreamEncoding(const char *encoding, const char *errors)

This API is kept for backward compatibility: setting PyConfig.stdio_encoding and PyConfig.stdio_errors should be used instead, see Python Initialization Configuration.

もし Py_Initialize() が呼ばれるなら、この関数はその前に呼ばなければなりません。標準の IO において、どのエンコーディングおよびどんなエラー処理を使うかを、 str.encode() と同様の意味で指定します。

これは、環境変数が働かない時に PYTHONIOENCODING の値を上書きし、埋め込みコードが IO エンコーディングをコントロールできるようにします。

encodingerrors のどちらかまたは両方を NULL にすることで、 PYTHONIOENCODING とデフォルト値のどちらかまたは両方を使うことができます (他の設定に依存します)。

この設定 (あるいは他の設定) に関わらず、 sys.stderr は常に "backslashreplace" エラーハンドラを使うことに注意してください。

Py_FinalizeEx() を呼び出した場合は、Py_Initialize() を呼び出す前に、この関数を再度呼び出す必要があるでしょう。

成功したら 0 を、エラーの場合は 0 でない値を返します (例えば、インタプリタが初期化された後に、この関数が呼び出された場合)。

バージョン 3.4 で追加.

バージョン 3.11 で非推奨.

void Py_SetProgramName(const wchar_t *name)
Part of the Stable ABI.

This API is kept for backward compatibility: setting PyConfig.program_name should be used instead, see Python Initialization Configuration.

この関数を呼び出すなら、最初に Py_Initialize() を呼び出すよりも前に呼び出さなければなりません。この関数はインタプリタにプログラムの main() 関数に指定した argv[0] 引数の値を教えます (ワイドキャラクタに変換されます)。この引数値は、 Py_GetPath() や、以下に示すその他の関数が、インタプリタの実行可能形式から Python ランタイムライブラリへの相対パスを取得するために使われます。デフォルトの値は 'python' です。引数はゼロ終端されたワイドキャラクタ文字列で、静的な記憶領域に入っていなければならず、その内容はプログラムの実行中に変更してはなりません。 Python インタプリタ内のコードで、この記憶領域の内容を変更するものは一切ありません。

Use Py_DecodeLocale() to decode a bytes string to get a wchar_t* string.

バージョン 3.11 で非推奨.

wchar_t *Py_GetProgramName()
Part of the Stable ABI.

Py_SetProgramName() で設定されたプログラム名か、デフォルトのプログラム名を返します。関数が返す文字列ポインタは静的な記憶領域を返します。関数の呼び出し側はこの値を変更できません。

This function should not be called before Py_Initialize(), otherwise it returns NULL.

バージョン 3.10 で変更: It now returns NULL if called before Py_Initialize().

wchar_t *Py_GetPrefix()
Part of the Stable ABI.

プラットフォーム非依存のファイル群がインストールされている場所である prefix を返します。この値は Py_SetProgramName() でセットされたプログラム名やいくつかの環境変数をもとに、数々の複雑な規則から導出されます。例えば、プログラム名が '/usr/local/bin/python' の場合、prefix は '/usr/local' になります。関数が返す文字列ポインタは静的な記憶領域を返します; 関数の呼び出し側はこの値を変更できません。この値はトップレベルの Makefile に指定されている変数 prefix や、ビルド値に configure スクリプトに指定した --prefix 引数に対応しています。この値は Python コードからは sys.prefix として利用できます。これはUnixでのみ有用です。次に説明する関数も参照してください。

This function should not be called before Py_Initialize(), otherwise it returns NULL.

バージョン 3.10 で変更: It now returns NULL if called before Py_Initialize().

wchar_t *Py_GetExecPrefix()
Part of the Stable ABI.

プラットフォーム 依存 のファイルがインストールされている場所である exec-prefix を返します。この値は Py_SetProgramName() でセットされたプログラム名やいくつかの環境変数をもとに、数々の複雑な規則から導出されます。例えば、プログラム名が '/usr/local/bin/python' の場合、exec-prefix は '/usr/local' になります。関数が返す文字列ポインタは静的な記憶領域を返します; 関数の呼び出し側はこの値を変更できません。この値はトップレベルの Makefile に指定されている変数 exec_prefix や、ビルド値に configure スクリプトに指定した --exec-prefix 引数に対応しています。この値は Python コードからは sys.exec_prefix として利用できます。 Unixのみで有用です。

背景: プラットフォーム依存のファイル (実行形式や共有ライブラリ) が別のディレクトリツリー内にインストールされている場合、 exec-prefix は prefix と異なります。典型的なインストール形態では、プラットフォーム非依存のファイルが /usr/local に収められる一方、プラットフォーム依存のファイルは /usr/local/plat サブツリーに収められます。

一般的に、プラットフォームとは、ハードウェアとソフトウェアファミリの組み合わせを指します。例えば、Solaris 2.x を動作させている Sparc マシンは全て同じプラットフォームであるとみなしますが、Solaris 2.x を動作させている Intel マシンは違うプラットフォームになりますし、同じ Intel マシンでも Linux を動作させているならまた別のプラットフォームです。一般的には、同じオペレーティングシステムでも、メジャーリビジョンの違うものは異なるプラットフォームです。非 Unix のオペレーティングシステムの場合は話はまた別です; 非 Unix のシステムでは、インストール方法はとても異なっていて、prefix や exec-prefix には意味がなく、空文字列が設定されています。コンパイル済みの Python バイトコードはプラットフォームに依存しないので注意してください (ただし、どのバージョンの Python でコンパイルされたかには依存します!)。

システム管理者は、 mountautomount プログラムを使って、各プラットフォーム用の /usr/local/plat を異なったファイルシステムに置き、プラットフォーム間で /usr/local を共有するための設定方法を知っているでしょう。

This function should not be called before Py_Initialize(), otherwise it returns NULL.

バージョン 3.10 で変更: It now returns NULL if called before Py_Initialize().

wchar_t *Py_GetProgramFullPath()
Part of the Stable ABI.

Python 実行可能形式の完全なプログラム名を返します; この値はデフォルトのモジュール検索パスを (前述の Py_SetProgramName() で設定された) プログラム名から導出する際に副作用的に計算されます。関数が返す文字列ポインタは静的な記憶領域を返します; 関数の呼び出し側はこの値を変更できません。この値は Python コードからは sys.executable として利用できます。

This function should not be called before Py_Initialize(), otherwise it returns NULL.

バージョン 3.10 で変更: It now returns NULL if called before Py_Initialize().

wchar_t *Py_GetPath()
Part of the Stable ABI.

デフォルトのモジュール検索パスを返します; パスは (上の Py_SetProgramName() で設定された) プログラム名と、いくつかの環境変数から計算されます。戻り値となる文字列は、プラットフォーム依存のパス区切り文字で分割された一連のディレクトリ名からなります。区切り文字は Unix と macOS では ':', Windows では ';' です。関数が返す文字列ポインタは静的な記憶領域を返します; 関数の呼び出し側はこの値を変更できません。 sys.path はインタプリタによってこの値で初期化され、その後にモジュールをロードする際の検索パスを変更するために修正することが可能で、たいていそうされます。

This function should not be called before Py_Initialize(), otherwise it returns NULL.

バージョン 3.10 で変更: It now returns NULL if called before Py_Initialize().

void Py_SetPath(const wchar_t*)
Part of the Stable ABI since version 3.7.

This API is kept for backward compatibility: setting PyConfig.module_search_paths and PyConfig.module_search_paths_set should be used instead, see Python Initialization Configuration.

デフォルトのモジュール検索パスを設定します。この関数が Py_Initialize() より前に呼び出された場合、 Py_GetPath() はデフォルトの検索パスを計算しようとせず、代わりにこの関数が与えた検索パスを返します。これは、 Python がアプリケーションに組み込まれていて、そのアプリケーションが全てのモジュールの場所を完全に把握しているときに便利です。パスはプラットフォーム依存の区切り文字で分割されている必要があります。区切り文字は Unix と macOS では ':' 、Windows では ';' です。

This also causes sys.executable to be set to the program full path (see Py_GetProgramFullPath()) and for sys.prefix and sys.exec_prefix to be empty. It is up to the caller to modify these if required after calling Py_Initialize().

バイト文字列を wchar_* 文字列にデコードするには Py_DecodeLocale() を使ってください。

パス引数は内部でコピーされます。したがって、呼び出し完了後に呼び出し元は引数を解放できます。

バージョン 3.8 で変更: プログラムの名前に代わって、プログラムのフルパスが sys.executable に使われるようになりました。

バージョン 3.11 で非推奨.

const char *Py_GetVersion()
Part of the Stable ABI.

Python インタプリタのバージョンを返します。バージョンは、次のような形式の文字列です

"3.0a5+ (py3k:63103M, May 12 2008, 00:53:55) \n[GCC 4.2.3]"

第一ワード (最初のスペース文字まで) は、現在の Python のバージョンです; 最初の文字は、ピリオドで区切られたメジャーバージョンとマイナーバージョンです。関数が返す文字列ポインタは静的な記憶領域を返します; 関数の呼び出し側はこの値を変更できません。この値は Python コードからは sys.version として利用できます。

See also the Py_Version constant.

const char *Py_GetPlatform()
Part of the Stable ABI.

現在のプラットフォームのプラットフォーム識別文字列を返します。Unixでは、オペレーティングシステムの "公式の" 名前を小文字に変換し、後ろにメジャーリビジョン番号を付けた構成になっています。例えば Solaris 2.x は、SunOS 5.x, としても知られていますが、'sunos5' になります。macOS では 'darwin' です。Windows では 'win' です。関数が返す文字列ポインタは静的な記憶領域を返します; 関数の呼び出し側はこの値を変更できません。この値は Python コードからは sys.platform として利用できます。

const char *Py_GetCopyright()
Part of the Stable ABI.

現在の Python バージョンに対する公式の著作権表示文字列を返します。例えば

'Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam'

関数が返す文字列ポインタは静的な記憶領域を返します; 関数の呼び出し側はこの値を変更できません。この値は Python コードからは sys.copyright として利用できます。

const char *Py_GetCompiler()
Part of the Stable ABI.

現在使っているバージョンの Python をビルドする際に用いたコンパイラを示す文字列を、角括弧で囲った文字列を返します。例えば:

"[GCC 2.7.2.2]"

関数が返す文字列ポインタは静的な記憶領域を返します; 関数の呼び出し側はこの値を変更できません。この値は Python コードからは sys.version の一部として取り出せます。

const char *Py_GetBuildInfo()
Part of the Stable ABI.

現在使っている Python インタプリタインスタンスの、シーケンス番号とビルド日時に関する情報を返します。例えば

"#67, Aug  1 1997, 22:34:28"

関数が返す文字列ポインタは静的な記憶領域を返します; 関数の呼び出し側はこの値を変更できません。この値は Python コードからは sys.version の一部として取り出せます。

void PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
Part of the Stable ABI.

This API is kept for backward compatibility: setting PyConfig.argv, PyConfig.parse_argv and PyConfig.safe_path should be used instead, see Python Initialization Configuration.

argc および argv に基づいて sys.argv を設定します。これらの引数はプログラムの main() に渡した引数に似ていますが、最初の要素が Python インタプリタの宿主となっている実行形式の名前ではなく、実行されるスクリプト名を参照しなければならない点が違います。実行するスクリプトがない場合、 argv の最初の要素は空文字列にしてもかまいません。この関数が sys.argv の初期化に失敗した場合、致命的エラーを Py_FatalError() で知らせます。

updatepath が 0 の場合、ここまでの動作がこの関数がすることの全てです。 updatepath が 0 でない場合、この関数は sys.path を以下のアルゴリズムに基づいて修正します:

  • 存在するスクリプトの名前が argv[0] に渡された場合、そのスクリプトがある場所の絶対パスを sys.path の先頭に追加します。

  • それ以外の場合 (argc0 だったり、 argv[0] が存在するファイル名を指していない場合)、 sys.path の先頭に空の文字列を追加します。 これは現在の作業ディレクトリ (".") を先頭に追加するのと同じです。

バイト文字列を wchar_* 文字列にデコードするには Py_DecodeLocale() を使ってください。

See also PyConfig.orig_argv and PyConfig.argv members of the Python Initialization Configuration.

注釈

単一のスクリプトを実行する以外の目的でPython インタプリタを埋め込んでいるアプリケーションでは、 updatepath0 を渡して、必要な場合は自分で sys.path を更新することをおすすめします。 CVE-2008-5983 を参照してください。

3.1.3 より前のバージョンでは、 PySys_SetArgv() の呼び出しが完了した後に sys.path の先頭の要素を取り出すことで、同じ効果が得られます。例えばこのように使います:

PyRun_SimpleString("import sys; sys.path.pop(0)\n");

バージョン 3.1.3 で追加.

バージョン 3.11 で非推奨.

void PySys_SetArgv(int argc, wchar_t **argv)
Part of the Stable ABI.

This API is kept for backward compatibility: setting PyConfig.argv and PyConfig.parse_argv should be used instead, see Python Initialization Configuration.

この関数は、 python インタプリタが -I オプション付きで実行されている場合を除き PySys_SetArgvEx()updatepath1 を設定したのと同じように動作します。

バイト文字列を wchar_* 文字列にデコードするには Py_DecodeLocale() を使ってください。

See also PyConfig.orig_argv and PyConfig.argv members of the Python Initialization Configuration.

バージョン 3.4 で変更: updatepath の値は -I オプションに依存します。

バージョン 3.11 で非推奨.

void Py_SetPythonHome(const wchar_t *home)
Part of the Stable ABI.

This API is kept for backward compatibility: setting PyConfig.home should be used instead, see Python Initialization Configuration.

Python の標準ライブラリがある、デフォルトの "home" ディレクトリを設定します。引数の文字列の意味については PYTHONHOME を参照してください。

引数は静的なストレージに置かれてプログラム実行中に書き換えられないようなゼロ終端の文字列であるべきです。Python インタプリタはこのストレージの内容を変更しません。

バイト文字列を wchar_* 文字列にデコードするには Py_DecodeLocale() を使ってください。

バージョン 3.11 で非推奨.

wchar_t *Py_GetPythonHome()
Part of the Stable ABI.

前回の Py_SetPythonHome() 呼び出しで設定されたデフォルトの "home" か、 PYTHONHOME 環境変数が設定されていればその値を返します。

This function should not be called before Py_Initialize(), otherwise it returns NULL.

バージョン 3.10 で変更: It now returns NULL if called before Py_Initialize().

スレッド状態 (thread state) とグローバルインタプリタロック (global interpreter lock)

Python インタプリタは完全にはスレッドセーフではありません。マルチスレッドの Python プログラムをサポートするために、 グローバルインタプリタロック あるいは GIL と呼ばれるグローバルなロックが存在していて、現在のスレッドが Python オブジェクトに安全にアクセスする前に必ずロックを獲得しなければならなくなっています。ロック機構がなければ、単純な操作でさえ、マルチスレッドプログラムの実行に問題を引き起こす可能性があります。たとえば、二つのスレッドが同じオブジェクトの参照カウントを同時にインクリメントすると、結果的に参照カウントは二回でなく一回だけしかインクリメントされないかもしれません。

このため、 GIL を獲得したスレッドだけが Python オブジェクトを操作したり、 Python/C API 関数を呼び出したりできるというルールがあります。並行処理をエミュレートするために、インタプリタは定期的にロックを解放したり獲得したりします。 (sys.setswitchinterval() を参照) このロックはブロックが起こりうる I/O 操作の付近でも解放・獲得され、 I/O を要求するスレッドが I/O 操作の完了を待つ間、他のスレッドが動作できるようにしています。

Python インタプリタはスレッドごとに必要な情報を PyThreadState と呼ばれるデータ構造の中に保存します。そしてグローバル変数として現在の PyThreadState を指すポインタを1つ持ちます。このグローバル変数は PyThreadState_Get() を使って取得できます。

拡張コード内で GIL を解放する

GIL を操作するほとんどのコードは、次のような単純な構造になります:

Save the thread state in a local variable.
Release the global interpreter lock.
... Do some blocking I/O operation ...
Reacquire the global interpreter lock.
Restore the thread state from the local variable.

この構造は非常に一般的なので、作業を単純にするために2つのマクロが用意されています:

Py_BEGIN_ALLOW_THREADS
... Do some blocking I/O operation ...
Py_END_ALLOW_THREADS

Py_BEGIN_ALLOW_THREADS マクロは新たなブロックを開始し、隠しローカル変数を宣言します; Py_END_ALLOW_THREADS はブロックを閉じます。

上のブロックは次のコードに展開されます:

PyThreadState *_save;

_save = PyEval_SaveThread();
... Do some blocking I/O operation ...
PyEval_RestoreThread(_save);

これらの関数の動作を説明します。GIL は現在のスレッド状態を指すポインタを保護するために使われます。ロックを解放してスレッド状態を退避する際、ロックを解放する前に現在のスレッド状態ポインタを取得しておかなければなりません (他のスレッドがすぐさまロックを獲得して、自らのスレッド状態をグローバル変数に保存してしまうかもしれないからです)。逆に、ロックを獲得してスレッド状態を復帰する際には、グローバル変数にスレッド状態ポインタを保存する前にロックを獲得しておかなければなりません。

注釈

GIL を解放するのはほとんどがシステムのI/O関数を呼び出す時ですが、メモリバッファに対する圧縮や暗号化のように、 Python のオブジェクトにアクセスしない長時間かかる計算処理を呼び出すときも GIL を解放することは有益です。例えば、 zlibhashlib モジュールは圧縮やハッシュ計算の前に GIL を解放します。

Python 以外で作られたスレッド

Python API を通して作られたスレッド (threading モジュールなど) では自動的にスレッド状態が割り当てられて、上記のコードは正しく動きます。しかし、(自前でスレッド管理を行う外部のライブラリなどにより)C言語でスレッドを生成した場合、そのスレッドには GIL がなく、スレッド状態データ構造体もないことに注意する必要があります。

このようなスレッドから Python コードを呼び出す必要がある場合 (外部のライブラリからコールバックするAPIなどがよくある例です)、Python/C API を呼び出す前に、スレッド状態データ構造体を生成し、GIL を獲得し、スレッド状態ポインタを保存することで、スレッドをインタプリタに登録しなければなりません。スレッドが作業を終えたら、スレッド状態ポインタをリセットして、ロックを解放し、最後にスレッド状態データ構造体のメモリを解放しなければなりません。

PyGILState_Ensure()PyGILState_Release() はこの処理を自動的に行います。 Cのスレッドから Python を呼び出す典型的な方法は以下のとおりです:

PyGILState_STATE gstate;
gstate = PyGILState_Ensure();

/* Perform Python actions here. */
result = CallSomeFunction();
/* evaluate result or handle exception */

/* Release the thread. No Python API allowed beyond this point. */
PyGILState_Release(gstate);

PyGILState_* 関数は、(Py_Initialize() によって自動的に作られる) グローバルインタプリタ1つだけが存在すると仮定する事に気をつけて下さい。 Python は (Py_NewInterpreter() を使って) 追加のインタプリタを作成できることに変わりはありませんが、複数インタプリタと PyGILState_* API を混ぜて使うことはサポートされていません。

Cautions about fork()

Another important thing to note about threads is their behaviour in the face of the C fork() call. On most systems with fork(), after a process forks only the thread that issued the fork will exist. This has a concrete impact both on how locks must be handled and on all stored state in CPython's runtime.

The fact that only the "current" thread remains means any locks held by other threads will never be released. Python solves this for os.fork() by acquiring the locks it uses internally before the fork, and releasing them afterwards. In addition, it resets any Lock オブジェクト in the child. When extending or embedding Python, there is no way to inform Python of additional (non-Python) locks that need to be acquired before or reset after a fork. OS facilities such as pthread_atfork() would need to be used to accomplish the same thing. Additionally, when extending or embedding Python, calling fork() directly rather than through os.fork() (and returning to or calling into Python) may result in a deadlock by one of Python's internal locks being held by a thread that is defunct after the fork. PyOS_AfterFork_Child() tries to reset the necessary locks, but is not always able to.

The fact that all other threads go away also means that CPython's runtime state there must be cleaned up properly, which os.fork() does. This means finalizing all other PyThreadState objects belonging to the current interpreter and all other PyInterpreterState objects. Due to this and the special nature of the "main" interpreter, fork() should only be called in that interpreter's "main" thread, where the CPython global runtime was originally initialized. The only exception is if exec() will be called immediately after.

高レベルAPI

C拡張を書いたりPythonインタプリタを埋め込むときに最も一般的に使われる型や関数は次のとおりです:

type PyInterpreterState
Part of the Limited API (as an opaque struct).

このデータ構造体は、協調動作する多数のスレッド間で共有されている状態を表現します。同じインタプリタに属するスレッドはモジュール管理情報やその他いくつかの内部的な情報を共有しています。この構造体には公開 (public) のメンバはありません。

異なるインタプリタに属するスレッド間では、利用可能なメモリ、開かれているファイルデスクリプタなどといったプロセス状態を除いて、初期状態では何も共有されていません。GILもまた、スレッドがどのインタプリタに属しているかに関わらずすべてのスレッドで共有されています。

type PyThreadState
Part of the Limited API (as an opaque struct).

This data structure represents the state of a single thread. The only public data member is:

PyInterpreterState *interp

This thread's interpreter state.

void PyEval_InitThreads()
Part of the Stable ABI.

Deprecated function which does nothing.

In Python 3.6 and older, this function created the GIL if it didn't exist.

バージョン 3.9 で変更: The function now does nothing.

バージョン 3.7 で変更: この関数は Py_Initialize() から呼び出されるようになり、わざわざ呼び出す必要はもう無くなりました。

バージョン 3.2 で変更: この関数は Py_Initialize() より前に呼び出すことができなくなりました。

バージョン 3.9 で非推奨.

int PyEval_ThreadsInitialized()
Part of the Stable ABI.

PyEval_InitThreads() をすでに呼び出している場合は真 (非ゼロ) を返します。この関数は、GILを獲得せずに呼び出すことができますので、シングルスレッドで実行している場合にはロック関連のAPI呼び出しを避けるために使うことができます。

バージョン 3.7 で変更: GILPy_Initialize() で初期化されるようになりました。

バージョン 3.9 で非推奨.

PyThreadState *PyEval_SaveThread()
Part of the Stable ABI.

(GIL が生成されている場合) GILを解放して、スレッドの状態を NULL にし、以前のスレッド状態 (NULL にはなりません) を返します。 ロックがすでに生成されている場合、現在のスレッドがロックを獲得していなければなりません。

void PyEval_RestoreThread(PyThreadState *tstate)
Part of the Stable ABI.

(GIL が生成されている場合) GIL を獲得して、現在のスレッド状態を tstate に設定します。 tstateNULL であってはなりません。 GIL が生成されていて、この関数を呼び出したスレッドがすでにロックを獲得している場合、デッドロックに陥ります。

注釈

Calling this function from a thread when the runtime is finalizing will terminate the thread, even if the thread was not created by Python. You can use _Py_IsFinalizing() or sys.is_finalizing() to check if the interpreter is in process of being finalized before calling this function to avoid unwanted termination.

PyThreadState *PyThreadState_Get()
Part of the Stable ABI.

現在のスレッド状態を返します。GIL を保持していなければなりません。現在のスレッド状態が NULL なら、(呼び出し側が NULL チェックをしなくてすむように) この関数は致命的エラーを起こすようになっています。

PyThreadState *PyThreadState_Swap(PyThreadState *tstate)
Part of the Stable ABI.

現在のスレッド状態を tstate に指定したスレッド状態と入れ変えます。tstateNULL の場合があります。GIL を保持していなければならず、解放しません。

以下の関数はスレッドローカルストレージを利用していて、サブインタプリタとの互換性がありません:

PyGILState_STATE PyGILState_Ensure()
Part of the Stable ABI.

Pythonの状態やGILに関わらず、実行中スレッドでPython C APIの呼び出しが可能となるようにします。この関数はスレッド内で何度でも呼び出すことができますが、必ず全ての呼び出しに対応して PyGILState_Release() を呼び出す必要があります。通常、 PyGILState_Ensure() 呼び出しと PyGILState_Release() 呼び出しの間でこれ以外のスレッド関連API を使用することができますが、Release()の前にスレッド状態は復元されていなければなりません。例えば、通常の Py_BEGIN_ALLOW_THREADS マクロと Py_END_ALLOW_THREADS は使用することができます。

戻り値は PyGILState_Ensure() 呼び出し時のスレッド状態を隠蔽した"ハンドル"で、 PyGILState_Release() に渡してPythonを同じ状態に保たなければなりません。再起呼び出しも可能ですが、ハンドルを共有することは できません - それぞれの PyGILState_Ensure() 呼び出しでハンドルを保存し、対応する PyGILState_Release() 呼び出しで渡してください。

関数から復帰したとき、実行中のスレッドはGILを所有していて、任意の Python コードを実行できます。処理の失敗は致命的なエラーです。

注釈

Calling this function from a thread when the runtime is finalizing will terminate the thread, even if the thread was not created by Python. You can use _Py_IsFinalizing() or sys.is_finalizing() to check if the interpreter is in process of being finalized before calling this function to avoid unwanted termination.

void PyGILState_Release(PyGILState_STATE)
Part of the Stable ABI.

獲得したすべてのリソースを解放します。この関数を呼び出すと、Pythonの状態は対応する PyGILState_Ensure() を呼び出す前と同じとなります (通常、この状態は呼び出し元でははわかりませんので、GILState APIを利用するようにしてください)。

PyGILState_Ensure() を呼び出す場合は、必ず同一スレッド内で対応する PyGILState_Release() を呼び出してください。

PyThreadState *PyGILState_GetThisThreadState()
Part of the Stable ABI.

このスレッドの現在のスレッドの状態を取得します。これまで現在のスレッドで GILState API を使ったことが無い場合は、NULL が返ります。メインスレッドで自身のスレッド状態に関する呼び出しを全くしないとしても、メインスレッドは常にスレッド状態の情報を持っていることに注意してください。こうなっている目的は主にヘルパ機能もしくは診断機能のためです。

int PyGILState_Check()

現在のスレッドが GILを保持しているならば 1 を、そうでなければ 0 を返します。この関数はいつでもどのスレッドからでも呼び出すことができます。 Python スレッドの状態が初期化されており、現在 GIL を保持している場合にのみ 1 を返します。これは主にヘルパー/診断用の関数です。この関数は、例えばコールバックのコンテキストやメモリ割り当て機能で有益でしょう。なぜなら、 GIL がロックされていると知っていれば、呼び出し元は sensitive な行動を実行することができ、そうでなければ異なるやりかたで振る舞うことができるからです。

バージョン 3.4 で追加.

以下のマクロは、通常末尾にセミコロンを付けずに使います; Python ソース配布物内の使用例を見てください。

Py_BEGIN_ALLOW_THREADS
Part of the Stable ABI.

このマクロを展開すると { PyThreadState *_save; _save = PyEval_SaveThread(); になります。マクロに開き波括弧が入っていることに注意してください; この波括弧は後で Py_END_ALLOW_THREADS マクロと対応させなければなりません。マクロについての詳しい議論は上記を参照してください。

Py_END_ALLOW_THREADS
Part of the Stable ABI.

このマクロを展開すると PyEval_RestoreThread(_save); } になります。マクロに開き波括弧が入っていることに注意してください; この波括弧は事前の Py_BEGIN_ALLOW_THREADS マクロと対応していなければなりません。マクロについての詳しい議論は上記を参照してください。

Py_BLOCK_THREADS
Part of the Stable ABI.

このマクロを展開すると PyEval_RestoreThread(_save); になります: 閉じ波括弧のない Py_END_ALLOW_THREADS と同じです。

Py_UNBLOCK_THREADS
Part of the Stable ABI.

このマクロを展開すると _save = PyEval_SaveThread(); になります: 開き波括弧のない Py_BEGIN_ALLOW_THREADS と同じです。

低レベルAPI

次の全ての関数は Py_Initialize() の後に呼び出さなければなりません。

バージョン 3.7 で変更: Py_Initialize()GIL を初期化するようになりました。

PyInterpreterState *PyInterpreterState_New()
Part of the Stable ABI.

新しいインタプリタ状態オブジェクトを生成します。GIL を保持しておく必要はありませんが、この関数を次々に呼び出す必要がある場合には保持しておいたほうがよいでしょう。

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

void PyInterpreterState_Clear(PyInterpreterState *interp)
Part of the Stable ABI.

インタプリタ状態オブジェクト内の全ての情報をリセットします。GIL を保持していなければなりません。

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

void PyInterpreterState_Delete(PyInterpreterState *interp)
Part of the Stable ABI.

インタプリタ状態オブジェクトを破壊します。GIL を保持しておく必要はありません。インタプリタ状態は PyInterpreterState_Clear() であらかじめリセットしておかなければなりません。

PyThreadState *PyThreadState_New(PyInterpreterState *interp)
Part of the Stable ABI.

指定したインタプリタオブジェクトに属する新たなスレッド状態オブジェクトを生成します。GIL を保持しておく必要はありませんが、この関数を次々に呼び出す必要がある場合には保持しておいたほうがよいでしょう。

void PyThreadState_Clear(PyThreadState *tstate)
Part of the Stable ABI.

スレッド状態オブジェクト内の全ての情報をリセットします。GIL を保持していなければなりません。

バージョン 3.9 で変更: This function now calls the PyThreadState.on_delete callback. Previously, that happened in PyThreadState_Delete().

void PyThreadState_Delete(PyThreadState *tstate)
Part of the Stable ABI.

スレッド状態オブジェクトを破壊します。GIL を保持する必要はありません。スレッド状態は PyThreadState_Clear() であらかじめリセットしておかなければなりません。

void PyThreadState_DeleteCurrent(void)

Destroy the current thread state and release the global interpreter lock. Like PyThreadState_Delete(), the global interpreter lock need not be held. The thread state must have been reset with a previous call to PyThreadState_Clear().

PyFrameObject *PyThreadState_GetFrame(PyThreadState *tstate)
Part of the Stable ABI since version 3.10.

Get the current frame of the Python thread state tstate.

Return a strong reference. Return NULL if no frame is currently executing.

See also PyEval_GetFrame().

tstate must not be NULL.

バージョン 3.9 で追加.

uint64_t PyThreadState_GetID(PyThreadState *tstate)
Part of the Stable ABI since version 3.10.

Get the unique thread state identifier of the Python thread state tstate.

tstate must not be NULL.

バージョン 3.9 で追加.

PyInterpreterState *PyThreadState_GetInterpreter(PyThreadState *tstate)
Part of the Stable ABI since version 3.10.

Get the interpreter of the Python thread state tstate.

tstate must not be NULL.

バージョン 3.9 で追加.

void PyThreadState_EnterTracing(PyThreadState *tstate)

Suspend tracing and profiling in the Python thread state tstate.

Resume them using the PyThreadState_LeaveTracing() function.

バージョン 3.11 で追加.

void PyThreadState_LeaveTracing(PyThreadState *tstate)

Resume tracing and profiling in the Python thread state tstate suspended by the PyThreadState_EnterTracing() function.

See also PyEval_SetTrace() and PyEval_SetProfile() functions.

バージョン 3.11 で追加.

PyInterpreterState *PyInterpreterState_Get(void)
Part of the Stable ABI since version 3.9.

Get the current interpreter.

Issue a fatal error if there no current Python thread state or no current interpreter. It cannot return NULL.

呼び出し側はGILを獲得する必要があります

バージョン 3.9 で追加.

int64_t PyInterpreterState_GetID(PyInterpreterState *interp)
Part of the Stable ABI since version 3.7.

インタプリタの一意な ID を返します。 処理中に何かエラーが起きたら、 -1 が返され、エラーがセットされます。

呼び出し側はGILを獲得する必要があります

バージョン 3.7 で追加.

PyObject *PyInterpreterState_GetDict(PyInterpreterState *interp)
Part of the Stable ABI since version 3.8.

インタプリタ固有のデータを保持している辞書を返します。 この関数が NULL を返した場合は、ここまでで例外は送出されておらず、呼び出し側はインタプリタ固有の辞書は利用できないと考えなければなりません。

この関数は PyModule_GetState() を置き換えるものではなく、拡張モジュールがインタプリタ固有の状態情報を格納するのに使うべきものです。

バージョン 3.8 で追加.

typedef PyObject *(*_PyFrameEvalFunction)(PyThreadState *tstate, _PyInterpreterFrame *frame, int throwflag)

Type of a frame evaluation function.

The throwflag parameter is used by the throw() method of generators: if non-zero, handle the current exception.

バージョン 3.9 で変更: The function now takes a tstate parameter.

バージョン 3.11 で変更: The frame parameter changed from PyFrameObject* to _PyInterpreterFrame*.

_PyFrameEvalFunction _PyInterpreterState_GetEvalFrameFunc(PyInterpreterState *interp)

Get the frame evaluation function.

See the PEP 523 "Adding a frame evaluation API to CPython".

バージョン 3.9 で追加.

void _PyInterpreterState_SetEvalFrameFunc(PyInterpreterState *interp, _PyFrameEvalFunction eval_frame)

Set the frame evaluation function.

See the PEP 523 "Adding a frame evaluation API to CPython".

バージョン 3.9 で追加.

PyObject *PyThreadState_GetDict()
Return value: Borrowed reference. Part of the Stable ABI.

拡張モジュールがスレッド固有の状態情報を保存できるような辞書を返します。各々の拡張モジュールが辞書に状態情報を保存するためには唯一のキーを使わなければなりません。現在のスレッド状態がない時にこの関数を呼び出してもかまいません。この関数が NULL を返す場合、例外はまったく送出されず、呼び出し側は現在のスレッド状態が利用できないと考えなければなりません。

int PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
Part of the Stable ABI.

Asynchronously raise an exception in a thread. The id argument is the thread id of the target thread; exc is the exception object to be raised. This function does not steal any references to exc. To prevent naive misuse, you must write your own C extension to call this. Must be called with the GIL held. Returns the number of thread states modified; this is normally one, but will be zero if the thread id isn't found. If exc is NULL, the pending exception (if any) for the thread is cleared. This raises no exceptions.

バージョン 3.7 で変更: id 引数の型が long から unsigned long へ変更されました。

void PyEval_AcquireThread(PyThreadState *tstate)
Part of the Stable ABI.

GIL を獲得し、現在のスレッド状態を tstate に設定します。 tstateNULL であってはなりません。ロックはあらかじめ作成されていなければなりません。この関数を呼び出したスレッドがすでにロックを獲得している場合、デッドロックに陥ります。

注釈

Calling this function from a thread when the runtime is finalizing will terminate the thread, even if the thread was not created by Python. You can use _Py_IsFinalizing() or sys.is_finalizing() to check if the interpreter is in process of being finalized before calling this function to avoid unwanted termination.

バージョン 3.8 で変更: Updated to be consistent with PyEval_RestoreThread(), Py_END_ALLOW_THREADS(), and PyGILState_Ensure(), and terminate the current thread if called while the interpreter is finalizing.

PyEval_RestoreThread() はいつでも (スレッドが初期化されたいないときでも) 利用可能な高レベル関数です。

void PyEval_ReleaseThread(PyThreadState *tstate)
Part of the Stable ABI.

現在のスレッド状態をリセットして NULL にし、GIL を解放します。ロックはあらかじめ作成されていなければならず、かつ現在のスレッドが保持していなければなりません。tstateNULL であってはなりませんが、その値が現在のスレッド状態を表現しているかどうかを調べるためにだけ使われます --- もしそうでなければ、致命的エラーが報告されます。

PyEval_SaveThread() はより高レベルな関数で常に (スレッドが初期化されていないときでも) 利用できます。

void PyEval_AcquireLock()
Part of the Stable ABI.

GILを獲得します。ロックは前もって作成されていなければなりません。この関数を呼び出したスレッドがすでにロックを獲得している場合、デッドロックに陥ります。

バージョン 3.2 で非推奨: この関数は現在のスレッドの状態を更新しません。代わりに PyEval_RestoreThread() もしくは PyEval_AcquireThread() を使用してください。

注釈

ランタイムが終了処理をしているときに、スレッドからこの関数を呼び出すと、そのスレッドが Python によって作成されたものではなかったとしても終了させられます。 _Py_IsFinalizing()sys.is_finalizing() を使うと、この関数を呼び出す前にインタプリタが終了される過程の途中なのか確認でき、望まないスレッドの終了が避けられます。

バージョン 3.8 で変更: Updated to be consistent with PyEval_RestoreThread(), Py_END_ALLOW_THREADS(), and PyGILState_Ensure(), and terminate the current thread if called while the interpreter is finalizing.

void PyEval_ReleaseLock()
Part of the Stable ABI.

GILを解放します。ロックは前もって作成されていなければなりません。

バージョン 3.2 で非推奨: この関数は現在のスレッドの状態を更新しません。代わりに PyEval_SaveThread() もしくは PyEval_ReleaseThread() を使用してください。

サブインタプリタサポート

ほとんどの場合は埋め込む Python インタプリタは1つだけですが、いくつかの場合に同一プロセス内、あるいは同一スレッド内で、複数の独立したインタプリタを作成する必要があります。 これを可能にするのがサブインタプリタです。

"メイン" インタプリタとは、ランタイムが初期化を行ったときに最初に作成されたインタプリタのことです。 サブインタプリタと違い、メインインタプリタにはシグナルハンドリングのような、プロセス全域で唯一な責務があります。 メインインタプリタにはランタイムの初期化中の処理実行という責務もあり、通常はランタイムの終了処理中に動いているランタイムでもあります。 PyInterpreterState_Main() 関数は、メインインタプリタの状態へのポインタを返します。

サブインタプリタを切り替えが PyThreadState_Swap() 関数でできます。 次の関数を使ってサブインタプリタの作成と削除が行えます:

type PyInterpreterConfig

Structure containing most parameters to configure a sub-interpreter. Its values are used only in Py_NewInterpreterFromConfig() and never modified by the runtime.

バージョン 3.12 で追加.

構造体フィールド:

int use_main_obmalloc

If this is 0 then the sub-interpreter will use its own "object" allocator state. Otherwise it will use (share) the main interpreter's.

If this is 0 then check_multi_interp_extensions must be 1 (non-zero). If this is 1 then gil must not be PyInterpreterConfig_OWN_GIL.

int allow_fork

If this is 0 then the runtime will not support forking the process in any thread where the sub-interpreter is currently active. Otherwise fork is unrestricted.

Note that the subprocess module still works when fork is disallowed.

int allow_exec

If this is 0 then the runtime will not support replacing the current process via exec (e.g. os.execv()) in any thread where the sub-interpreter is currently active. Otherwise exec is unrestricted.

Note that the subprocess module still works when exec is disallowed.

int allow_threads

If this is 0 then the sub-interpreter's threading module won't create threads. Otherwise threads are allowed.

int allow_daemon_threads

If this is 0 then the sub-interpreter's threading module won't create daemon threads. Otherwise daemon threads are allowed (as long as allow_threads is non-zero).

int check_multi_interp_extensions

If this is 0 then all extension modules may be imported, including legacy (single-phase init) modules, in any thread where the sub-interpreter is currently active. Otherwise only multi-phase init extension modules (see PEP 489) may be imported. (Also see Py_mod_multiple_interpreters.)

This must be 1 (non-zero) if use_main_obmalloc is 0.

int gil

This determines the operation of the GIL for the sub-interpreter. It may be one of the following:

PyInterpreterConfig_DEFAULT_GIL

Use the default selection (PyInterpreterConfig_SHARED_GIL).

PyInterpreterConfig_SHARED_GIL

Use (share) the main interpreter's GIL.

PyInterpreterConfig_OWN_GIL

Use the sub-interpreter's own GIL.

If this is PyInterpreterConfig_OWN_GIL then PyInterpreterConfig.use_main_obmalloc must be 0.

PyStatus Py_NewInterpreterFromConfig(PyThreadState **tstate_p, const PyInterpreterConfig *config)

新しいサブインタプリタ (sub-interpreter) を生成します。サブインタプリタとは、(ほぼ完全に) 個別に分割された Python コードの実行環境です。特に、新しいサブインタプリタは、 import されるモジュール全てについて個別のバージョンを持ち、これには基盤となるモジュール builtins, __main__ および sys も含まれます。ロード済みのモジュールからなるテーブル (sys.modules) およびモジュール検索パス (sys.path) もサブインタプリタ毎に別個のものになります。新たなサブインタプリタ環境には sys.argv 変数がありません。また、サブインタプリタは新たな標準 I/O ストリーム sys.stdin, sys.stdout, sys.stderr を持ちます (とはいえ、これらのストリームは根底にある同じファイル記述子を参照しています)。

The given config controls the options with which the interpreter is initialized.

Upon success, tstate_p will be set to the first thread state created in the new sub-interpreter. This thread state is made in the current thread state. Note that no actual thread is created; see the discussion of thread states below. If creation of the new interpreter is unsuccessful, tstate_p is set to NULL; no exception is set since the exception state is stored in the current thread state and there may not be a current thread state.

Like all other Python/C API functions, the global interpreter lock must be held before calling this function and is still held when it returns. Likewise a current thread state must be set on entry. On success, the returned thread state will be set as current. If the sub-interpreter is created with its own GIL then the GIL of the calling interpreter will be released. When the function returns, the new interpreter's GIL will be held by the current thread and the previously interpreter's GIL will remain released here.

バージョン 3.12 で追加.

Sub-interpreters are most effective when isolated from each other, with certain functionality restricted:

PyInterpreterConfig config = {
    .use_main_obmalloc = 0,
    .allow_fork = 0,
    .allow_exec = 0,
    .allow_threads = 1,
    .allow_daemon_threads = 0,
    .check_multi_interp_extensions = 1,
    .gil = PyInterpreterConfig_OWN_GIL,
};
PyThreadState *tstate = Py_NewInterpreterFromConfig(&config);

Note that the config is used only briefly and does not get modified. During initialization the config's values are converted into various PyInterpreterState values. A read-only copy of the config may be stored internally on the PyInterpreterState.

Extension modules are shared between (sub-)interpreters as follows:

  • For modules using multi-phase initialization, e.g. PyModule_FromDefAndSpec(), a separate module object is created and initialized for each interpreter. Only C-level static and global variables are shared between these module objects.

  • For modules using single-phase initialization, e.g. PyModule_Create(), the first time a particular extension is imported, it is initialized normally, and a (shallow) copy of its module's dictionary is squirreled away. When the same extension is imported by another (sub-)interpreter, a new module is initialized and filled with the contents of this copy; the extension's init function is not called. Objects in the module's dictionary thus end up shared across (sub-)interpreters, which might cause unwanted behavior (see Bugs and caveats below).

    Note that this is different from what happens when an extension is imported after the interpreter has been completely re-initialized by calling Py_FinalizeEx() and Py_Initialize(); in that case, the extension's initmodule function is called again. As with multi-phase initialization, this means that only C-level static and global variables are shared between these modules.

PyThreadState *Py_NewInterpreter(void)
Part of the Stable ABI.

Create a new sub-interpreter. This is essentially just a wrapper around Py_NewInterpreterFromConfig() with a config that preserves the existing behavior. The result is an unisolated sub-interpreter that shares the main interpreter's GIL, allows fork/exec, allows daemon threads, and allows single-phase init modules.

void Py_EndInterpreter(PyThreadState *tstate)
Part of the Stable ABI.

Destroy the (sub-)interpreter represented by the given thread state. The given thread state must be the current thread state. See the discussion of thread states below. When the call returns, the current thread state is NULL. All thread states associated with this interpreter are destroyed. The global interpreter lock used by the target interpreter must be held before calling this function. No GIL is held when it returns.

Py_FinalizeEx() will destroy all sub-interpreters that haven't been explicitly destroyed at that point.

A Per-Interpreter GIL

Using Py_NewInterpreterFromConfig() you can create a sub-interpreter that is completely isolated from other interpreters, including having its own GIL. The most important benefit of this isolation is that such an interpreter can execute Python code without being blocked by other interpreters or blocking any others. Thus a single Python process can truly take advantage of multiple CPU cores when running Python code. The isolation also encourages a different approach to concurrency than that of just using threads. (See PEP 554.)

Using an isolated interpreter requires vigilance in preserving that isolation. That especially means not sharing any objects or mutable state without guarantees about thread-safety. Even objects that are otherwise immutable (e.g. None, (1, 5)) can't normally be shared because of the refcount. One simple but less-efficient approach around this is to use a global lock around all use of some state (or object). Alternately, effectively immutable objects (like integers or strings) can be made safe in spite of their refcounts by making them "immortal". In fact, this has been done for the builtin singletons, small integers, and a number of other builtin objects.

If you preserve isolation then you will have access to proper multi-core computing without the complications that come with free-threading. Failure to preserve isolation will expose you to the full consequences of free-threading, including races and hard-to-debug crashes.

Aside from that, one of the main challenges of using multiple isolated interpreters is how to communicate between them safely (not break isolation) and efficiently. The runtime and stdlib do not provide any standard approach to this yet. A future stdlib module would help mitigate the effort of preserving isolation and expose effective tools for communicating (and sharing) data between interpreters.

バージョン 3.12 で追加.

バグと注意事項

Because sub-interpreters (and the main interpreter) are part of the same process, the insulation between them isn't perfect --- for example, using low-level file operations like os.close() they can (accidentally or maliciously) affect each other's open files. Because of the way extensions are shared between (sub-)interpreters, some extensions may not work properly; this is especially likely when using single-phase initialization or (static) global variables. It is possible to insert objects created in one sub-interpreter into a namespace of another (sub-)interpreter; this should be avoided if possible.

Special care should be taken to avoid sharing user-defined functions, methods, instances or classes between sub-interpreters, since import operations executed by such objects may affect the wrong (sub-)interpreter's dictionary of loaded modules. It is equally important to avoid sharing objects from which the above are reachable.

サブインタプリタを PyGILState_* API と組み合わせるのが難しいことにも注意してください。これらのAPIはPythonのスレッド状態とOSレベルスレッドが1対1で対応していることを前提にしていて、サブインタプリタが存在するとその前提が崩れるからです。対応する PyGILState_Ensure()PyGILState_Release() の呼び出しのペアの間では、サブインタプリタの切り替えを行わないことを強く推奨します。さらに、(ctypes のような)これらのAPIを使ってPythonの外で作られたスレッドから Pythonコードを実行している拡張モジュールはサブインタプリタを使うと壊れる可能性があります。

非同期通知

インタプリタのメインスレッドに非同期な通知を行うために提供されている仕組みです。これらの通知は関数ポインタと void ポインタ引数という形態を取ります。

int Py_AddPendingCall(int (*func)(void*), void *arg)
Part of the Stable ABI.

インタプリタのメインスレッドから関数が呼び出される予定を組みます。成功すると 0 が返り、func はメインスレッドの呼び出しキューに詰められます。失敗すると、例外をセットせずに -1 が返ります。

無事にキューに詰められると、funcいつかは必ず インタプリタのメインスレッドから、arg を引数として呼び出されます。この関数は、通常の実行中の Python コードに対して非同期に呼び出されますが、次の両方の条件に合致したときに呼び出されます:

  • bytecode 境界上にいるとき、

  • メインスレッドが global interpreter lock を保持している (すなわち func が全ての C API を呼び出せる) とき。

成功したら func0 を返さねばならず、失敗したら -1 を返し例外をセットしなければいけません。func は、他の非同期通知を行うために、さらに割り込まれることはありませんが、グローバルインタプリタロックが解放された場合は、スレッドの切り替えによって割り込まれる可能性が残っています。

この関数は実行するのに現在のスレッド状態を必要とせず、グローバルインタプリタロックも必要としません。

To call this function in a subinterpreter, the caller must hold the GIL. Otherwise, the function func can be scheduled to be called from the wrong interpreter.

警告

これは、非常に特別な場合にのみ役立つ、低レベルな関数です。 func が可能な限り早く呼び出される保証はありません。メインスレッドがシステムコールを実行するのに忙しい場合は、 func はシステムコールが返ってくるまで呼び出されないでしょう。この関数は一般的には、任意の C スレッドから Python コードを呼び出すのには 向きません 。これの代わりに、 PyGILState API を使用してください。

バージョン 3.1 で追加.

バージョン 3.9 で変更: If this function is called in a subinterpreter, the function func is now scheduled to be called from the subinterpreter, rather than being called from the main interpreter. Each subinterpreter now has its own list of scheduled calls.

プロファイルとトレース (profiling and tracing)

Python インタプリタは、プロファイル: 分析 (profile) や実行のトレース: 追跡 (trace) といった機能を組み込むために低水準のサポートを提供しています。このサポートは、プロファイルやデバッグ、適用範囲分析 (coverage analysis) ツールなどに使われます。

この C インターフェースは、プロファイルやトレース作業時に、Python レベルの呼び出し可能オブジェクトが呼び出されることによるオーバヘッドを避け、直接 C 関数呼び出しが行えるようにしています。プロファイルやトレース機能の本質的な特性は変わっていません; インターフェースではトレース関数をスレッドごとにインストールでき、トレース関数に報告される基本イベント (basic event) は以前のバージョンにおいて Python レベルのトレース関数で報告されていたものと同じです。

typedef int (*Py_tracefunc)(PyObject *obj, PyFrameObject *frame, int what, PyObject *arg)

The type of the trace function registered using PyEval_SetProfile() and PyEval_SetTrace(). The first parameter is the object passed to the registration function as obj, frame is the frame object to which the event pertains, what is one of the constants PyTrace_CALL, PyTrace_EXCEPTION, PyTrace_LINE, PyTrace_RETURN, PyTrace_C_CALL, PyTrace_C_EXCEPTION, PyTrace_C_RETURN, or PyTrace_OPCODE, and arg depends on the value of what:

what の値

arg の意味

PyTrace_CALL

常に Py_None

PyTrace_EXCEPTION

sys.exc_info() の返す例外情報です。

PyTrace_LINE

常に Py_None

PyTrace_RETURN

呼び出し側に返される予定の値か、例外によって関数を抜ける場合は NULL です。

PyTrace_C_CALL

呼び出される関数オブジェクト。

PyTrace_C_EXCEPTION

呼び出される関数オブジェクト。

PyTrace_C_RETURN

呼び出される関数オブジェクト。

PyTrace_OPCODE

常に Py_None

int PyTrace_CALL

関数やメソッドが新たに呼び出されたり、ジェネレータが新たなエントリの処理に入ったことを報告する際の、 Py_tracefuncwhat の値です。イテレータやジェネレータ関数の生成は、対応するフレーム内の Python バイトコードに制御の委譲 (control transfer) が起こらないため報告されないので注意してください。

int PyTrace_EXCEPTION

例外が送出された際の Py_tracefuncwhat の値です。現在実行されているフレームで例外がセットされ、何らかのバイトコードが処理された後に、 what にこの値がセットされた状態でコールバック関数が呼び出されます。この結果、例外の伝播によって Python が呼び出しスタックを逆戻りする際に、各フレームから処理が戻るごとにコールバック関数が呼び出されます。トレース関数だけがこれらのイベントを受け取ります; プロファイラはこの種のイベントを必要としません。

int PyTrace_LINE

The value passed as the what parameter to a Py_tracefunc function (but not a profiling function) when a line-number event is being reported. It may be disabled for a frame by setting f_trace_lines to 0 on that frame.

int PyTrace_RETURN

呼び出しが返るときに Py_tracefunc 関数に what 引数として渡す値です。

int PyTrace_C_CALL

C関数を呼び出す直前に Py_tracefunc 関数の what 引数として渡す値です。

int PyTrace_C_EXCEPTION

C関数が例外を送出したときに Py_tracefunc 関数の what 引数として渡す値です。

int PyTrace_C_RETURN

C関数から戻るときに Py_tracefunc 関数の what 引数として渡す値です。

int PyTrace_OPCODE

The value for the what parameter to Py_tracefunc functions (but not profiling functions) when a new opcode is about to be executed. This event is not emitted by default: it must be explicitly requested by setting f_trace_opcodes to 1 on the frame.

void PyEval_SetProfile(Py_tracefunc func, PyObject *obj)

Set the profiler function to func. The obj parameter is passed to the function as its first parameter, and may be any Python object, or NULL. If the profile function needs to maintain state, using a different value for obj for each thread provides a convenient and thread-safe place to store it. The profile function is called for all monitored events except PyTrace_LINE PyTrace_OPCODE and PyTrace_EXCEPTION.

sys.setprofile() 関数も参照してください。

呼び出し側は GIL を獲得しなければなりません。

void PyEval_SetProfileAllThreads(Py_tracefunc func, PyObject *obj)

Like PyEval_SetProfile() but sets the profile function in all running threads belonging to the current interpreter instead of the setting it only on the current thread.

呼び出し側は GIL を獲得しなければなりません。

As PyEval_SetProfile(), this function ignores any exceptions raised while setting the profile functions in all threads.

バージョン 3.12 で追加.

void PyEval_SetTrace(Py_tracefunc func, PyObject *obj)

Set the tracing function to func. This is similar to PyEval_SetProfile(), except the tracing function does receive line-number events and per-opcode events, but does not receive any event related to C function objects being called. Any trace function registered using PyEval_SetTrace() will not receive PyTrace_C_CALL, PyTrace_C_EXCEPTION or PyTrace_C_RETURN as a value for the what parameter.

sys.settrace() 関数も参照してください。

呼び出し側は GIL を獲得しなければなりません。

void PyEval_SetTraceAllThreads(Py_tracefunc func, PyObject *obj)

Like PyEval_SetTrace() but sets the tracing function in all running threads belonging to the current interpreter instead of the setting it only on the current thread.

呼び出し側は GIL を獲得しなければなりません。

As PyEval_SetTrace(), this function ignores any exceptions raised while setting the trace functions in all threads.

バージョン 3.12 で追加.

高度なデバッガサポート (advanced debugger support)

以下の関数は高度なデバッグツールでの使用のためだけのものです。

PyInterpreterState *PyInterpreterState_Head()

インタプリタ状態オブジェクトからなるリストのうち、先頭にあるものを返します。

PyInterpreterState *PyInterpreterState_Main()

メインインタプリタの状態オブジェクトを返します。

PyInterpreterState *PyInterpreterState_Next(PyInterpreterState *interp)

インタプリタ状態オブジェクトからなるリストのうち、interp の次にあるものを返します。

PyThreadState *PyInterpreterState_ThreadHead(PyInterpreterState *interp)

インタプリタ interp に関連付けられているスレッドからなるリストのうち、先頭にある PyThreadState オブジェクトを返します。

PyThreadState *PyThreadState_Next(PyThreadState *tstate)

tstate と同じ PyInterpreterState オブジェクトに属しているスレッド状態オブジェクトのうち、 tstate の次にあるものを返します。

スレッドローカルストレージのサポート

Python インタプリタは、スレッドローカルストレージ (thread-local storage, TLS) の低レベルサポートを提供していて、ネイティブの TLS 実装を内部にラップして Python レベルのスレッドローカルストレージ API (threading.local) をサポートしています。 CPython の C レベル API は pthreads や Windows で与えられる TLS と同様です: スレッドキーとスレッドごとに void* 値を関係付ける関数を使います。

API で使われる関数を呼ぶときは、 GIL を取得する必要は ありません 。関数自身のロックがサポートされています。

Python.h は TLS API の宣言を include せず、スレッドローカルストレージを使うには pythread.h を include する必要があることに注意してください。

注釈

この API 関数はどれも void* 値の代わりにメモリ管理を行うことはしません。 メモリの確保と解放は自前で行う必要があります。 void* 値がたまたま PyObject* だった場合は、 API 関数はそれぞれの値の参照カウントの操作は行いません。

スレッド固有ストレージ (Thread Specific Storage, TSS) API

TSS API は、 CPython インタプリタに含まれている既存の TLS API を置き換えるために導入されました。 この API は、スレッドキーの表現に int の代わりに新しい型 Py_tss_t を使います。

バージョン 3.7 で追加.

参考

"CPython のスレッドローカルストレージのための新しい C API" (PEP 539)

type Py_tss_t

このデータ構造体はスレッドキーの状態を表現しています。この構造体の定義は、根底の TLS 実装に依存し、キーの初期化状態を表現する内部フィールドを持ちます。 この構造体には公開 (public) のメンバはありません。

Py_LIMITED_API が定義されていないときは、この型の Py_tss_NEEDS_INIT による静的メモリ確保ができます。

Py_tss_NEEDS_INIT

このマクロは Py_tss_t 変数の初期化子に展開されます。 このマクロは Py_LIMITED_API があるときは定義されません。

動的メモリ確保

動的な Py_tss_t のメモリ確保は Py_LIMITED_API でビルドされた拡張モジュールで必要になりますが、その実装がビルド時に不透明なために、この型の静的なメモリ確保は不可能です。

Py_tss_t *PyThread_tss_alloc()
Part of the Stable ABI since version 3.7.

Return a value which is the same state as a value initialized with Py_tss_NEEDS_INIT, or NULL in the case of dynamic allocation failure.

void PyThread_tss_free(Py_tss_t *key)
Part of the Stable ABI since version 3.7.

Free the given key allocated by PyThread_tss_alloc(), after first calling PyThread_tss_delete() to ensure any associated thread locals have been unassigned. This is a no-op if the key argument is NULL.

注釈

A freed key becomes a dangling pointer. You should reset the key to NULL.

メソッド

The parameter key of these functions must not be NULL. Moreover, the behaviors of PyThread_tss_set() and PyThread_tss_get() are undefined if the given Py_tss_t has not been initialized by PyThread_tss_create().

int PyThread_tss_is_created(Py_tss_t *key)
Part of the Stable ABI since version 3.7.

Return a non-zero value if the given Py_tss_t has been initialized by PyThread_tss_create().

int PyThread_tss_create(Py_tss_t *key)
Part of the Stable ABI since version 3.7.

Return a zero value on successful initialization of a TSS key. The behavior is undefined if the value pointed to by the key argument is not initialized by Py_tss_NEEDS_INIT. This function can be called repeatedly on the same key -- calling it on an already initialized key is a no-op and immediately returns success.

void PyThread_tss_delete(Py_tss_t *key)
Part of the Stable ABI since version 3.7.

Destroy a TSS key to forget the values associated with the key across all threads, and change the key's initialization state to uninitialized. A destroyed key is able to be initialized again by PyThread_tss_create(). This function can be called repeatedly on the same key -- calling it on an already destroyed key is a no-op.

int PyThread_tss_set(Py_tss_t *key, void *value)
Part of the Stable ABI since version 3.7.

Return a zero value to indicate successfully associating a void* value with a TSS key in the current thread. Each thread has a distinct mapping of the key to a void* value.

void *PyThread_tss_get(Py_tss_t *key)
Part of the Stable ABI since version 3.7.

Return the void* value associated with a TSS key in the current thread. This returns NULL if no value is associated with the key in the current thread.

スレッドローカルストレージ (TLS) API

バージョン 3.7 で非推奨: This API is superseded by Thread Specific Storage (TSS) API.

注釈

This version of the API does not support platforms where the native TLS key is defined in a way that cannot be safely cast to int. On such platforms, PyThread_create_key() will return immediately with a failure status, and the other TLS functions will all be no-ops on such platforms.

前述の互換性の問題により、このバージョンのAPIは新規のコードで利用すべきではありません。

int PyThread_create_key()
Part of the Stable ABI.
void PyThread_delete_key(int key)
Part of the Stable ABI.
int PyThread_set_key_value(int key, void *value)
Part of the Stable ABI.
void *PyThread_get_key_value(int key)
Part of the Stable ABI.
void PyThread_delete_key_value(int key)
Part of the Stable ABI.
void PyThread_ReInitTLS()
Part of the Stable ABI.