Python 初始化配置

PyInitConfig C API

在 3.14 版本加入。

Python 可以使用 Py_InitializeFromInitConfig() 進行初始化。

Py_RunMain() 函式可以用來編寫自定義的 Python 程式。

另請參閱 初始化、終止化和執行緒

參見

PEP 741 “Python Configuration C API”。

示例

一個自定義 Python 始終在啟用 Python 開發模式 下執行的示例;出錯時返回 -1

int init_python(void)
{
    PyInitConfig *config = PyInitConfig_Create();
    if (config == NULL) {
        printf("PYTHON INIT ERROR: memory allocation failed\n");
        return -1;
    }

    // Enable the Python Development Mode
    if (PyInitConfig_SetInt(config, "dev_mode", 1) < 0) {
        goto error;
    }

    // Initialize Python with the configuration
    if (Py_InitializeFromInitConfig(config) < 0) {
        goto error;
    }
    PyInitConfig_Free(config);
    return 0;

error:
    {
        // Display the error message.
        //
        // This uncommon braces style is used, because you cannot make
        // goto targets point to variable declarations.
        const char *err_msg;
        (void)PyInitConfig_GetError(config, &err_msg);
        printf("PYTHON INIT ERROR: %s\n", err_msg);
        PyInitConfig_Free(config);
        return -1;
    }
}

建立配置

struct PyInitConfig

用於配置 Python 初始化的不透明結構。

PyInitConfig *PyInitConfig_Create(void)

使用 隔離配置 預設值建立新的初始化配置。

它必須透過 PyInitConfig_Free() 釋放。

記憶體分配失敗時返回 NULL

void PyInitConfig_Free(PyInitConfig *config)

釋放初始化配置 config 的記憶體。

如果 configNULL,則不執行任何操作。

錯誤處理

int PyInitConfig_GetError(PyInitConfig *config, const char **err_msg)

獲取 config 的錯誤訊息。

  • 如果設定了錯誤,則設定 *err_msg 並返回 1

  • 否則,將 *err_msg 設定為 NULL 並返回 0

錯誤訊息是 UTF-8 編碼的字串。

如果 config 有退出程式碼,則將退出程式碼格式化為錯誤訊息。

錯誤訊息在呼叫另一個帶有 configPyInitConfig 函式之前保持有效。呼叫者無需釋放錯誤訊息。

int PyInitConfig_GetExitCode(PyInitConfig *config, int *exitcode)

獲取 config 的退出程式碼。

  • 如果 config 設定了退出程式碼,則設定 *exitcode 並返回 1

  • 如果 config 沒有設定退出程式碼,則返回 0

只有在 parse_argv 選項非零時,Py_InitializeFromInitConfig() 函式才能設定退出程式碼。

當命令列解析失敗(退出程式碼 2)或命令列選項要求顯示命令列幫助(退出程式碼 0)時,可以設定退出程式碼。

獲取選項

配置選項 name 引數必須是一個非 NULL 的、以 null 結尾的 UTF-8 編碼字串。請參閱 配置選項

int PyInitConfig_HasOption(PyInitConfig *config, const char *name)

測試配置是否有一個名為 name 的選項。

如果選項存在,則返回 1,否則返回 0

int PyInitConfig_GetInt(PyInitConfig *config, const char *name, int64_t *value)

獲取整數配置選項。

  • 設定 *value,成功時返回 0

  • config 中設定錯誤並返回 -1

int PyInitConfig_GetStr(PyInitConfig *config, const char *name, char **value)

將字串配置選項獲取為以 null 結尾的 UTF-8 編碼字串。

  • 設定 *value,成功時返回 0

  • config 中設定錯誤並返回 -1

如果選項是可選字串且未設定,*value 可以設定為 NULL

成功時,如果字串不為 NULL,則必須使用 free(value) 釋放。

int PyInitConfig_GetStrList(PyInitConfig *config, const char *name, size_t *length, char ***items)

將字串列表配置選項獲取為以 null 結尾的 UTF-8 編碼字串陣列。

  • 設定 *length*value,成功時返回 0

  • config 中設定錯誤並返回 -1

成功時,字串列表必須透過 PyInitConfig_FreeStrList(length, items) 釋放。

void PyInitConfig_FreeStrList(size_t length, char **items)

釋放由 PyInitConfig_GetStrList() 建立的字串列表的記憶體。

設定選項

配置選項 name 引數必須是一個非 NULL 的、以 null 結尾的 UTF-8 編碼字串。請參閱 配置選項

某些配置選項對其他選項具有副作用。此邏輯僅在呼叫 Py_InitializeFromInitConfig() 時實現,而不是透過下面的“Set”函式實現。例如,將 dev_mode 設定為 1 並不會將 faulthandler 設定為 1

int PyInitConfig_SetInt(PyInitConfig *config, const char *name, int64_t value)

設定整數配置選項。

  • 成功時返回 0

  • config 中設定錯誤並返回 -1

int PyInitConfig_SetStr(PyInitConfig *config, const char *name, const char *value)

從以 null 結尾的 UTF-8 編碼字串設定字串配置選項。字串被複制。

  • 成功時返回 0

  • config 中設定錯誤並返回 -1

int PyInitConfig_SetStrList(PyInitConfig *config, const char *name, size_t length, char *const *items)

從以 null 結尾的 UTF-8 編碼字串陣列設定字串列表配置選項。字串列表被複制。

  • 成功時返回 0

  • config 中設定錯誤並返回 -1

模組

int PyInitConfig_AddModule(PyInitConfig *config, const char *name, PyObject *(*initfunc)(void))

將內建擴充套件模組新增到內建模組表中。

新模組可以按名稱 name 匯入,並使用函式 initfunc 作為首次嘗試匯入時呼叫的初始化函式。

  • 成功時返回 0

  • config 中設定錯誤並返回 -1

如果 Python 被多次初始化,PyInitConfig_AddModule() 必須在每次 Python 初始化時呼叫。

類似於 PyImport_AppendInittab() 函式。

初始化 Python

int Py_InitializeFromInitConfig(PyInitConfig *config)

從初始化配置初始化 Python。

  • 成功時返回 0

  • config 中設定錯誤並返回 -1

  • 如果 Python 需要退出,則在 config 中設定退出程式碼並返回 -1

有關退出程式碼的情況,請參閱 PyInitConfig_GetExitcode()

配置選項

選項

PyConfig/PyPreConfig 成員

型別

可見性

"allocator"

allocator

int

只讀

"argv"

argv

list[str]

公開

"base_exec_prefix"

base_exec_prefix

str

公開

"base_executable"

base_executable

str

公開

"base_prefix"

base_prefix

str

公開

"buffered_stdio"

buffered_stdio

bool

只讀

"bytes_warning"

bytes_warning

int

公開

"check_hash_pycs_mode"

check_hash_pycs_mode

str

只讀

"code_debug_ranges"

code_debug_ranges

bool

只讀

"coerce_c_locale"

coerce_c_locale

bool

只讀

"coerce_c_locale_warn"

coerce_c_locale_warn

bool

只讀

"configure_c_stdio"

configure_c_stdio

bool

只讀

"configure_locale"

configure_locale

bool

只讀

"cpu_count"

cpu_count

int

公開

"dev_mode"

dev_mode

bool

只讀

"dump_refs"

dump_refs

bool

只讀

"dump_refs_file"

dump_refs_file

str

只讀

"exec_prefix"

exec_prefix

str

公開

"executable"

executable

str

公開

"faulthandler"

faulthandler

bool

只讀

"filesystem_encoding"

filesystem_encoding

str

只讀

"filesystem_errors"

filesystem_errors

str

只讀

"hash_seed"

hash_seed

int

只讀

"home"

home

str

只讀

"import_time"

import_time

int

只讀

"inspect"

inspect

bool

公開

"install_signal_handlers"

install_signal_handlers

bool

只讀

"int_max_str_digits"

int_max_str_digits

int

公開

"interactive"

互動

bool

公開

"isolated"

isolated

bool

只讀

"legacy_windows_fs_encoding"

legacy_windows_fs_encoding

bool

只讀

"legacy_windows_stdio"

legacy_windows_stdio

bool

只讀

"malloc_stats"

malloc_stats

bool

只讀

"module_search_paths"

module_search_paths

list[str]

公開

"optimization_level"

optimization_level

int

公開

"orig_argv"

orig_argv

list[str]

只讀

"parse_argv"

parse_argv

bool

只讀

"parser_debug"

parser_debug

bool

公開

"pathconfig_warnings"

pathconfig_warnings

bool

只讀

"perf_profiling"

perf_profiling

bool

只讀

"platlibdir"

platlibdir

str

公開

"prefix"

prefix

str

公開

"program_name"

program_name

str

只讀

"pycache_prefix"

pycache_prefix

str

公開

"quiet"

quiet

bool

公開

"run_command"

run_command

str

只讀

"run_filename"

run_filename

str

只讀

"run_module"

run_module

str

只讀

"run_presite"

run_presite

str

只讀

"safe_path"

safe_path

bool

只讀

"show_ref_count"

show_ref_count

bool

只讀

"site_import"

site_import

bool

只讀

"skip_source_first_line"

skip_source_first_line

bool

只讀

"stdio_encoding"

stdio_encoding

str

只讀

"stdio_errors"

stdio_errors

str

只讀

"stdlib_dir"

stdlib_dir

str

公開

"tracemalloc"

tracemalloc

int

只讀

"use_environment"

use_environment

bool

公開

"use_frozen_modules"

use_frozen_modules

bool

只讀

"use_hash_seed"

use_hash_seed

bool

只讀

"use_system_logger"

use_system_logger

bool

只讀

"user_site_directory"

user_site_directory

bool

只讀

"utf8_mode"

utf8_mode

bool

只讀

"verbose"

verbose

int

公開

"warn_default_encoding"

warn_default_encoding

bool

只讀

"warnoptions"

warnoptions

list[str]

公開

"write_bytecode"

write_bytecode

bool

公開

"xoptions"

xoptions

dict[str, str]

公開

"_pystats"

_pystats

bool

只讀

可見性

執行時 Python 配置 API

在執行時,可以使用 PyConfig_Get()PyConfig_Set() 函式獲取和設定配置選項。

配置選項 name 引數必須是一個非 NULL 的、以 null 結尾的 UTF-8 編碼字串。請參閱 配置選項

某些選項從 sys 屬性讀取。例如,選項 "argv"sys.argv 讀取。

PyObject *PyConfig_Get(const char *name)

獲取配置選項的當前執行時值作為 Python 物件。

  • 成功時返回一個新引用。

  • 出錯時設定一個異常並返回 NULL

物件型別取決於配置選項。它可以是

  • bool

  • int

  • str

  • list[str]

  • dict[str, str]

呼叫者必須具有 附加的執行緒狀態。該函式不能在 Python 初始化之前或 Python 終止之後呼叫。

在 3.14 版本加入。

int PyConfig_GetInt(const char *name, int *value)

類似於 PyConfig_Get(),但將值作為 C 整型獲取。

  • 成功時返回 0

  • 出錯時設定一個異常並返回 -1

在 3.14 版本加入。

PyObject *PyConfig_Names(void)

frozenset 形式獲取所有配置選項名稱。

  • 成功時返回一個新引用。

  • 出錯時設定一個異常並返回 NULL

呼叫者必須具有 附加的執行緒狀態。該函式不能在 Python 初始化之前或 Python 終止之後呼叫。

在 3.14 版本加入。

int PyConfig_Set(const char *name, PyObject *value)

設定配置選項的當前執行時值。

  • 如果沒有選項 name,則引發 ValueError

  • 如果 value 是無效值,則引發 ValueError

  • 如果選項是隻讀的(不能設定),則引發 ValueError

  • 如果 value 沒有正確的型別,則引發 TypeError

呼叫者必須具有 附加的執行緒狀態。該函式不能在 Python 初始化之前或 Python 終止之後呼叫。

使用引數 name, value 觸發 審計事件 cpython.PyConfig_Set

在 3.14 版本加入。

PyConfig C API

在 3.8 版本加入。

Python 可以使用 Py_InitializeFromConfig()PyConfig 結構體進行初始化。它可以使用 Py_PreInitialize()PyPreConfig 結構體進行預初始化。

有兩種配置

  • Python 配置 可用於構建一個行為與常規 Python 相同的自定義 Python。例如,環境變數和命令列引數用於配置 Python。

  • 隔離配置 可用於將 Python 嵌入到應用程式中。它將 Python 與系統隔離。例如,環境變數被忽略,LC_CTYPE 語言環境保持不變,並且不註冊訊號處理程式。

Py_RunMain() 函式可以用來編寫自定義的 Python 程式。

另請參閱 初始化、終止化和執行緒

參見

PEP 587 “Python 初始化配置”。

示例

始終在隔離模式下執行的自定義 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 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);
}

PyWideStringList

type 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 必須大於或等於 0

必須預初始化 Python 才能呼叫此函式。

結構欄位

Py_ssize_t length

列表長度。

wchar_t **items

列表項。

PyStatus

type PyStatus

用於儲存初始化函式狀態的結構體:成功、錯誤或退出。

對於錯誤,它可以儲存建立錯誤的 C 函式名稱。

結構欄位

int exitcode

退出程式碼。傳遞給 exit() 的引數。

const char *err_msg

錯誤訊息。

const char *func

建立錯誤的函式名稱,可以是 NULL

建立狀態的函式

PyStatus PyStatus_Ok(void)

成功。

PyStatus PyStatus_Error(const char *err_msg)

帶有訊息的初始化錯誤。

err_msg 不得為 NULL

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

type PyPreConfig

用於預初始化 Python 的結構體。

初始化預配置的函式

void PyPreConfig_InitPythonConfig(PyPreConfig *preconfig)

使用 Python 配置 初始化預配置。

void PyPreConfig_InitIsolatedConfig(PyPreConfig *preconfig)

使用 隔離配置 初始化預配置。

結構欄位

int allocator

Python 記憶體分配器的名稱

如果 Python 使用 --without-pymalloc 配置,則不支援 PYMEM_ALLOCATOR_PYMALLOCPYMEM_ALLOCATOR_PYMALLOC_DEBUG

如果 Python 使用 --without-mimalloc 配置 或底層原子支援不可用,則不支援 PYMEM_ALLOCATOR_MIMALLOCPYMEM_ALLOCATOR_MIMALLOC_DEBUG

請參閱 記憶體管理

預設值:PYMEM_ALLOCATOR_NOT_SET

int configure_locale

將 LC_CTYPE 語言環境設定為使用者首選語言環境。

如果等於 0,則將 coerce_c_localecoerce_c_locale_warn 成員設定為 0

請參閱 語言環境編碼

預設值:Python 配置中為 1,隔離配置中為 0

int coerce_c_locale

如果等於 2,則強制 C 語言環境。

如果等於 1,則讀取 LC_CTYPE 語言環境以決定是否應強制。

請參閱 語言環境編碼

預設值:Python 配置中為 -1,隔離配置中為 0

int coerce_c_locale_warn

如果非零,則在強制 C 語言環境時發出警告。

預設值:Python 配置中為 -1,隔離配置中為 0

int dev_mode

Python 開發模式:請參閱 PyConfig.dev_mode

預設值:Python 模式下為 -1,隔離模式下為 0

int isolated

隔離模式:請參閱 PyConfig.isolated

預設值:Python 模式下為 0,隔離模式下為 1

int legacy_windows_fs_encoding

如果非零

PYTHONLEGACYWINDOWSFSENCODING 環境變數值初始化。

僅在 Windows 上可用。#ifdef MS_WINDOWS 宏可用於 Windows 特定的程式碼。

預設值:0

int parse_argv

如果非零,Py_PreInitializeFromArgs()Py_PreInitializeFromBytesArgs() 將以常規 Python 解析命令列引數的相同方式解析其 argv 引數:請參閱 命令列引數

預設值:Python 配置中為 1,隔離配置中為 0

int use_environment

使用 環境變數?請參閱 PyConfig.use_environment

預設值:Python 配置中為 1,隔離配置中為 0

int utf8_mode

如果非零,則啟用 Python UTF-8 模式

透過 -X utf8 命令列選項和 PYTHONUTF8 環境變數設定為 01

如果 LC_CTYPE 語言環境是 CPOSIX,也設定為 1

預設值:Python 配置中為 -1,隔離配置中為 0

使用 PyPreConfig 預初始化 Python

Python 的預初始化

當前的預配置(PyPreConfig 型別)儲存在 _PyRuntime.preconfig 中。

預初始化 Python 的函式

PyStatus Py_PreInitialize(const PyPreConfig *preconfig)

preconfig 預配置預初始化 Python。

preconfig 不得為 NULL

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

preconfig 預配置預初始化 Python。

如果 preconfigparse_argv 非零,則解析 argv 命令列引數(位元組字串)。

preconfig 不得為 NULL

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

preconfig 預配置預初始化 Python。

如果 preconfigparse_argv 非零,則解析 argv 命令列引數(寬字串)。

preconfig 不得為 NULL

呼叫者有責任使用 PyStatus_Exception()Py_ExitStatusException() 處理異常(錯誤或退出)。

對於 Python 配置 (PyPreConfig_InitPythonConfig()),如果 Python 使用命令列引數初始化,則命令列引數也必須傳遞給預初始化 Python,因為它們對預配置(如編碼)有影響。例如,-X utf8 命令列選項啟用 Python UTF-8 模式

PyMem_SetAllocator() 可以在 Py_PreInitialize() 之後和 Py_InitializeFromConfig() 之前呼叫,以安裝自定義記憶體分配器。如果 PyPreConfig.allocator 設定為 PYMEM_ALLOCATOR_NOT_SET,則可以在 Py_PreInitialize() 之前呼叫它。

Python 記憶體分配函式(如 PyMem_RawMalloc())在 Python 預初始化之前不得使用,而直接呼叫 malloc()free() 始終是安全的。Py_DecodeLocale() 在 Python 預初始化之前不得呼叫。

使用預初始化啟用 Python UTF-8 模式 的示例

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 speaks UTF-8 */

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

PyConfig

type PyConfig

包含大多數配置 Python 引數的結構體。

完成後,必須使用 PyConfig_Clear() 函式釋放配置記憶體。

結構方法

void PyConfig_InitPythonConfig(PyConfig *config)

使用 Python 配置 初始化配置。

void PyConfig_InitIsolatedConfig(PyConfig *config)

使用 隔離配置 初始化配置。

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

將寬字元字串 str 複製到 *config_str 中。

如果需要,預初始化 Python

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

使用 Py_DecodeLocale() 解碼 str,並將結果設定到 *config_str 中。

如果需要,預初始化 Python

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

從寬字元字串列表 argv 設定命令列引數(configargv 成員)。

如果需要,預初始化 Python

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

從位元組字串列表 argv 設定命令列引數(configargv 成員)。使用 Py_DecodeLocale() 解碼位元組。

如果需要,預初始化 Python

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

將寬字串列表 list 設定為 lengthitems

如果需要,預初始化 Python

PyStatus PyConfig_Read(PyConfig *config)

讀取所有 Python 配置。

已初始化的欄位保持不變。

從 Python 3.11 開始,呼叫此函式時不再計算或修改 路徑配置 的欄位。

PyConfig_Read() 函式只解析 PyConfig.argv 引數一次:在引數解析後,PyConfig.parse_argv 設定為 2。由於 Python 引數從 PyConfig.argv 中刪除,兩次解析引數會將應用程式選項解析為 Python 選項。

如果需要,預初始化 Python

3.10 版中已更改: PyConfig.argv 引數現在只解析一次,引數解析後 PyConfig.parse_argv 設定為 2,並且只有當 PyConfig.parse_argv 等於 1 時才解析引數。

3.11 版中已更改: PyConfig_Read() 不再計算所有路徑,因此在呼叫 Py_InitializeFromConfig() 之前,Python 路徑配置 下列出的欄位可能不再更新。

void PyConfig_Clear(PyConfig *config)

釋放配置記憶體。

大多數 PyConfig 方法會在需要時預初始化 Python。在這種情況下,Python 預初始化配置(PyPreConfig)基於 PyConfig。如果調整了與 PyPreConfig 相同的配置欄位,則必須在呼叫 PyConfig 方法之前設定它們。

此外,如果使用了 PyConfig_SetArgv()PyConfig_SetBytesArgv(),則此方法必須在其他方法之前呼叫,因為預初始化配置依賴於命令列引數(如果 parse_argv 非零)。

這些方法的呼叫者負責使用 PyStatus_Exception()Py_ExitStatusException() 處理異常(錯誤或退出)。

結構欄位

PyWideStringList argv

根據 argv 設定 sys.argv 命令列引數。這些引數與傳遞給程式的 main() 函式的引數類似,不同之處在於第一個條目應指向要執行的指令碼檔案,而不是託管 Python 直譯器的可執行檔案。如果沒有要執行的指令碼,則 argv 中的第一個條目可以為空字串。

parse_argv 設定為 1,以與常規 Python 解析 Python 命令列引數相同的方式解析 argv,然後從 argv 中刪除 Python 引數。

如果 argv 為空,則新增一個空字串以確保 sys.argv 始終存在且從不為空。

預設值:NULL

另請參閱 orig_argv 成員。

int safe_path

如果等於零,則 Py_RunMain() 在啟動時將一個可能不安全的路徑新增到 sys.path 中。

  • 如果 argv[0] 等於 L"-m"python -m module),則預置當前工作目錄。

  • 如果執行指令碼(python script.py),則預置指令碼的目錄。如果是符號連結,則解析符號連結。

  • 否則(python -c codepython),預置一個空字串,這意味著當前工作目錄。

-P 命令列選項和 PYTHONSAFEPATH 環境變數設定為 1

預設值:Python 配置中為 0,隔離配置中為 1

在 3.11 版本中新增。

wchar_t *base_exec_prefix

sys.base_exec_prefix.

預設值:NULL

Python 路徑配置 輸出的一部分。

另請參閱 PyConfig.exec_prefix

wchar_t *base_executable

Python 基礎可執行檔案:sys._base_executable

__PYVENV_LAUNCHER__ 環境變數設定。

如果 NULL,則從 PyConfig.executable 設定。

預設值:NULL

Python 路徑配置 輸出的一部分。

另請參閱 PyConfig.executable

wchar_t *base_prefix

sys.base_prefix.

預設值:NULL

Python 路徑配置 輸出的一部分。

另請參閱 PyConfig.prefix

int buffered_stdio

如果等於 0 並且 configure_c_stdio 非零,則停用 C 標準輸出和標準錯誤流上的緩衝。

-u 命令列選項和 PYTHONUNBUFFERED 環境變數設定為 0

標準輸入始終以緩衝模式開啟。

預設值:1

int bytes_warning

如果等於 1,則在比較 bytesbytearraystr 時發出警告,或在比較 bytesint 時發出警告。

如果等於或大於 2,則在這些情況下引發 BytesWarning 異常。

-b 命令列選項遞增。

預設值:0

int warn_default_encoding

如果非零,當 io.TextIOWrapper 使用其預設編碼時,發出 EncodingWarning 警告。有關詳細資訊,請參閱 Opt-in EncodingWarning

預設值:0

在 3.10 版本加入。

int code_debug_ranges

如果等於 0,則停用在程式碼物件中包含結束行和列對映。還停用追溯列印插入符號到特定錯誤位置。

PYTHONNODEBUGRANGES 環境變數和 -X no_debug_ranges 命令列選項設定為 0

預設值:1

在 3.11 版本中新增。

wchar_t *check_hash_pycs_mode

控制基於雜湊的 .pyc 檔案的驗證行為:--check-hash-based-pycs 命令列選項的值。

有效值

  • L"always":無論“check_source”標誌的值如何,都對原始檔進行雜湊以進行失效。

  • L"never":假設基於雜湊的 pycs 始終有效。

  • L"default":基於雜湊的 pycs 中的“check_source”標誌決定失效。

預設值:L"default"

另請參閱 PEP 552 “確定性 pycs”。

int configure_c_stdio

如果非零,則配置 C 標準流。

  • 在 Windows 上,設定 stdin、stdout 和 stderr 的二進位制模式(O_BINARY)。

  • 如果 buffered_stdio 等於零,則停用 stdin、stdout 和 stderr 流的緩衝。

  • 如果 interactive 非零,則啟用 stdin 和 stdout 上的流緩衝(Windows 上僅 stdout)。

預設值:Python 配置中為 1,隔離配置中為 0

int dev_mode

如果非零,則啟用 Python 開發模式

-X dev 選項和 PYTHONDEVMODE 環境變數設定為 1

預設值:Python 模式下為 -1,隔離模式下為 0

int dump_refs

轉儲 Python 引用?

如果非零,則轉儲退出時仍然活動的所有物件。

PYTHONDUMPREFS 環境變數設定為 1

需要使用定義了 Py_TRACE_REFS 宏的特殊 Python 構建:請參閱 configure --with-trace-refs option

預設值:0

wchar_t *dump_refs_file

轉儲 Python 引用的檔名。

PYTHONDUMPREFSFILE 環境變數設定。

預設值:NULL

在 3.11 版本中新增。

wchar_t *exec_prefix

安裝平臺相關 Python 檔案的特定於站點的目錄字首:sys.exec_prefix

預設值:NULL

Python 路徑配置 輸出的一部分。

另請參閱 PyConfig.base_exec_prefix

wchar_t *executable

Python 直譯器可執行二進位制檔案的絕對路徑:sys.executable

預設值:NULL

Python 路徑配置 輸出的一部分。

另請參閱 PyConfig.base_executable

int faulthandler

啟用錯誤處理器?

如果非零,則在啟動時呼叫 faulthandler.enable()

-X faulthandlerPYTHONFAULTHANDLER 環境變數設定為 1

預設值:Python 模式下為 -1,隔離模式下為 0

wchar_t *filesystem_encoding

檔案系統編碼sys.getfilesystemencoding()

在 macOS、Android 和 VxWorks 上:預設使用 "utf-8"

在 Windows 上:預設使用 "utf-8",如果 PyPreConfiglegacy_windows_fs_encoding 非零,則使用 "mbcs"

其他平臺上的預設編碼

  • 如果 PyPreConfig.utf8_mode 非零,則為 "utf-8"

  • 如果 Python 檢測到 nl_langinfo(CODESET) 宣佈 ASCII 編碼,而 mbstowcs() 函式從不同的編碼(通常是 Latin1)解碼,則為 "ascii"

  • 如果 nl_langinfo(CODESET) 返回空字串,則為 "utf-8"

  • 否則,使用 locale encodingnl_langinfo(CODESET) 結果。

在 Python 啟動時,編碼名稱被規範化為 Python 編解碼器名稱。例如,"ANSI_X3.4-1968" 被替換為 "ascii"

另請參閱 filesystem_errors 成員。

wchar_t *filesystem_errors

檔案系統錯誤處理器sys.getfilesystemencodeerrors()

在 Windows 上:預設使用 "surrogatepass",如果 PyPreConfiglegacy_windows_fs_encoding 非零,則使用 "replace"

在其他平臺:預設使用 "surrogateescape"

支援的錯誤處理器

  • "strict"

  • "surrogateescape"

  • "surrogatepass"(僅支援 UTF-8 編碼)

另請參閱 filesystem_encoding 成員。

int use_frozen_modules

如果非零,則使用凍結模組。

PYTHON_FROZEN_MODULES 環境變數設定。

預設值:釋出版本中為 1除錯版本中為 0

unsigned long hash_seed
int use_hash_seed

隨機化雜湊函式種子。

如果 use_hash_seed 為零,則在 Python 啟動時隨機選擇一個種子,並忽略 hash_seed

PYTHONHASHSEED 環境變數設定。

預設的 use_hash_seed 值:Python 模式下為 -1,隔離模式下為 0

wchar_t *home

設定預設的 Python “home” 目錄,即標準 Python 庫的位置(請參閱 PYTHONHOME)。

PYTHONHOME 環境變數設定。

預設值:NULL

Python 路徑配置 輸入的一部分。

int import_time

如果為 1,則分析匯入時間。如果為 2,則包含額外的輸出,指示匯入的模組何時已載入。

-X importtime 選項和 PYTHONPROFILEIMPORTTIME 環境變數設定。

預設值:0

3.14 版本中的變化: 增加了對 import_time = 2 的支援。

int inspect

執行指令碼或命令後進入互動模式。

如果大於 0,則啟用檢查模式:當指令碼作為第一個引數傳遞或使用 -c 選項時,執行指令碼或命令後進入互動模式,即使 sys.stdin 似乎不是終端。

-i 命令列選項遞增。如果 PYTHONINSPECT 環境變數非空,則設定為 1

預設值:0

int install_signal_handlers

安裝 Python 訊號處理器?

預設值:Python 模式下為 1,隔離模式下為 0

int interactive

如果大於 0,則啟用互動模式 (REPL)。

-i 命令列選項遞增。

預設值:0

int int_max_str_digits

配置整數字符串轉換長度限制。初始值 -1 表示該值將從命令列或環境變數中獲取,否則預設為 4300(sys.int_info.default_max_str_digits)。值為 0 會停用限制。大於零但小於 640(sys.int_info.str_digits_check_threshold)的值不受支援,並將產生錯誤。

-X int_max_str_digits 命令列標誌或 PYTHONINTMAXSTRDIGITS 環境變數配置。

預設值:Python 模式下為 -1。隔離模式下為 4300(sys.int_info.default_max_str_digits)。

3.12 新版功能.

int cpu_count

如果 cpu_count 的值不是 -1,那麼它將覆蓋 os.cpu_count()os.process_cpu_count()multiprocessing.cpu_count() 的返回值。

-X cpu_count=n|default 命令列標誌或 PYTHON_CPU_COUNT 環境變數配置。

預設值:-1

在 3.13 版本加入。

int isolated

如果大於 0,則啟用隔離模式。

  • safe_path 設定為 1:在 Python 啟動時,不要將可能不安全的路徑(如當前目錄、指令碼目錄或空字串)新增到 sys.path 中。

  • use_environment 設定為 0:忽略 PYTHON 環境變數。

  • user_site_directory 設定為 0:不要將使用者站點目錄新增到 sys.path

  • Python REPL 不會匯入 readline,也不會在互動式提示符下啟用預設的 readline 配置。

-I 命令列選項設定為 1

預設值:Python 模式下為 0,隔離模式下為 1

另請參閱 隔離配置PyPreConfig.isolated

int legacy_windows_stdio

如果非零,則對 sys.stdinsys.stdoutsys.stderr 使用 io.FileIO 而不是 io._WindowsConsoleIO

如果 PYTHONLEGACYWINDOWSSTDIO 環境變數設定為非空字串,則設定為 1

僅在 Windows 上可用。#ifdef MS_WINDOWS 宏可用於 Windows 特定的程式碼。

預設值:0

另請參閱 PEP 528(更改 Windows 控制檯編碼為 UTF-8)。

int malloc_stats

如果非零,則在退出時轉儲 Python pymalloc 記憶體分配器 的統計資訊。

PYTHONMALLOCSTATS 環境變數設定為 1

如果 Python 使用 --without-pymalloc 選項 配置,則忽略該選項。

預設值:0

wchar_t *platlibdir

平臺庫目錄名稱:sys.platlibdir

PYTHONPLATLIBDIR 環境變數設定。

預設值:PLATLIBDIR 宏的值,該值由 configure --with-platlibdir option 設定(預設值:"lib",Windows 上為 "DLLs")。

Python 路徑配置 輸入的一部分。

在 3.9 版本中新增。

3.11 版本中的變化: 此宏現在在 Windows 上用於定位標準庫擴充套件模組,通常在 DLLs 下。然而,為了相容性,請注意,對於任何非標準佈局(包括樹內構建和虛擬環境),此值都會被忽略。

wchar_t *pythonpath_env

模組搜尋路徑(sys.path)作為由 DELIMos.pathsep)分隔的字串。

PYTHONPATH 環境變數設定。

預設值:NULL

Python 路徑配置 輸入的一部分。

PyWideStringList module_search_paths
int module_search_paths_set

模組搜尋路徑:sys.path

如果 module_search_paths_set 等於 0Py_InitializeFromConfig() 將替換 module_search_paths 並將 module_search_paths_set 設定為 1

預設值:空列表(module_search_paths)和 0module_search_paths_set)。

Python 路徑配置 輸出的一部分。

int optimization_level

編譯最佳化級別。

  • 0:窺孔最佳化器,將 __debug__ 設定為 True

  • 1:級別 0,移除斷言,將 __debug__ 設定為 False

  • 2:級別 1,移除文件字串。

-O 命令列選項遞增。設定為 PYTHONOPTIMIZE 環境變數的值。

預設值:0

PyWideStringList orig_argv

傳遞給 Python 可執行檔案的原始命令列引數列表:sys.orig_argv

如果 orig_argv 列表為空且 argv 不是僅包含空字串的列表,PyConfig_Read() 在修改 argv 之前將 argv 複製到 orig_argv(如果 parse_argv 非零)。

另請參閱 argv 成員和 Py_GetArgcArgv() 函式。

預設值:空列表。

在 3.10 版本加入。

int parse_argv

解析命令列引數?

如果等於 1,則以常規 Python 解析命令列引數的相同方式解析 argv,並從 argv 中刪除 Python 引數。

PyConfig_Read() 函式只解析 PyConfig.argv 引數一次:在引數解析後,PyConfig.parse_argv 設定為 2。由於 Python 引數從 PyConfig.argv 中刪除,兩次解析引數會將應用程式選項解析為 Python 選項。

預設值:Python 模式下為 1,隔離模式下為 0

3.10 版本中的變化: 現在僅當 PyConfig.parse_argv 等於 1 時,才解析 PyConfig.argv 引數。

int parser_debug

解析器除錯模式。如果大於 0,則開啟解析器除錯輸出(僅限專家,取決於編譯選項)。

-d 命令列選項遞增。設定為 PYTHONDEBUG 環境變數的值。

需要 Python 的除錯構建(必須定義 Py_DEBUG 宏)。

預設值:0

int pathconfig_warnings

如果非零,則允許路徑配置計算將警告記錄到 stderr 中。如果等於 0,則抑制這些警告。

預設值:Python 模式下為 1,隔離模式下為 0

Python 路徑配置 輸入的一部分。

3.11 版本中的變化: 現在也適用於 Windows。

wchar_t *prefix

安裝平臺無關 Python 檔案的特定於站點的目錄字首:sys.prefix

預設值:NULL

Python 路徑配置 輸出的一部分。

另請參閱 PyConfig.base_prefix

wchar_t *program_name

用於初始化 executable 和在 Python 初始化期間早期錯誤訊息中使用的程式名稱。

  • 在 macOS 上,如果設定了 PYTHONEXECUTABLE 環境變數,則使用它。

  • 如果定義了 WITH_NEXT_FRAMEWORK 宏,則如果設定了 __PYVENV_LAUNCHER__ 環境變數,則使用它。

  • 如果可用且非空,則使用 argvargv[0]

  • 否則,在 Windows 上使用 L"python",在其他平臺使用 L"python3"

預設值:NULL

Python 路徑配置 輸入的一部分。

wchar_t *pycache_prefix

快取的 .pyc 檔案寫入的目錄:sys.pycache_prefix

-X pycache_prefix=PATH 命令列選項和 PYTHONPYCACHEPREFIX 環境變數設定。命令列選項優先。

如果為 NULL,則將 sys.pycache_prefix 設定為 None

預設值:NULL

int quiet

靜默模式。如果大於 0,則在互動模式下 Python 啟動時不顯示版權和版本。

-q 命令列選項遞增。

預設值:0

wchar_t *run_command

-c 命令列選項的值。

Py_RunMain() 使用。

預設值:NULL

wchar_t *run_filename

命令列上傳遞的檔名:不帶 -c-m 的尾隨命令列引數。它由 Py_RunMain() 函式使用。

例如,透過 python3 script.py arg 命令列設定為 script.py

另請參閱 PyConfig.skip_source_first_line 選項。

預設值:NULL

wchar_t *run_module

-m 命令列選項的值。

Py_RunMain() 使用。

預設值:NULL

wchar_t *run_presite

package.module 路徑,指向應在 site.py 執行之前匯入的模組。

-X presite=package.module 命令列選項和 PYTHON_PRESITE 環境變數設定。命令列選項優先。

需要 Python 的除錯構建(必須定義 Py_DEBUG 宏)。

預設值:NULL

int show_ref_count

在退出時顯示總引用計數(不包括永生物件)?

-X showrefcount 命令列選項設定為 1

需要 Python 的除錯構建(必須定義 Py_REF_DEBUG 宏)。

預設值:0

int site_import

在啟動時匯入 site 模組?

如果等於零,則停用模組 site 的匯入以及它所導致的 sys.path 的站點相關操作。

如果 site 模組稍後被顯式匯入,也會停用這些操作(如果您希望觸發它們,請呼叫 site.main())。

-S 命令列選項設定為 0

sys.flags.no_site 被設定為 site_import 的反轉值。

預設值:1

int skip_source_first_line

如果非零,則跳過 PyConfig.run_filename 源的第一行。

它允許使用非 Unix 形式的 #!cmd。這僅用於 DOS 特定的駭客手段。

-x 命令列選項設定為 1

預設值:0

wchar_t *stdio_encoding
wchar_t *stdio_errors

sys.stdinsys.stdoutsys.stderr 的編碼和編碼錯誤(但 sys.stderr 始終使用 "backslashreplace" 錯誤處理器)。

如果 PYTHONIOENCODING 環境變數非空,則使用它。

預設編碼

預設錯誤處理器

  • 在 Windows 上:使用 "surrogateescape"

  • 如果 PyPreConfig.utf8_mode 非零,或者 LC_CTYPE 區域設定為“C”或“POSIX”,則為 "surrogateescape"

  • 否則為 "strict"

另請參閱 PyConfig.legacy_windows_stdio

int tracemalloc

啟用 tracemalloc?

如果非零,則在啟動時呼叫 tracemalloc.start()

-X tracemalloc=N 命令列選項和 PYTHONTRACEMALLOC 環境變數設定。

預設值:Python 模式下為 -1,隔離模式下為 0

int perf_profiling

啟用 Linux perf 分析器支援?

如果等於 1,則啟用對 Linux perf 分析器的支援。

如果等於 2,則啟用對帶 DWARF JIT 支援的 Linux perf 分析器的支援。

-X perf 命令列選項和 PYTHONPERFSUPPORT 環境變數設定為 1

-X perf_jit 命令列選項和 PYTHON_PERF_JIT_SUPPORT 環境變數設定為 2

預設值:-1

參見

有關詳細資訊,請參閱 Python 對 Linux perf 分析器的支援

3.12 新版功能.

wchar_t *stdlib_dir

Python 標準庫的目錄。

預設值:NULL

在 3.11 版本中新增。

int use_environment

使用環境變數

如果等於零,則忽略環境變數

-E 環境變數設定為 0

預設值:Python 配置中為 1,隔離配置中為 0

int use_system_logger

如果非零,則 stdoutstderr 將重定向到系統日誌。

僅在 macOS 10.12 及更高版本以及 iOS 上可用。

預設值:macOS 上為 0(不使用系統日誌);iOS 上為 1(使用系統日誌)。

在 3.14 版本加入。

int user_site_directory

如果非零,則將使用者站點目錄新增到 sys.path

-s-I 命令列選項設定為 0

PYTHONNOUSERSITE 環境變數設定為 0

預設值:Python 模式下為 1,隔離模式下為 0

int verbose

詳細模式。如果大於 0,則每次匯入模組時列印一條訊息,顯示其載入位置(檔名或內建模組)。

如果大於或等於 2,則為搜尋模組時檢查的每個檔案列印一條訊息。還提供退出時模組清理的資訊。

-v 命令列選項遞增。

PYTHONVERBOSE 環境變數值設定。

預設值:0

PyWideStringList warnoptions

warnings 模組的選項,用於構建警告過濾器,優先順序從低到高:sys.warnoptions

warnings 模組按相反順序新增 sys.warnoptions:最後一個 PyConfig.warnoptions 項成為 warnings.filters 的第一個項,該項首先被檢查(最高優先順序)。

-W 命令列選項將其值新增到 warnoptions,它可以多次使用。

PYTHONWARNINGS 環境變數也可以用於新增警告選項。可以指定多個選項,用逗號(,)分隔。

預設值:空列表。

int write_bytecode

如果等於 0,則 Python 不會嘗試在匯入源模組時寫入 .pyc 檔案。

-B 命令列選項和 PYTHONDONTWRITEBYTECODE 環境變數設定為 0

sys.dont_write_bytecode 初始化為 write_bytecode 的反轉值。

預設值:1

PyWideStringList xoptions

-X 命令列選項的值:sys._xoptions

預設值:空列表。

int _pystats

如果非零,則在 Python 退出時寫入效能統計資訊。

需要使用 Py_STATS 宏進行特殊構建:請參閱 --enable-pystats

預設值:0

如果 parse_argv 為非零,argv 引數的解析方式與常規 Python 解析 命令列引數 的方式相同,並且 Python 引數將從 argv 中移除。

xoptions 選項用於設定其他選項:請參閱 -X 命令列選項。

3.9 版中的變化: show_alloc_count 欄位已被移除。

使用 PyConfig 進行初始化

透過呼叫 Py_InitializeFromConfig() 來處理從已填充的配置結構初始化直譯器。

呼叫者有責任使用 PyStatus_Exception()Py_ExitStatusException() 處理異常(錯誤或退出)。

如果使用了 PyImport_FrozenModules()PyImport_AppendInittab()PyImport_ExtendInittab(),則必須在 Python 預初始化之後和 Python 初始化之前設定或呼叫它們。如果 Python 被多次初始化,PyImport_AppendInittab()PyImport_ExtendInittab() 必須在每次 Python 初始化之前呼叫。

當前配置(PyConfig 型別)儲存在 PyInterpreterState.config 中。

設定程式名稱的示例

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

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

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

更完整的示例:修改預設配置,讀取配置,然後覆蓋一些引數。請注意,自 3.11 版本以來,許多引數在初始化之前不會計算,因此無法從配置結構中讀取值。在呼叫初始化之前設定的任何值在初始化後將保持不變。

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

    /* Specify sys.path explicitly */
    /* If you want to modify the default set of paths, finish
       initialization first and then use PySys_GetObject("path") */
    config.module_search_paths_set = 1;
    status = PyWideStringList_Append(&config.module_search_paths,
                                     L"/path/to/stdlib");
    if (PyStatus_Exception(status)) {
        goto done;
    }
    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 嵌入到應用程式中。

此配置忽略全域性配置變數、環境變數、命令列引數(PyConfig.argv 未解析)和使用者站點目錄。C 標準流(例如:stdout)和 LC_CTYPE 區域設定保持不變。不安裝訊號處理程式。

此配置仍使用配置檔案來確定未指定的路徑。確保指定 PyConfig.home 以避免計算預設路徑配置。

Python 配置

PyPreConfig_InitPythonConfig()PyConfig_InitPythonConfig() 函式用於建立配置,以構建行為與常規 Python 相同的定製 Python。

環境變數和命令列引數用於配置 Python,而全域性配置變數被忽略。

此函式根據 LC_CTYPE 區域設定、PYTHONUTF8PYTHONCOERCECLOCALE 環境變數啟用 C 語言環境強制轉換 (PEP 538) 和 Python UTF-8 模式 (PEP 540)。

Python 路徑配置

PyConfig 包含用於路徑配置的多個欄位

如果至少有一個“輸出欄位”未設定,Python 會計算路徑配置以填充未設定的欄位。如果 module_search_paths_set 等於 0,則 module_search_paths 會被覆蓋,並且 module_search_paths_set 會被設定為 1

透過顯式設定上面列出的所有路徑配置輸出欄位,可以完全忽略計算預設路徑配置的函式。即使字串不為空,也被視為已設定。module_search_pathsmodule_search_paths_set 設定為 1 時被視為已設定。在這種情況下,module_search_paths 將不加修改地使用。

pathconfig_warnings 設定為 0 以抑制計算路徑配置時的警告(僅限 Unix,Windows 不會記錄任何警告)。

如果 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 模組會將使用者站點包目錄新增到 sys.path 中。

路徑配置使用以下配置檔案

  • pyvenv.cfg

  • ._pth 檔案(例如:python._pth

  • pybuilddir.txt(僅限 Unix)

如果存在 ._pth 檔案

如果 home 未設定,並且在與 executable 相同或其父目錄中存在 pyvenv.cfg 檔案,則 prefixexec_prefix 將設定為該位置。發生這種情況時,base_prefixbase_exec_prefix 仍保留其值,指向基本安裝。有關更多資訊,請參閱 虛擬環境

__PYVENV_LAUNCHER__ 環境變數用於設定 PyConfig.base_executable

3.14 版中的變化: prefixexec_prefix 現在設定為 pyvenv.cfg 目錄。這以前由 site 完成,因此受 -S 影響。

Py_GetArgcArgv()

void Py_GetArgcArgv(int *argc, wchar_t ***argv)

獲取 Python 修改之前的原始命令列引數。

另請參閱 PyConfig.orig_argv 成員。

延遲主模組執行

在某些嵌入用例中,可能需要將直譯器初始化與主模組的執行分開。

這種分離可以透過在初始化期間將 PyConfig.run_command 設定為空字串(以防止直譯器進入互動式提示符),然後隨後使用 __main__.__dict__ 作為全域性名稱空間執行所需的主模組程式碼來實現。