Конфігурація ініціалізації Python¶
PyInitConfig C API¶
Added in version 3.14.
Python can be initialized with Py_InitializeFromInitConfig().
Функцію Py_RunMain() можна використовувати для написання спеціальної програми Python.
Дивіться також Ініціалізація, фіналізація та потоки.
Дивись також
PEP 741 «Python Configuration C API».
приклад¶
Example of customized Python always running with the Python Development
Mode enabled; return -1 on error:
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;
}
}
Create Config¶
-
struct PyInitConfig¶
Opaque structure to configure the Python initialization.
-
PyInitConfig *PyInitConfig_Create(void)¶
Create a new initialization configuration using Isolated Configuration default values.
It must be freed by
PyInitConfig_Free().Return
NULLon memory allocation failure.
-
void PyInitConfig_Free(PyInitConfig *config)¶
Free memory of the initialization configuration config.
If config is
NULL, no operation is performed.
Error Handling¶
-
int PyInitConfig_GetError(PyInitConfig *config, const char **err_msg)¶
Get the config error message.
Set *err_msg and return
1if an error is set.Set *err_msg to
NULLand return0otherwise.
An error message is an UTF-8 encoded string.
If config has an exit code, format the exit code as an error message.
The error message remains valid until another
PyInitConfigfunction is called with config. The caller doesn’t have to free the error message.
-
int PyInitConfig_GetExitCode(PyInitConfig *config, int *exitcode)¶
Get the config exit code.
Set *exitcode and return
1if config has an exit code set.Return
0if config has no exit code set.
Only the
Py_InitializeFromInitConfig()function can set an exit code if theparse_argvoption is non-zero.An exit code can be set when parsing the command line failed (exit code
2) or when a command line option asks to display the command line help (exit code0).
Get Options¶
The configuration option name parameter must be a non-NULL null-terminated UTF-8 encoded string. See Configuration Options.
-
int PyInitConfig_HasOption(PyInitConfig *config, const char *name)¶
Test if the configuration has an option called name.
Return
1if the option exists, or return0otherwise.
-
int PyInitConfig_GetInt(PyInitConfig *config, const char *name, int64_t *value)¶
Get an integer configuration option.
Set *value, and return
0on success.Set an error in config and return
-1on error.
-
int PyInitConfig_GetStr(PyInitConfig *config, const char *name, char **value)¶
Get a string configuration option as a null-terminated UTF-8 encoded string.
Set *value, and return
0on success.Set an error in config and return
-1on error.
*value can be set to
NULLif the option is an optional string and the option is unset.On success, the string must be released with
free(value)if it’s notNULL.
-
int PyInitConfig_GetStrList(PyInitConfig *config, const char *name, size_t *length, char ***items)¶
Get a string list configuration option as an array of null-terminated UTF-8 encoded strings.
Set *length and *value, and return
0on success.Set an error in config and return
-1on error.
On success, the string list must be released with
PyInitConfig_FreeStrList(length, items).
-
void PyInitConfig_FreeStrList(size_t length, char **items)¶
Free memory of a string list created by
PyInitConfig_GetStrList().
Set Options¶
The configuration option name parameter must be a non-NULL null-terminated UTF-8 encoded string. See Configuration Options.
Some configuration options have side effects on other options. This logic is
only implemented when Py_InitializeFromInitConfig() is called, not by the
«Set» functions below. For example, setting dev_mode to 1 does not set
faulthandler to 1.
-
int PyInitConfig_SetInt(PyInitConfig *config, const char *name, int64_t value)¶
Set an integer configuration option.
Return
0on success.Set an error in config and return
-1on error.
-
int PyInitConfig_SetStr(PyInitConfig *config, const char *name, const char *value)¶
Set a string configuration option from a null-terminated UTF-8 encoded string. The string is copied.
Return
0on success.Set an error in config and return
-1on error.
-
int PyInitConfig_SetStrList(PyInitConfig *config, const char *name, size_t length, char *const *items)¶
Set a string list configuration option from an array of null-terminated UTF-8 encoded strings. The string list is copied.
Return
0on success.Set an error in config and return
-1on error.
Module¶
-
int PyInitConfig_AddModule(PyInitConfig *config, const char *name, PyObject *(*initfunc)(void))¶
Add a built-in extension module to the table of built-in modules.
The new module can be imported by the name name, and uses the function initfunc as the initialization function called on the first attempted import.
Return
0on success.Set an error in config and return
-1on error.
If Python is initialized multiple times,
PyInitConfig_AddModule()must be called at each Python initialization.Similar to the
PyImport_AppendInittab()function.
Initialize Python¶
-
int Py_InitializeFromInitConfig(PyInitConfig *config)¶
Initialize Python from the initialization configuration.
Return
0on success.Set an error in config and return
-1on error.Set an exit code in config and return
-1if Python wants to exit.
See
PyInitConfig_GetExitcode()for the exit code case.
Configuration Options¶
Option |
PyConfig/PyPreConfig member |
Type |
Visibility |
|---|---|---|---|
|
|
Read-only |
|
|
|
Public |
|
|
|
Public |
|
|
|
Public |
|
|
|
Public |
|
|
|
Read-only |
|
|
|
Public |
|
|
|
Read-only |
|
|
|
Read-only |
|
|
|
Read-only |
|
|
|
Read-only |
|
|
|
Read-only |
|
|
|
Read-only |
|
|
|
Public |
|
|
|
Read-only |
|
|
|
Read-only |
|
|
|
Read-only |
|
|
|
Public |
|
|
|
Public |
|
|
|
Read-only |
|
|
|
Read-only |
|
|
|
Read-only |
|
|
|
Read-only |
|
|
|
Read-only |
|
|
|
Read-only |
|
|
|
Public |
|
|
|
Read-only |
|
|
|
Public |
|
|
|
Public |
|
|
|
Read-only |
|
|
|
Read-only |
|
|
|
Read-only |
|
|
|
Read-only |
|
|
|
Public |
|
|
|
Public |
|
|
|
Read-only |
|
|
|
Read-only |
|
|
|
Public |
|
|
|
Read-only |
|
|
|
Read-only |
|
|
|
Public |
|
|
|
Public |
|
|
|
Read-only |
|
|
|
Public |
|
|
|
Public |
|
|
|
Read-only |
|
|
|
Read-only |
|
|
|
Read-only |
|
|
|
Read-only |
|
|
|
Read-only |
|
|
|
Read-only |
|
|
|
Read-only |
|
|
|
Read-only |
|
|
|
Read-only |
|
|
|
Read-only |
|
|
|
Public |
|
|
|
Read-only |
|
|
|
Public |
|
|
|
Read-only |
|
|
|
Read-only |
|
|
|
Read-only |
|
|
|
Read-only |
|
|
|
Read-only |
|
|
|
Public |
|
|
|
Read-only |
|
|
|
Public |
|
|
|
Public |
|
|
|
Public |
|
|
|
Read-only |
Visibility:
Public: Can by get by
PyConfig_Get()and set byPyConfig_Set().Read-only: Can by get by
PyConfig_Get(), but cannot be set byPyConfig_Set().
Runtime Python configuration API¶
At runtime, it’s possible to get and set configuration options using
PyConfig_Get() and PyConfig_Set() functions.
The configuration option name parameter must be a non-NULL null-terminated UTF-8 encoded string. See Configuration Options.
Some options are read from the sys attributes. For example, the option
"argv" is read from sys.argv.
-
PyObject *PyConfig_Get(const char *name)¶
Get the current runtime value of a configuration option as a Python object.
Return a new reference on success.
Set an exception and return
NULLon error.
The object type depends on the configuration option. It can be:
boolintstrlist[str]dict[str, str]
The caller must have an attached thread state. The function cannot be called before Python initialization nor after Python finalization.
Added in version 3.14.
-
int PyConfig_GetInt(const char *name, int *value)¶
Similar to
PyConfig_Get(), but get the value as a C int.Return
0on success.Set an exception and return
-1on error.
Added in version 3.14.
-
PyObject *PyConfig_Names(void)¶
Get all configuration option names as a
frozenset.Return a new reference on success.
Set an exception and return
NULLon error.
The caller must have an attached thread state. The function cannot be called before Python initialization nor after Python finalization.
Added in version 3.14.
-
int PyConfig_Set(const char *name, PyObject *value)¶
Set the current runtime value of a configuration option.
Raise a
ValueErrorif there is no option name.Raise a
ValueErrorif value is an invalid value.Raise a
ValueErrorif the option is read-only (cannot be set).Raise a
TypeErrorif value has not the proper type.
The caller must have an attached thread state. The function cannot be called before Python initialization nor after Python finalization.
Raises an auditing event
cpython.PyConfig_Setwith argumentsname,value.Added in version 3.14.
PyConfig C API¶
Added in version 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)¶
Додайте елемент до списку.
Щоб викликати цю функцію, Python має бути попередньо ініціалізований.
-
PyStatus PyWideStringList_Insert(PyWideStringList *list, Py_ssize_t index, const wchar_t *item)¶
Вставте елемент у список за індексом.
Якщо index більше або дорівнює довжині list, додайте item до list.
index must be greater than or equal to
0.Щоб викликати цю функцію, Python має бути попередньо ініціалізований.
Поля структури:
-
Py_ssize_t length¶
Довжина списку.
-
wchar_t **items¶
Список елементів.
-
PyStatus PyWideStringList_Append(PyWideStringList *list, const wchar_t *item)¶
PyStatus¶
-
type PyStatus¶
Структура для збереження стану функції ініціалізації: успіх, помилка або вихід.
Для помилки він може зберегти назву функції C, яка створила помилку.
Поля структури:
-
int exitcode¶
Код виходу. Аргумент, переданий до
exit().
-
const char *err_msg¶
Повідомлення про помилку.
-
const char *func¶
Ім’я функції, яка створила помилку, може бути
NULL.
Функції для створення статусу:
-
PyStatus PyStatus_Error(const char *err_msg)¶
Помилка ініціалізації з повідомленням.
err_msg не має бути
NULL.
Функції для обробки статусу:
-
int PyStatus_Exception(PyStatus status)¶
Статус помилка чи вихід? Якщо істина, виняток потрібно обробити; наприклад, викликом
Py_ExitStatusException().
-
int exitcode¶
Примітка
Внутрішньо 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:
PYMEM_ALLOCATOR_NOT_SET(0): не змінювати розподільники пам’яті (використовувати значення за замовчуванням).PYMEM_ALLOCATOR_DEFAULT(1): розподіл пам’яті за замовчуванням.PYMEM_ALLOCATOR_DEBUG(2): розподільники пам’яті за замовчуванням з налагоджувальними хуками.PYMEM_ALLOCATOR_MALLOC(3): використовуйтеmalloc()бібліотеки C.PYMEM_ALLOCATOR_MALLOC_DEBUG(4): примусове використанняmalloc()з налагоджувальними хуками.PYMEM_ALLOCATOR_PYMALLOC(5): Виділювач пам’яті Python pymalloc.PYMEM_ALLOCATOR_PYMALLOC_DEBUG(6): Розподіл пам’яті Python pymalloc з налагоджувальними хуками.PYMEM_ALLOCATOR_MIMALLOC(6): usemimalloc, a fast malloc replacement.PYMEM_ALLOCATOR_MIMALLOC_DEBUG(7): usemimalloc, a fast malloc replacement with debug hooks.
PYMEM_ALLOCATOR_PYMALLOCіPYMEM_ALLOCATOR_PYMALLOC_DEBUGне підтримуються, якщо Pythonналаштовано за допомогою --without-pymalloc.PYMEM_ALLOCATOR_MIMALLOCandPYMEM_ALLOCATOR_MIMALLOC_DEBUGare not supported if Python isconfigured using --without-mimallocor if the underlying atomic support isn’t available.Перегляньте Керування пам’яттю.
Типове значення:
PYMEM_ALLOCATOR_NOT_SET.
-
int configure_locale¶
Set the LC_CTYPE locale to the user preferred locale.
If equals to
0, setcoerce_c_localeandcoerce_c_locale_warnmembers to0.Перегляньте locale encoding.
За замовчуванням:
1у конфігурації Python,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.Перегляньте locale encoding.
За замовчуванням:
-1у конфігурації Python,0в ізольованій конфігурації.
-
int coerce_c_locale_warn¶
Якщо значення відмінне від нуля, видати попередження, якщо локаль C виведена примусово.
За замовчуванням:
-1у конфігурації Python,0в ізольованій конфігурації.
-
int dev_mode¶
Python Development Mode: see
PyConfig.dev_mode.Типове значення:
-1в режимі Python,0в ізольованому режимі.
-
int isolated¶
Ізольований режим: див.
PyConfig.isolated.Типове значення:
0в режимі Python,1в ізольованому режимі.
-
int legacy_windows_fs_encoding¶
Якщо відмінне від нуля:
Установіть
PyPreConfig.utf8_modeна0,Установіть
PyConfig.filesystem_encodingна"mbcs",Установіть
PyConfig.filesystem_errorsна"replace".
Initialized from the
PYTHONLEGACYWINDOWSFSENCODINGenvironment variable value.Доступно лише для Windows. Макрос
#ifdef MS_WINDOWSможна використовувати для спеціального коду Windows.Типове значення:
0.
-
int parse_argv¶
Якщо значення відмінне від нуля,
Py_PreInitializeFromArgs()іPy_PreInitializeFromBytesArgs()аналізують свій аргументargvтак само, як звичайний Python аналізує аргументи командного рядка: див. Аргументи командного рядка.За замовчуванням:
1у конфігурації Python,0в ізольованій конфігурації.
-
int use_environment¶
Використовувати змінні середовища? Перегляньте
PyConfig.use_environment.За замовчуванням:
1у конфігурації Python і0в ізольованій конфігурації.
-
int utf8_mode¶
Якщо не нуль, увімкніть Режим Python UTF-8.
Set to
0or1by the-X utf8command line option and thePYTHONUTF8environment variable.Also set to
1if theLC_CTYPElocale isCorPOSIX.За замовчуванням:
-1у конфігурації Python і0в ізольованій конфігурації.
-
void PyPreConfig_InitPythonConfig(PyPreConfig *preconfig)¶
Попередня ініціалізація Python за допомогою PyPreConfig¶
Попередня ініціалізація Python:
Встановіть розподільники пам’яті Python (
PyPreConfig.allocator)Налаштувати локаль LC_CTYPE (locale encoding)
Установіть режим Python UTF-8 Mode (
PyPreConfig.utf8_mode)
Поточна попередня конфігурація (тип PyPreConfig) зберігається в _PyRuntime.preconfig.
Функції для попередньої ініціалізації Python:
-
PyStatus Py_PreInitialize(const PyPreConfig *preconfig)¶
Попередньо ініціалізуйте Python із попередньої конфігурації preconfig.
preconfig не має бути
NULL.
-
PyStatus Py_PreInitializeFromBytesArgs(const PyPreConfig *preconfig, int argc, char *const *argv)¶
Попередньо ініціалізуйте Python із попередньої конфігурації preconfig.
Проаналізуйте аргументи командного рядка argv (рядки байтів), якщо
parse_argvpreconfig не дорівнює нулю.preconfig не має бути
NULL.
-
PyStatus Py_PreInitializeFromArgs(const PyPreConfig *preconfig, int argc, wchar_t *const *argv)¶
Попередньо ініціалізуйте Python із попередньої конфігурації preconfig.
Проаналізуйте аргументи командного рядка argv (широкі рядки), якщо
parse_argvpreconfig не дорівнює нулю.preconfig не має бути
NULL.
Виклик відповідає за обробку винятків (помилка або вихід) за допомогою PyStatus_Exception() і Py_ExitStatusException().
Для Конфігурації Python (PyPreConfig_InitPythonConfig()), якщо Python ініціалізовано аргументами командного рядка, аргументи командного рядка також потрібно передати для попередньої ініціалізації Python, оскільки вони впливають на попередні конфігурація, як кодування. Наприклад, параметр командного рядка -X utf8 вмикає Режим Python UTF-8.
PyMem_SetAllocator() можна викликати після Py_PreInitialize() і перед Py_InitializeFromConfig(), щоб встановити спеціальний розподільник пам’яті. Його можна викликати перед Py_PreInitialize(), якщо PyPreConfig.allocator має значення PYMEM_ALLOCATOR_NOT_SET.
Функції виділення пам’яті 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)¶
Декодуйте str за допомогою
Py_DecodeLocale()і встановіть результат у*config_str.Попередньо ініціалізуйте Python, якщо потрібно.
-
PyStatus PyConfig_SetArgv(PyConfig *config, int argc, wchar_t *const *argv)¶
Установіть аргументи командного рядка (
argvчлен config) зі списку argv рядків широких символів.Попередньо ініціалізуйте Python, якщо потрібно.
-
PyStatus PyConfig_SetBytesArgv(PyConfig *config, int argc, char *const *argv)¶
Установіть аргументи командного рядка (
argvчлен config) зі списку argv рядків байтів. Декодуйте байти за допомогоюPy_DecodeLocale().Попередньо ініціалізуйте Python, якщо потрібно.
-
PyStatus PyConfig_SetWideStringList(PyConfig *config, PyWideStringList *list, Py_ssize_t length, wchar_t **items)¶
Установіть для списку широких рядків list значення length і items.
Попередньо ініціалізуйте Python, якщо потрібно.
-
PyStatus PyConfig_Read(PyConfig *config)¶
Прочитайте всю конфігурацію Python.
Поля, які вже ініціалізовані, залишаються без змін.
Fields for path configuration are no longer calculated or modified when calling this function, as of Python 3.11.
The
PyConfig_Read()function only parsesPyConfig.argvarguments once:PyConfig.parse_argvis set to2after arguments are parsed. Since Python arguments are stripped fromPyConfig.argv, parsing arguments twice would parse the application options as Python options.Попередньо ініціалізуйте Python, якщо потрібно.
Змінено в версії 3.10: Аргументи
PyConfig.argvтепер аналізуються лише один раз,PyConfig.parse_argvвстановлюється на2після аналізу аргументів, і аргументи аналізуються, лише якщоPyConfig.parse_argvдорівнює1.Змінено в версії 3.11:
PyConfig_Read()no longer calculates all paths, and so fields listed under Python Path Configuration may no longer be updated untilPy_InitializeFromConfig()is called.
Більшість методів
PyConfigза необхідності попередньо ініціалізують Python. У цьому випадку конфігурація попередньої ініціалізації Python (PyPreConfig) базується наPyConfig. Якщо поля конфігурації, які є спільними зPyPreConfig, налаштовано, їх потрібно встановити перед викликом методуPyConfig:Moreover, if
PyConfig_SetArgv()orPyConfig_SetBytesArgv()is used, this method must be called before other methods, since the preinitialization configuration depends on command line arguments (ifparse_argvis non-zero).Виклик цих методів відповідає за обробку винятків (помилка або вихід) за допомогою
PyStatus_Exception()іPy_ExitStatusException().Поля структури:
-
PyWideStringList argv¶
Set
sys.argvcommand line arguments based onargv. These parameters are similar to those passed to the program’smain()function with the difference that the first entry should refer to the script file to be executed rather than the executable hosting the Python interpreter. If there isn’t a script that will be run, the first entry inargvcan be an empty string.Установіть для
parse_argvзначення1, щоб аналізуватиargvтак само, як звичайний Python аналізує аргументи командного рядка Python, а потім видаляти аргументи Python зargv.Якщо
argvпорожній, додається порожній рядок, щоб гарантувати, щоsys.argvзавжди існує і ніколи не буде порожнім.Типове значення:
NULL.Дивіться також елемент
orig_argv.
-
int safe_path¶
If equals to zero,
Py_RunMain()prepends a potentially unsafe path tosys.pathat startup:If
argv[0]is equal toL"-m"(python -m module), prepend the current working directory.If running a script (
python script.py), prepend the script’s directory. If it’s a symbolic link, resolve symbolic links.Otherwise (
python -c codeandpython), prepend an empty string, which means the current working directory.
Set to
1by the-Pcommand line option and thePYTHONSAFEPATHenvironment variable.Default:
0in Python config,1in isolated config.Added in version 3.11.
-
wchar_t *base_exec_prefix¶
-
Типове значення:
NULL.Частина виведення Налаштування шляху Python.
See also
PyConfig.exec_prefix.
-
wchar_t *base_executable¶
Базовий виконуваний файл Python:
sys._base_executable.Встановлюється змінною середовища
__PYVENV_LAUNCHER__.Установити з
PyConfig.executable, якщоNULL.Типове значення:
NULL.Частина виведення Налаштування шляху Python.
See also
PyConfig.executable.
-
wchar_t *base_prefix¶
-
Типове значення:
NULL.Частина виведення Налаштування шляху Python.
See also
PyConfig.prefix.
-
int buffered_stdio¶
If equals to
0andconfigure_c_stdiois non-zero, disable buffering on the C streams stdout and stderr.Set to
0by the-ucommand line option and thePYTHONUNBUFFEREDenvironment variable.stdin завжди відкривається в режимі буферизації.
Типове значення:
1.
-
int bytes_warning¶
If equals to
1, issue a warning when comparingbytesorbytearraywithstr, or comparingbyteswithint.If equal or greater to
2, raise aBytesWarningexception in these cases.Збільшується параметром командного рядка
-b.Типове значення:
0.
-
int warn_default_encoding¶
Якщо не нуль, видавати попередження
EncodingWarning, колиio.TextIOWrapperвикористовує кодування за замовчуванням. Дивіться Увімкніть EncodingWarning для деталей.Типове значення:
0.Added in version 3.10.
-
int code_debug_ranges¶
If equals to
0, disables the inclusion of the end line and column mappings in code objects. Also disables traceback printing carets to specific error locations.Set to
0by thePYTHONNODEBUGRANGESenvironment variable and by the-X no_debug_rangescommand line option.Типове значення:
1.Added in version 3.11.
-
wchar_t *check_hash_pycs_mode¶
Керуйте поведінкою перевірки файлів
.pycна основі хешу: значення параметра командного рядка--check-hash-based-pycs.Дійсні значення:
L"always": хеш вихідного файлу для визнання недійсним незалежно від значення позначки „check_source“.L"never": припустимо, що pics на основі хешу завжди дійсні.L"default": прапор „check_source“ у pycs на основі хешу визначає недійсність.
Типове значення:
L"default".Дивіться також PEP 552 «Детерміновані фото».
-
int configure_c_stdio¶
Якщо не нуль, налаштуйте стандартні потоки C:
У Windows установіть бінарний режим (
O_BINARY) для stdin, stdout і stderr.Якщо
buffered_stdioдорівнює нулю, вимкніть буферизацію потоків stdin, stdout і stderr.Якщо
interactiveне дорівнює нулю, увімкніть буферизацію потоку на stdin і stdout (лише stdout у Windows).
За замовчуванням:
1у конфігурації Python,0в ізольованій конфігурації.
-
int dev_mode¶
Якщо не нуль, увімкніть Режим розробки Python.
Set to
1by the-X devoption and thePYTHONDEVMODEenvironment variable.Типове значення:
-1в режимі Python,0в ізольованому режимі.
-
int dump_refs¶
Скинути посилання на Python?
Якщо значення відмінне від нуля, скинути всі об’єкти, які ще живі при виході.
Установіть значення
1за допомогою змінної середовищаPYTHONDUMPREFS.Needs a special build of Python with the
Py_TRACE_REFSmacro defined: see theconfigure --with-trace-refs option.Типове значення:
0.
-
wchar_t *dump_refs_file¶
Filename where to dump Python references.
Set by the
PYTHONDUMPREFSFILEenvironment variable.Типове значення:
NULL.Added in version 3.11.
-
wchar_t *exec_prefix¶
Префікс каталогу сайту, де встановлено файли Python, залежні від платформи:
sys.exec_prefix.Типове значення:
NULL.Частина виведення Налаштування шляху Python.
See also
PyConfig.base_exec_prefix.
-
wchar_t *executable¶
Абсолютний шлях виконуваного двійкового файлу для інтерпретатора Python:
sys.executable.Типове значення:
NULL.Частина виведення Налаштування шляху Python.
See also
PyConfig.base_executable.
-
int faulthandler¶
Увімкнути обробник помилок?
Якщо не нуль, викликати
faulthandler.enable()під час запуску.Установіть значення
1за допомогою-X faulthandlerі змінної середовищаPYTHONFAULTHANDLER.Типове значення:
-1в режимі Python,0в ізольованому режимі.
-
wchar_t *filesystem_encoding¶
Кодування файлової системи:
sys.getfilesystemencoding().У macOS, Android і VxWorks: використовуйте
"utf-8"за умовчанням.У Windows: використовуйте
"utf-8"за замовчуванням або"mbcs", якщоlegacy_windows_fs_encodingPyPreConfigне дорівнює нулю.Стандартне кодування на інших платформах:
"utf-8", якщоPyPreConfig.utf8_modeне нульовий."ascii", якщо Python виявляє, щоnl_langinfo(CODESET)повідомляє про кодування ASCII, тоді як функціяmbstowcs()декодує з іншого кодування (зазвичай Latin1)."utf-8", якщоnl_langinfo(CODESET)повертає порожній рядок.В іншому випадку використовуйте результат locale encoding:
nl_langinfo(CODESET).
Під час запуску Python назва кодування нормалізується до назви кодека Python. Наприклад,
"ANSI_X3.4-1968"замінюється на"ascii".Дивіться також елемент
filesystem_errors.
-
wchar_t *filesystem_errors¶
Обробник помилок файлової системи:
sys.getfilesystemencodeerrors().У Windows: використовуйте
"surrogatepass"за замовчуванням або"replace", якщоlegacy_windows_fs_encodingPyPreConfigне дорівнює нулю.На інших платформах: використовуйте
"surrogateescape"за умовчанням.Підтримувані засоби обробки помилок:
"суворий""сурогатна втеча""surrogatepass"(підтримується лише з кодуванням UTF-8)
Дивіться також елемент
filesystem_encoding.
-
int use_frozen_modules¶
If non-zero, use frozen modules.
Set by the
PYTHON_FROZEN_MODULESenvironment variable.Default:
1in a release build, or0in a debug build.
-
unsigned long hash_seed¶
-
int use_hash_seed¶
Рандомізоване початкове значення хеш-функції.
Якщо
use_hash_seedдорівнює нулю, початкове значення вибирається випадковим чином під час запуску Python, аhash_seedігнорується.Встановлюється змінною середовища
PYTHONHASHSEED.Значення use_hash_seed за замовчуванням:
-1у режимі Python,0в ізольованому режимі.
-
wchar_t *home¶
Set the default Python «home» directory, that is, the location of the standard Python libraries (see
PYTHONHOME).Встановлюється змінною середовища
PYTHONHOME.Типове значення:
NULL.Частина вхідних даних Налаштування шляху Python.
-
int import_time¶
If
1, profile import time. If2, include additional output that indicates when an imported module has already been loaded.Set by the
-X importtimeoption and thePYTHONPROFILEIMPORTTIMEenvironment variable.Типове значення:
0.Змінено в версії 3.14: Added support for
import_time = 2
-
int inspect¶
Увійти в інтерактивний режим після виконання сценарію або команди.
If greater than
0, enable inspect: when a script is passed as first argument or the -c option is used, enter interactive mode after executing the script or the command, even whensys.stdindoes not appear to be a terminal.Збільшується параметром командного рядка
-i. Установіть значення1, якщо змінна середовищаPYTHONINSPECTне порожня.Типове значення:
0.
-
int install_signal_handlers¶
Установити обробники сигналів Python?
Типове значення:
1в режимі Python,0в ізольованому режимі.
-
int interactive¶
If greater than
0, enable the interactive mode (REPL).Збільшується параметром командного рядка
-i.Типове значення:
0.
-
int int_max_str_digits¶
Configures the integer string conversion length limitation. An initial value of
-1means the value will be taken from the command line or environment or otherwise default to 4300 (sys.int_info.default_max_str_digits). A value of0disables the limitation. Values greater than zero but less than 640 (sys.int_info.str_digits_check_threshold) are unsupported and will produce an error.Configured by the
-X int_max_str_digitscommand line flag or thePYTHONINTMAXSTRDIGITSenvironment variable.Default:
-1in Python mode. 4300 (sys.int_info.default_max_str_digits) in isolated mode.Added in version 3.12.
-
int cpu_count¶
If the value of
cpu_countis not-1then it will override the return values ofos.cpu_count(),os.process_cpu_count(), andmultiprocessing.cpu_count().Configured by the
-X cpu_count=n|defaultcommand line flag or thePYTHON_CPU_COUNTenvironment variable.Default:
-1.Added in version 3.13.
-
int isolated¶
If greater than
0, enable isolated mode:Set
safe_pathto1: don’t prepend a potentially unsafe path tosys.pathat Python startup, such as the current directory, the script’s directory or an empty string.Set
use_environmentto0: ignorePYTHONenvironment variables.Set
user_site_directoryto0: don’t add the user site directory tosys.path.Python REPL не імпортує
readlineі не вмикає стандартну конфігурацію readline в інтерактивних підказках.
Set to
1by the-Icommand line option.Типове значення:
0в режимі Python,1в ізольованому режимі.See also the Isolated Configuration and
PyPreConfig.isolated.
-
int legacy_windows_stdio¶
If non-zero, use
io.FileIOinstead ofio._WindowsConsoleIOforsys.stdin,sys.stdoutandsys.stderr.Установіть значення
1, якщо змінна середовищаPYTHONLEGACYWINDOWSSTDIOмає значення непорожнього рядка.Доступно лише для Windows. Макрос
#ifdef MS_WINDOWSможна використовувати для спеціального коду Windows.Типове значення:
0.Дивіться також PEP 528 (Змінити кодування консолі Windows на UTF-8).
-
int malloc_stats¶
Якщо значення відмінне від нуля, вивести статистику на Python pymalloc memory allocator при виході.
Установіть значення
1за допомогою змінної середовищаPYTHONMALLOCSTATS.Параметр ігнорується, якщо Python
налаштовано за допомогою параметра --without-pymalloc.Типове значення:
0.
-
wchar_t *platlibdir¶
Назва каталогу бібліотеки платформи:
sys.platlibdir.Встановлюється змінною середовища
PYTHONPLATLIBDIR.Default: value of the
PLATLIBDIRmacro which is set by theconfigure --with-platlibdir option(default:"lib", or"DLLs"on Windows).Частина вхідних даних Налаштування шляху Python.
Added in version 3.9.
Змінено в версії 3.11: This macro is now used on Windows to locate the standard library extension modules, typically under
DLLs. However, for compatibility, note that this value is ignored for any non-standard layouts, including in-tree builds and virtual environments.
-
wchar_t *pythonpath_env¶
Module search paths (
sys.path) as a string separated byDELIM(os.pathsep).Встановлюється змінною середовища
PYTHONPATH.Типове значення:
NULL.Частина вхідних даних Налаштування шляху Python.
-
PyWideStringList module_search_paths¶
-
int module_search_paths_set¶
Шляхи пошуку модуля:
sys.path.If
module_search_paths_setis equal to0,Py_InitializeFromConfig()will replacemodule_search_pathsand setsmodule_search_paths_setto1.За замовчуванням: порожній список (
module_search_paths) і0(module_search_paths_set).Частина виведення Налаштування шляху Python.
-
int optimization_level¶
Рівень оптимізації компіляції:
0: оптимізатор Peephole, встановіть__debug__наTrue.1: Рівень 0, видалити твердження, встановити__debug__наFalse.2: Рівень 1, рядки документації.
Збільшується параметром командного рядка
-O. Установіть значення змінної середовищаPYTHONOPTIMIZE.Типове значення:
0.
-
PyWideStringList orig_argv¶
Список вихідних аргументів командного рядка, переданих у виконуваний файл Python:
sys.orig_argv.Якщо список
orig_argvпорожній іargvне є списком, який містить лише порожній рядок,PyConfig_Read()копіюєargvвorig_argvперед зміноюargv(якщоparse_argvне дорівнює нулю) .Дивіться також член
argvі функціюPy_GetArgcArgv().За замовчуванням: порожній список.
Added in version 3.10.
-
int parse_argv¶
Розібрати аргументи командного рядка?
Якщо дорівнює
1, аналізуватиargvтак само, як звичайний Python аналізує аргументи командного рядка, і видаляти аргументи Python зargv.The
PyConfig_Read()function only parsesPyConfig.argvarguments once:PyConfig.parse_argvis set to2after arguments are parsed. Since Python arguments are stripped fromPyConfig.argv, parsing arguments twice would parse the application options as Python options.Типове значення:
1в режимі Python,0в ізольованому режимі.Змінено в версії 3.10: Аргументи
PyConfig.argvтепер аналізуються, лише якщоPyConfig.parse_argvдорівнює1.
-
int parser_debug¶
Parser debug mode. If greater than
0, turn on parser debugging output (for expert only, depending on compilation options).Збільшується параметром командного рядка
-d. Установіть значення змінної середовищаPYTHONDEBUG.Needs a debug build of Python (the
Py_DEBUGmacro must be defined).Типове значення:
0.
-
int pathconfig_warnings¶
If non-zero, calculation of path configuration is allowed to log warnings into
stderr. If equals to0, suppress these warnings.Типове значення:
1в режимі Python,0в ізольованому режимі.Частина вхідних даних Налаштування шляху Python.
Змінено в версії 3.11: Now also applies on Windows.
-
wchar_t *prefix¶
Префікс каталогу сайту, де встановлено незалежні від платформи файли Python:
sys.prefix.Типове значення:
NULL.Частина виведення Налаштування шляху Python.
See also
PyConfig.base_prefix.
-
wchar_t *program_name¶
Ім’я програми, що використовується для ініціалізації
executableі в ранніх повідомленнях про помилки під час ініціалізації Python.У macOS використовуйте змінну середовища
PYTHONEXECUTABLE, якщо встановлено.Якщо визначено макрос
WITH_NEXT_FRAMEWORK, використовуйте змінну середовища__PYVENV_LAUNCHER__, якщо встановлено.Використовуйте
argv[0]argv, якщо доступний і не є порожнім.В іншому випадку використовуйте
L"python"у Windows абоL"python3"на інших платформах.
Типове значення:
NULL.Частина вхідних даних Налаштування шляху Python.
-
wchar_t *pycache_prefix¶
Каталог, де записуються кешовані файли
.pyc:sys.pycache_prefix.Set by the
-X pycache_prefix=PATHcommand line option and thePYTHONPYCACHEPREFIXenvironment variable. The command-line option takes precedence.Якщо
NULL,sys.pycache_prefixмає значенняNone.Типове значення:
NULL.
-
int quiet¶
Quiet mode. If greater than
0, don’t display the copyright and version at Python startup in interactive mode.Збільшується параметром командного рядка
-q.Типове значення:
0.
-
wchar_t *run_command¶
Значення параметра командного рядка
-c.Використовується
Py_RunMain().Типове значення:
NULL.
-
wchar_t *run_filename¶
Filename passed on the command line: trailing command line argument without
-cor-m. It is used by thePy_RunMain()function.For example, it is set to
script.pyby thepython3 script.py argcommand line.See also the
PyConfig.skip_source_first_lineoption.Типове значення:
NULL.
-
wchar_t *run_module¶
Значення параметра командного рядка
-m.Використовується
Py_RunMain().Типове значення:
NULL.
-
wchar_t *run_presite¶
package.modulepath to module that should be imported beforesite.pyis run.Set by the
-X presite=package.modulecommand-line option and thePYTHON_PRESITEenvironment variable. The command-line option takes precedence.Needs a debug build of Python (the
Py_DEBUGmacro must be defined).Типове значення:
NULL.
-
int show_ref_count¶
Show total reference count at exit (excluding immortal objects)?
Set to
1by-X showrefcountcommand line option.Needs a debug build of Python (the
Py_REF_DEBUGmacro must be defined).Типове значення:
0.
-
int site_import¶
Імпортувати модуль
siteпід час запуску?Якщо дорівнює нулю, вимкніть імпорт сайту модуля та залежні від сайту маніпуляції
sys.path, які він тягне за собою.Також вимкніть ці маніпуляції, якщо модуль
siteбуде явно імпортовано пізніше (викличтеsite.main(), якщо ви хочете, щоб вони були активовані).Установіть
0за допомогою параметра командного рядка-S.sys.flags.no_siteis set to the inverted value ofsite_import.Типове значення:
1.
-
int skip_source_first_line¶
Якщо значення не нульове, пропустіть перший рядок джерела
PyConfig.run_filename.Це дозволяє використовувати не-Unix форми
#!cmd. Це призначено лише для спеціального злому DOS.Установіть значення
1за допомогою параметра командного рядка-x.Типове значення:
0.
-
wchar_t *stdio_encoding¶
-
wchar_t *stdio_errors¶
Кодування та помилки кодування
sys.stdin,sys.stdoutіsys.stderr(алеsys.stderrзавжди використовує"backslashreplace"обробник помилок).Використовуйте змінну середовища
PYTHONIOENCODING, якщо вона непорожня.Стандартне кодування:
"UTF-8", якщоPyPreConfig.utf8_modeне нульовий.В іншому випадку використовуйте locale encoding.
Обробник помилок за замовчуванням:
У Windows: використовуйте
"surrogateescape"."surrogateescape", якщоPyPreConfig.utf8_modeне нульовий, або якщо LC_CTYPE локаль «C» або «POSIX»."строгий"інакше.
See also
PyConfig.legacy_windows_stdio.
-
int tracemalloc¶
Увімкнути tracemalloc?
Якщо не нуль, викликати
tracemalloc.start()під час запуску.Встановлюється параметром командного рядка
-X tracemalloc=Nі змінною середовищаPYTHONTRACEMALLOC.Типове значення:
-1в режимі Python,0в ізольованому режимі.
-
int perf_profiling¶
Enable the Linux
perfprofiler support?If equals to
1, enable support for the Linuxperfprofiler.If equals to
2, enable support for the Linuxperfprofiler with DWARF JIT support.Set to
1by-X perfcommand-line option and thePYTHONPERFSUPPORTenvironment variable.Set to
2by the-X perf_jitcommand-line option and thePYTHON_PERF_JIT_SUPPORTenvironment variable.Default:
-1.Дивись також
See Python support for the Linux perf profiler for more information.
Added in version 3.12.
-
wchar_t *stdlib_dir¶
Directory of the Python standard library.
Типове значення:
NULL.Added in version 3.11.
-
int use_environment¶
Використовувати змінні середовища?
Якщо дорівнює нулю, ігноруйте змінні середовища.
Set to
0by the-Eenvironment variable.За замовчуванням:
1у конфігурації Python і0в ізольованій конфігурації.
-
int use_system_logger¶
If non-zero,
stdoutandstderrwill be redirected to the system log.Only available on macOS 10.12 and later, and on iOS.
Default:
0(don’t use the system log) on macOS;1on iOS (use the system log).Added in version 3.14.
-
int user_site_directory¶
Якщо значення не нульове, додайте каталог сайту користувача до
sys.path.Установіть значення
0за допомогою параметрів командного рядка-sі-I.Установлено значення
0за допомогою змінної середовищаPYTHONNOUSERSITE.Типове значення:
1в режимі Python,0в ізольованому режимі.
-
int verbose¶
Verbose mode. If greater than
0, print a message each time a module is imported, showing the place (filename or built-in module) from which it is loaded.If greater than or equal to
2, print a message for each file that is checked for when searching for a module. Also provides information on module cleanup at exit.Збільшується параметром командного рядка
-v.Set by the
PYTHONVERBOSEenvironment variable value.Типове значення:
0.
-
PyWideStringList warnoptions¶
Параметри модуля
warningsдля створення фільтрів попереджень, від найнижчого до найвищого пріоритету:sys.warnoptions.Модуль
warningsдодаєsys.warnoptionsу зворотному порядку: останній елементPyConfig.warnoptionsстає першим елементомwarnings.filters, який є перевіряється першим (найвищий пріоритет).Параметр командного рядка
-Wдодає значення доwarnoptions, тому його можна використовувати кілька разів.Змінну середовища
PYTHONWARNINGSтакож можна використовувати для додавання параметрів попередження. Можна вказати декілька параметрів, розділених комами (,).За замовчуванням: порожній список.
-
int write_bytecode¶
If equal to
0, Python won’t try to write.pycfiles on the import of source modules.Установіть значення
0за допомогою параметра командного рядка-Bі змінної середовищаPYTHONDONTWRITEBYTECODE.sys.dont_write_bytecodeініціалізується інвертованим значеннямwrite_bytecode.Типове значення:
1.
-
PyWideStringList xoptions¶
Значення параметрів командного рядка
-X:sys._xoptions.За замовчуванням: порожній список.
-
int _pystats¶
If non-zero, write performance statistics at Python exit.
Need a special build with the
Py_STATSmacro: see--enable-pystats.Типове значення:
0.
-
void PyConfig_InitPythonConfig(PyConfig *config)¶
Якщо parse_argv не дорівнює нулю, аргументи argv аналізуються так само, як звичайний Python аналізує аргументи командного рядка, і Python аргументи видаляються з argv.
Параметри xoptions аналізуються, щоб встановити інші параметри: дивіться параметр командного рядка -X.
Змінено в версії 3.9: Поле show_alloc_count видалено.
Ініціалізація за допомогою PyConfig¶
Initializing the interpreter from a populated configuration struct is handled
by calling Py_InitializeFromConfig().
Виклик відповідає за обробку винятків (помилка або вихід) за допомогою PyStatus_Exception() і Py_ExitStatusException().
Якщо PyImport_FrozenModules(), PyImport_AppendInittab() або PyImport_ExtendInittab() використовуються, їх потрібно встановити або викликати після попередньої ініціалізації Python та перед ініціалізацією Python. Якщо Python ініціалізовано кілька разів, перед кожною ініціалізацією Python потрібно викликати PyImport_AppendInittab() або PyImport_ExtendInittab().
Поточна конфігурація (тип 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);
}
More complete example modifying the default configuration, read the configuration, and then override some parameters. Note that since 3.11, many parameters are not calculated until initialization, and so values cannot be read from the configuration structure. Any values set before initialize is called will be left unchanged by initialization:
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 залишаються без змін. Обробники сигналів не встановлені.
Configuration files are still used with this configuration to determine
paths that are unspecified. Ensure PyConfig.home is specified
to avoid computing the default path configuration.
Конфігурація Python¶
Функції PyPreConfig_InitPythonConfig() і PyConfig_InitPythonConfig() створюють конфігурацію для створення налаштованого Python, який веде себе як звичайний Python.
Для налаштування Python використовуються змінні середовища та аргументи командного рядка, тоді як глобальні змінні конфігурації ігноруються.
Ця функція вмикає примусове налаштування локалі C (PEP 538) і Python UTF-8 Mode (PEP 540) залежно від локалі LC_CTYPE, PYTHONUTF8 і Змінні середовища PYTHONCOERCECLOCALE.
Конфігурація шляху Python¶
PyConfig містить кілька полів для конфігурації шляху:
Вхідні дані конфігурації шляху:
поточний робочий каталог: щоб отримати абсолютні шляхи
Змінна середовища
PATH, щоб отримати повний шлях до програми (зPyConfig.program_name)Змінна середовища
__PYVENV_LAUNCHER__(Лише для Windows) Шляхи програм у реєстрі в розділі «SoftwarePythonPythonCoreX.YPythonPath» HKEY_CURRENT_USER і HKEY_LOCAL_MACHINE (де X.Y — версія Python).
Поля виведення конфігурації шляху:
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,
module_search_paths will be used without modification.
Set pathconfig_warnings to 0 to suppress warnings when
calculating the path configuration (Unix only, Windows does not log any warning).
Якщо поля base_prefix або base_exec_prefix не встановлені, вони успадковують свої значення від prefix і exec_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._pthfile (ex:python._pth)pybuilddir.txt(лише Unix)
If a ._pth file is present:
Set
isolatedto1.Set
use_environmentto0.Set
site_importto0.Set
safe_pathto1.
If home is not set and a pyvenv.cfg file is present in
the same directory as executable, or its parent,
prefix and exec_prefix are set that
location. When this happens, base_prefix and
base_exec_prefix still keep their value, pointing to the
base installation. See Virtual Environments for more
information.
The __PYVENV_LAUNCHER__ environment variable is used to set
PyConfig.base_executable.
Змінено в версії 3.14: prefix, and exec_prefix, are now
set to the pyvenv.cfg directory. This was previously done by site,
therefore affected by -S.
Py_GetArgcArgv()¶
-
void Py_GetArgcArgv(int *argc, wchar_t ***argv)¶
Отримайте оригінальні аргументи командного рядка до того, як Python їх змінив.
Дивіться також член
PyConfig.orig_argv.
Delaying main module execution¶
In some embedding use cases, it may be desirable to separate interpreter initialization from the execution of the main module.
This separation can be achieved by setting PyConfig.run_command to the empty
string during initialization (to prevent the interpreter from dropping into the
interactive prompt), and then subsequently executing the desired main module
code using __main__.__dict__ as the global namespace.