Python 初始化配置

Added in version 3.8.

可以初始化 Python 采用 Py_InitializeFromConfig() PyConfig 结构。可以预初始化它采用 Py_PreInitialize() PyPreConfig 结构。

有 2 种配置:

  • The Python 配置 can be used to build a customized Python which behaves as the regular Python. For example, environment variables and command line arguments are used to configure Python.

  • The 隔离配置 can be used to embed Python into an application. It isolates Python from the system. For example, environment variables are ignored, the LC_CTYPE locale is left unchanged and no signal handler is registered.

The Py_RunMain() 函数可以用于编写定制 Python 程序。

另请参阅 初始化、定稿和线程 .

另请参阅

PEP 587 Python 初始化配置。

范例

Example of customized Python always running in isolated mode:

int main(int argc, char **argv)
{
    PyStatus status;
    PyConfig config;
    PyConfig_InitPythonConfig(&config);
    config.isolated = 1;
    /* Decode command line arguments.
       Implicitly preinitialize Python (in isolated mode). */
    status = PyConfig_SetBytesArgv(&config, argc, argv);
    if (PyStatus_Exception(status)) {
        goto exception;
    }
    status = Py_InitializeFromConfig(&config);
    if (PyStatus_Exception(status)) {
        goto exception;
    }
    PyConfig_Clear(&config);
    return Py_RunMain();
exception:
    PyConfig_Clear(&config);
    if (PyStatus_IsExit(status)) {
        return status.exitcode;
    }
    /* Display the error message and exit the process with
       non-zero exit code */
    Py_ExitStatusException(status);
}