Python初始化配置

3.8 版新加入.

结构

函数

The preconfiguration (PyPreConfig type) is stored in _PyRuntime.preconfig and the configuration (PyConfig type) is stored in PyInterpreterState.config.

参见 Initialization, Finalization, and Threads.

也參考

PEP 587 "Python 初始化配置".

PyWideStringList

PyWideStringList

wchar_t* 字符串组成的列表。

如果 length 为非零值,则 items 必须不为 NULL 并且所有字符串均必须不为 NULL

方法

PyStatus PyWideStringList_Append(PyWideStringList *list, const wchar_t *item)

item 添加到 list

Python 必须被预初始化以便调用此函数。

PyStatus PyWideStringList_Insert(PyWideStringList *list, Py_ssize_t index, const wchar_t *item)

item 插入到 listindex 位置上。

如果 index 大于等于 list 的长度,则将 item 添加到 list

index must be greater than or equal to 0.

Python 必须被预初始化以便调用此函数。

结构体字段:

Py_ssize_t length

List 长度。

wchar_t** items

列表项目。

PyStatus

PyStatus

存储初始函数状态:成功、错误或退出的结构体。

对于错误,它可以存储造成错误的 C 函数的名称。

结构体字段:

int exitcode

退出码。 传给 exit() 的参数。

const char *err_msg

错误信息

const char *func

造成错误的函数的名称,可以为 NULL

创建状态的函数:

PyStatus PyStatus_Ok(void)

完成。

PyStatus PyStatus_Error(const char *err_msg)

带消息的初始化错误。

PyStatus PyStatus_NoMemory(void)

内存分配失败(内存不足)。

PyStatus PyStatus_Exit(int exitcode)

以指定的退出代码退出 Python。

处理状态的函数:

int PyStatus_Exception(PyStatus status)

状态为错误还是退出?如为真值,则异常必须被处理;例如通过调用 Py_ExitStatusException()

int PyStatus_IsError(PyStatus status)

结果错误吗?

int PyStatus_IsExit(PyStatus status)

结果是否退出?

void Py_ExitStatusException(PyStatus status)

如果 status 是一个退出码则调用 exit(exitcode)。如果 status 是一个错误码则打印错误消息并设置一个非零退出码再退出。 必须在 PyStatus_Exception(status) 为非零值时才能被调用。

備註

在内部,Python 将使用设置 PyStatus.func 的宏,而创建状态的函数则会将 func 设为 NULL

示例:

PyStatus alloc(void **ptr, size_t size)
{
    *ptr = PyMem_RawMalloc(size);
    if (*ptr == NULL) {
        return PyStatus_NoMemory();
    }
    return PyStatus_Ok();
}

int main(int argc, char **argv)
{
    void *ptr;
    PyStatus status = alloc(&ptr, 16);
    if (PyStatus_Exception(status)) {
        Py_ExitStatusException(status);
    }
    PyMem_Free(ptr);
    return 0;
}

PyPreConfig

PyPreConfig

Structure used to preinitialize Python:

  • Set the Python memory allocator

  • Configure the LC_CTYPE locale

  • 设置为 UTF-8 模式

用于初始化预先配置的函数:

void PyPreConfig_InitPythonConfig(PyPreConfig *preconfig)

通过 Python 配置 来初始化预先配置。

void PyPreConfig_InitIsolatedConfig(PyPreConfig *preconfig)

通过 隔离配置 来初始化预先配置。

结构体字段:

int allocator

Name of the memory allocator:

  • PYMEM_ALLOCATOR_NOT_SET (0): don't change memory allocators (use defaults)

  • PYMEM_ALLOCATOR_DEFAULT (1): default memory allocators

  • PYMEM_ALLOCATOR_DEBUG (2): default memory allocators with debug hooks

  • PYMEM_ALLOCATOR_MALLOC (3): force usage of malloc()

  • PYMEM_ALLOCATOR_MALLOC_DEBUG (4): force usage of malloc() with debug hooks

  • PYMEM_ALLOCATOR_PYMALLOC (5): Python pymalloc memory allocator

  • PYMEM_ALLOCATOR_PYMALLOC_DEBUG (6): Python pymalloc memory allocator with debug hooks

PYMEM_ALLOCATOR_PYMALLOC and PYMEM_ALLOCATOR_PYMALLOC_DEBUG are not supported if Python is configured using --without-pymalloc

参见 Memory Management.

int configure_locale

Set the LC_CTYPE locale to the user preferred locale? If equals to 0, set coerce_c_locale and coerce_c_locale_warn to 0.

int coerce_c_locale

If equals to 2, coerce the C locale; if equals to 1, read the LC_CTYPE locale to decide if it should be coerced.

int coerce_c_locale_warn

如为非零值,则会在 C 语言区域被强制转换时发出警告。

int dev_mode

参见 PyConfig.dev_mode.

int isolated

参见 PyConfig.isolated.

int legacy_windows_fs_encoding(Windows only)

If non-zero, disable UTF-8 Mode, set the Python filesystem encoding to mbcs, set the filesystem error handler to replace.

仅在 Windows 上可用。 #ifdef MS_WINDOWS 宏可被用于 Windows 专属的代码。

int parse_argv

如为非零值,Py_PreInitializeFromArgs()Py_PreInitializeFromBytesArgs() 将以与常规 Python 解析命令行参数的相同方式解析其 argv 参数:参见 命令行参数

int use_environment

参见 PyConfig.use_environment.

int utf8_mode

If non-zero, enable the UTF-8 mode.

Preinitialization with PyPreConfig

用于预初始化 Python 的函数:

PyStatus Py_PreInitialize(const PyPreConfig *preconfig)

根据 preconfig 预配置来预初始化 Python。

PyStatus Py_PreInitializeFromBytesArgs(const PyPreConfig *preconfig, int argc, char * const *argv)

Preinitialize Python from preconfig preconfiguration and command line arguments (bytes strings).

PyStatus Py_PreInitializeFromArgs(const PyPreConfig *preconfig, int argc, wchar_t * const * argv)

Preinitialize Python from preconfig preconfiguration and command line arguments (wide strings).

调用方要负责使用 PyStatus_Exception()Py_ExitStatusException() 来处理异常(错误或退出)。

For Python Configuration (PyPreConfig_InitPythonConfig()), if Python is initialized with command line arguments, the command line arguments must also be passed to preinitialize Python, since they have an effect on the pre-configuration like encodings. For example, the -X utf8 command line option enables the UTF-8 Mode.

PyMem_SetAllocator() 可在 Py_PreInitialize() 之后、Py_InitializeFromConfig() 之前被调用以安装自定义的内存分配器。 如果 PyPreConfig.allocator 被设为 PYMEM_ALLOCATOR_NOT_SET 则可在 Py_PreInitialize() 之前被调用。

Python memory allocation functions like PyMem_RawMalloc() must not be used before Python preinitialization, whereas calling directly malloc() and free() is always safe. Py_DecodeLocale() must not be called before the preinitialization.

Example using the preinitialization to enable the UTF-8 Mode:

PyStatus status;
PyPreConfig preconfig;
PyPreConfig_InitPythonConfig(&preconfig);

preconfig.utf8_mode = 1;

status = Py_PreInitialize(&preconfig);
if (PyStatus_Exception(status)) {
    Py_ExitStatusException(status);
}

/* at this point, Python will speak UTF-8 */

Py_Initialize();
/* ... use Python API here ... */
Py_Finalize();

PyConfig

PyConfig

包含了大部分用于配置 Python 的形参的结构体。

结构体方法:

void PyConfig_InitPythonConfig(PyConfig *config)

Initialize configuration with Python Configuration.

void PyConfig_InitIsolatedConfig(PyConfig *config)

Initialize configuration with Isolated Configuration.

PyStatus PyConfig_SetString(PyConfig *config, wchar_t * const *config_str, const wchar_t *str)

将宽字符串 str 拷贝至 *config_str

Preinitialize Python if needed.

PyStatus PyConfig_SetBytesString(PyConfig *config, wchar_t * const *config_str, const char *str)

Decode str using Py_DecodeLocale() and set the result into *config_str.

Preinitialize Python if needed.

PyStatus PyConfig_SetArgv(PyConfig *config, int argc, wchar_t * const *argv)

Set command line arguments from wide character strings.

Preinitialize Python if needed.

PyStatus PyConfig_SetBytesArgv(PyConfig *config, int argc, char * const *argv)

Set command line arguments: decode bytes using Py_DecodeLocale().

Preinitialize Python if needed.

PyStatus PyConfig_SetWideStringList(PyConfig *config, PyWideStringList *list, Py_ssize_t length, wchar_t **items)

将宽字符串列表 list 设置为 lengthitems

Preinitialize Python if needed.

PyStatus PyConfig_Read(PyConfig *config)

读取所有 Python 配置。

已经初始化的字段会保持不变。

Preinitialize Python if needed.

void PyConfig_Clear(PyConfig *config)

释放配置内存

Most PyConfig methods preinitialize Python if needed. In that case, the Python preinitialization configuration in based on the PyConfig. If configuration fields which are in common with PyPreConfig are tuned, they must be set before calling a PyConfig method:

Moreover, if PyConfig_SetArgv() or PyConfig_SetBytesArgv() is used, this method must be called first, before other methods, since the preinitialization configuration depends on command line arguments (if parse_argv is non-zero).

这些方法的调用者要负责使用 PyStatus_Exception()Py_ExitStatusException() 来处理异常(错误或退出)。

结构体字段:

PyWideStringList argv

Command line arguments, sys.argv. See parse_argv to parse argv the same way the regular Python parses Python command line arguments. If argv is empty, an empty string is added to ensure that sys.argv always exists and is never empty.

wchar_t* base_exec_prefix

sys.base_exec_prefix.

wchar_t* base_executable

sys._base_executable: __PYVENV_LAUNCHER__ environment variable value, or copy of PyConfig.executable.

wchar_t* base_prefix

sys.base_prefix.

int buffered_stdio

If equals to 0, enable unbuffered mode, making the stdout and stderr streams unbuffered.

stdin 始终以缓冲模式打开。

int bytes_warning

If equals to 1, issue a warning when comparing bytes or bytearray with str, or comparing bytes with int. If equal or greater to 2, raise a BytesWarning exception.

wchar_t* check_hash_pycs_mode

Control the validation behavior of hash-based .pyc files (see PEP 552): --check-hash-based-pycs command line option value.

Valid values: always, never and default.

默认值为: default.

int configure_c_stdio

If non-zero, configure C standard streams (stdio, stdout, stdout). For example, set their mode to O_BINARY on Windows.

int dev_mode

Development mode: see -X dev.

int dump_refs

如果为非零值,则转储所有在退出时仍存活的对象。

Require a debug build of Python (Py_REF_DEBUG macro must be defined).

wchar_t* exec_prefix

sys.exec_prefix.

wchar_t* executable

sys.executable.

int faulthandler

如果为非零值,则在启动时调用 faulthandler.enable()

wchar_t* filesystem_encoding

Filesystem encoding, sys.getfilesystemencoding().

wchar_t* filesystem_errors

Filesystem encoding errors, sys.getfilesystemencodeerrors().

unsigned long hash_seed
int use_hash_seed

随机化的哈希函数种子。

If use_hash_seed is zero, a seed is chosen randomly at Pythonstartup, and hash_seed is ignored.

wchar_t* home

Python 主目录。

Initialized from PYTHONHOME environment variable value by default.

int import_time

如为非零值,则对导入时间执行性能分析。

int inspect

在执行脚本或命令之后进入交互模式。

int install_signal_handlers

Install signal handlers?

int interactive

交互模式

int isolated

If greater than 0, enable isolated mode:

  • sys.path contains neither the script's directory (computed from argv[0] or the current directory) nor the user's site-packages directory.

  • Python REPL 将不导入 readline 也不在交互提示符中启用默认的 readline 配置。

  • Set use_environment and user_site_directory to 0.

int legacy_windows_stdio

If non-zero, use io.FileIO instead of io.WindowsConsoleIO for sys.stdin, sys.stdout and sys.stderr.

仅在 Windows 上可用。 #ifdef MS_WINDOWS 宏可被用于 Windows 专属的代码。

int malloc_stats

如为非零值,则在退出时转储 Python pymalloc 内存分配器 的统计数据。

The option is ignored if Python is built using --without-pymalloc.

wchar_t* pythonpath_env

Module search paths as a string separated by DELIM (os.path.pathsep).

Initialized from PYTHONPATH environment variable value by default.

PyWideStringList module_search_paths
int module_search_paths_set

sys.path. If module_search_paths_set is equal to 0, the module_search_paths is overridden by the function calculating the Path Configuration.

int optimization_level

编译优化级别:

  • 0: Peephole optimizer (and __debug__ is set to True)

  • 1: Remove assertions, set __debug__ to False

  • 2: Strip docstrings

int parse_argv

If non-zero, parse argv the same way the regular Python command line arguments, and strip Python arguments from argv: see Command Line Arguments.

int parser_debug

If non-zero, turn on parser debugging output (for expert only, depending on compilation options).

int pathconfig_warnings

If equal to 0, suppress warnings when calculating the Path Configuration (Unix only, Windows does not log any warning). Otherwise, warnings are written into stderr.

wchar_t* prefix

sys.prefix.

wchar_t* program_name

Program name. Used to initialize executable, and in early error messages.

wchar_t* pycache_prefix

sys.pycache_prefix: .pyc cache prefix.

如果为 NULL,则 sys.pycache_prefix 将被设为 None

int quiet

Quiet mode. For example, don't display the copyright and version messages in interactive mode.

wchar_t* run_command

python3 -c COMMAND argument. Used by Py_RunMain().

wchar_t* run_filename

python3 FILENAME argument. Used by Py_RunMain().

wchar_t* run_module

python3 -m MODULE argument. Used by Py_RunMain().

int show_alloc_count

Show allocation counts at exit?

Set to 1 by -X showalloccount command line option.

Need a special Python build with COUNT_ALLOCS macro defined.

int show_ref_count

在退出时显示引用总数?

Set to 1 by -X showrefcount command line option.

Need a debug build of Python (Py_REF_DEBUG macro must be defined).

int site_import

在启动时导入 site 模块?

int skip_source_first_line

Skip the first line of the source?

wchar_t* stdio_encoding
wchar_t* stdio_errors

Encoding and encoding errors of sys.stdin, sys.stdout and sys.stderr.

int tracemalloc

如果为非零值,则在启动时调用 tracemalloc.start()

int use_environment

If greater than 0, use environment variables.

int user_site_directory

If non-zero, add user site directory to sys.path.

int verbose

If non-zero, enable verbose mode.

PyWideStringList warnoptions

sys.warnoptions: options of the warnings module to build warnings filters: lowest to highest priority.

warnings 模块以相反的顺序添加 sys.warnoptions: 最后一个 PyConfig.warnoptions 条目将成为 warnings.filters 的第一个条目并将最先被检查(最高优先级)。

int write_bytecode

If non-zero, write .pyc files.

sys.dont_write_bytecode 会被初始化为 write_bytecode 取反后的值。

PyWideStringList xoptions

sys._xoptions.

If parse_argv is non-zero, argv arguments are parsed the same way the regular Python parses command line arguments, and Python arguments are stripped from argv: see Command Line Arguments.

The xoptions options are parsed to set other options: see -X option.

使用 PyConfig 初始化

用于初始化 Python 的函数:

PyStatus Py_InitializeFromConfig(const PyConfig *config)

根据 config 配置来初始化 Python。

调用方要负责使用 PyStatus_Exception()Py_ExitStatusException() 来处理异常(错误或退出)。

If PyImport_FrozenModules, PyImport_AppendInittab() or PyImport_ExtendInittab() are used, they must be set or called after Python preinitialization and before the Python initialization.

设置程序名称的示例:

void init_python(void)
{
    PyStatus status;

    PyConfig config;
    PyConfig_InitPythonConfig(&config);

    /* Set the program name. Implicitly preinitialize Python. */
    status = PyConfig_SetString(&config, &config.program_name,
                                L"/path/to/my_program");
    if (PyStatus_Exception(status)) {
        goto fail;
    }

    status = Py_InitializeFromConfig(&config);
    if (PyStatus_Exception(status)) {
        goto fail;
    }
    PyConfig_Clear(&config);
    return;

fail:
    PyConfig_Clear(&config);
    Py_ExitStatusException(status);
}

More complete example modifying the default configuration, read the configuration, and then override some parameters:

PyStatus init_python(const char *program_name)
{
    PyStatus status;

    PyConfig config;
    PyConfig_InitPythonConfig(&config);

    /* Set the program name before reading the configuration
       (decode byte string from the locale encoding).

       Implicitly preinitialize Python. */
    status = PyConfig_SetBytesString(&config, &config.program_name,
                                  program_name);
    if (PyStatus_Exception(status)) {
        goto done;
    }

    /* Read all configuration at once */
    status = PyConfig_Read(&config);
    if (PyStatus_Exception(status)) {
        goto done;
    }

    /* Append our custom search path to sys.path */
    status = PyWideStringList_Append(&config.module_search_paths,
                                     L"/path/to/more/modules");
    if (PyStatus_Exception(status)) {
        goto done;
    }

    /* Override executable computed by PyConfig_Read() */
    status = PyConfig_SetString(&config, &config.executable,
                                L"/path/to/my_executable");
    if (PyStatus_Exception(status)) {
        goto done;
    }

    status = Py_InitializeFromConfig(&config);

done:
    PyConfig_Clear(&config);
    return status;
}

隔离配置

PyPreConfig_InitIsolatedConfig()PyConfig_InitIsolatedConfig() 函数会创建一个配置来将 Python 与系统隔离开来。 例如,将 Python 嵌入到某个应用程序。

This configuration ignores global configuration variables, environments variables, command line arguments (PyConfig.argv is not parsed) and user site directory. The C standard streams (ex: stdout) and the LC_CTYPE locale are left unchanged. Signal handlers are not installed.

Configuration files are still used with this configuration. Set the Path Configuration ("output fields") to ignore these configuration files and avoid the function computing the default path configuration.

Python 配置

PyPreConfig_InitPythonConfig()PyConfig_InitPythonConfig() 函数会创建一个配置来构建一个行为与常规 Python 相同的自定义 Python。

环境变量和命令行参数将被用于配置 Python,而全局配置变量将被忽略。

This function enables C locale coercion (PEP 538) and UTF-8 Mode (PEP 540) depending on the LC_CTYPE locale, PYTHONUTF8 and PYTHONCOERCECLOCALE environment variables.

定制的 Python 的示例总是会以隔离模式运行:

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 fail;
    }

    status = Py_InitializeFromConfig(&config);
    if (PyStatus_Exception(status)) {
        goto fail;
    }
    PyConfig_Clear(&config);

    return Py_RunMain();

fail:
    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);
}

路径配置

PyConfig 包含多个用于路径配置的字段:

If at least one "output field" is not set, Python calculates the path configuration to fill unset fields. If module_search_paths_set is equal to 0, module_search_paths is overridden and module_search_paths_set is set to 1.

It is possible to completely ignore the function calculating the default path configuration by setting explicitly all path configuration output fields listed above. A string is considered as set even if it is non-empty. module_search_paths is considered as set if module_search_paths_set is set to 1. In this case, path configuration input fields are ignored as well.

Set pathconfig_warnings to 0 to suppress warnings when calculating the path configuration (Unix only, Windows does not log any warning).

如果 base_prefixbase_exec_prefix 字段未设置,它们将分别从 prefixexec_prefix 继承其值。

Py_RunMain()Py_Main() 将修改 sys.path:

  • 如果 run_filename 已设置并且是一个包含 __main__.py 脚本的目录,则会将 run_filename 添加到 sys.path 的开头。

  • 如果 isolated 为零:

    • 如果设置了 run_module,则将当前目录添加到 sys.path 的开头。 如果无法读取当前目录则不执行任何操作。

    • 如果设置了 run_filename,则将文件名的目录添加到 sys.path 的开头。

    • 在其他情况下,则将一个空字符串添加到 sys.path 的开头。

如果 site_import 为非零值,则 sys.path 可通过 site 模块修改。 如果 user_site_directory 为非零值且用户的 site-package 目录存在,则 site 模块会将用户的 site-package 目录附加到 sys.path

路径配置会使用以下配置文件:

  • pyvenv.cfg

  • python._pth (仅Windows)

  • pybuilddir.txt (仅Unix)

__PYVENV_LAUNCHER__ 环境变量将被用于设置 PyConfig.base_executable

Py_RunMain()

int Py_RunMain(void)

执行在命令行或配置中指定的命令 (PyConfig.run_command)、脚本 (PyConfig.run_filename) 或模块 (PyConfig.run_module)。

在默认情况下如果使用了 -i 选项,则运行 REPL。

最后,终结化 Python 并返回一个可传递给 exit() 函数的退出状态。

请参阅 Python 配置 查看一个使用 Py_RunMain() 在隔离模式下始终运行自定义 Python 的示例。

多阶段初始化私有暂定 API

This section is a private provisional API introducing multi-phase initialization, the core feature of the PEP 432:

  • “核心”初始化阶段,“最小化的基本 Python”:

    • 内置类型;

    • 内置异常;

    • 内置和已冻结模块;

    • sys 模块仅部分初始化(例如: sys.path 尚不存在)。

  • "主要"初始化阶段,Python 被完全初始化:

私有临时API:

PyStatus _Py_InitializeMain(void)

进入“主要”初始化阶段,完成 Python 初始化。

在“核心”阶段不会导入任何模块,也不会配置 importlib 模块: 路径配置 只会在“主要”阶段期间应用。 这可能允许在 Python 中定制 Python 以覆盖或微调 路径配置,也可能会安装自定义的 sys.meta_path 导入器或导入钩子等等。

It may become possible to calculatin the Path Configuration in Python, after the Core phase and before the Main phase, which is one of the PEP 432 motivation.

“核心”阶段并没有完整的定义:在这一阶段什么应该可用什么不应该可用都尚未被指明。 该 API 被标记为私有和暂定的:也就是说该 API 可以随时被修改甚至被移除直到设计出适用的公共 API。

在“核心”和“主要”初始化阶段之间运行 Python 代码的示例:

void init_python(void)
{
    PyStatus status;

    PyConfig config;
    PyConfig_InitPythonConfig(&config);
    config._init_main = 0;

    /* ... customize 'config' configuration ... */

    status = Py_InitializeFromConfig(&config);
    PyConfig_Clear(&config);
    if (PyStatus_Exception(status)) {
        Py_ExitStatusException(status);
    }

    /* Use sys.stderr because sys.stdout is only created
       by _Py_InitializeMain() */
    int res = PyRun_SimpleString(
        "import sys; "
        "print('Run Python code before _Py_InitializeMain', "
               "file=sys.stderr)");
    if (res < 0) {
        exit(1);
    }

    /* ... put more configuration code here ... */

    status = _Py_InitializeMain();
    if (PyStatus_Exception(status)) {
        Py_ExitStatusException(status);
    }
}