Configuración de inicialización de Python¶
PyInitConfig C API¶
Added in version 3.14.
Python can be initialized with Py_InitializeFromInitConfig().
La función Py_RunMain() se puede utilizar para escribir un programa Python personalizado.
Consulte también Inicialización, finalización y subprocesos.
Ver también
PEP 741 «Python Configuration C API».
Ejemplo¶
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 se puede inicializar con Py_InitializeFromConfig() y la estructura PyConfig. Se puede preinicializar con Py_PreInitialize() y la estructura PyPreConfig.
Hay dos tipos de configuración:
The Python Configuration can be used to build a customized Python which behaves as the regular Python. For example, environment variables and command line arguments are used to configure Python.
The Isolated Configuration can be used to embed Python into an application. It isolates Python from the system. For example, environment variables are ignored, the LC_CTYPE locale is left unchanged and no signal handler is registered.
La función Py_RunMain() se puede utilizar para escribir un programa Python personalizado.
Consulte también Inicialización, finalización y subprocesos.
Ver también
PEP 587 «Configuración de inicialización de Python».
Ejemplo¶
Ejemplo de Python personalizado que siempre se ejecuta en modo aislado:
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¶
Lista de cadenas de caracteres
wchar_t*.Si length no es cero, items no deben ser
NULLy todas las cadenas de caracteres deben ser noNULL.Métodos:
-
PyStatus PyWideStringList_Append(PyWideStringList *list, const wchar_t *item)¶
Agregar item a list.
Python debe estar preinicializado para llamar a esta función.
-
PyStatus PyWideStringList_Insert(PyWideStringList *list, Py_ssize_t index, const wchar_t *item)¶
Inserta item en list en index.
Si index es mayor o igual que el largo de list, agrega item a list.
index must be greater than or equal to
0.Python debe estar preinicializado para llamar a esta función.
Campos de estructura:
-
Py_ssize_t length¶
Longitud de la lista.
-
wchar_t **items¶
Elementos de la lista.
-
PyStatus PyWideStringList_Append(PyWideStringList *list, const wchar_t *item)¶
PyStatus¶
-
type PyStatus¶
Estructura para almacenar el estado de una función de inicialización: éxito, error o salida.
Para un error, puede almacenar el nombre de la función C que creó el error.
Campos de estructura:
-
int exitcode¶
Código de salida El argumento pasó a
exit().
-
const char *err_msg¶
Mensaje de error.
-
const char *func¶
El nombre de la función que creó un error puede ser
NULL.
Funciones para crear un estado:
-
PyStatus PyStatus_Error(const char *err_msg)¶
Error de inicialización con un mensaje.
err_msg no debe ser
NULL.
Funciones para manejar un estado:
-
int PyStatus_Exception(PyStatus status)¶
¿Es el estado un error o una salida? Si es verdadero, la excepción debe ser manejada; por ejemplo llamando a
Py_ExitStatusException().
-
int exitcode¶
Nota
Internamente, Python usa macros que establecen PyStatus.func, mientras que las funciones para crear un estado establecen func en NULL.
Ejemplo:
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¶
Estructura utilizada para preinicializar Python.
Función para inicializar una preconfiguración:
-
void PyPreConfig_InitPythonConfig(PyPreConfig *preconfig)¶
Inicializa la preconfiguración con Configuración de Python.
-
void PyPreConfig_InitIsolatedConfig(PyPreConfig *preconfig)¶
Inicializa la preconfiguración con Configuración aislada.
Campos de estructura:
-
int allocator¶
Nombre de los asignadores de memoria de Python:
PYMEM_ALLOCATOR_NOT_SET(0): no cambia asignadores de memoria (usa los valores predeterminados)PYMEM_ALLOCATOR_DEFAULT(1): asignadores de memoria predeterminados.PYMEM_ALLOCATOR_DEBUG(2): asignadores de memoria predeterminados con ganchos de depuración.PYMEM_ALLOCATOR_MALLOC(3): usamalloc()de la biblioteca C.PYMEM_ALLOCATOR_MALLOC_DEBUG(4): fuerza el uso demalloc()con ganchos de depuración.PYMEM_ALLOCATOR_PYMALLOC(5): asignador de memoria pymalloc de PythonPYMEM_ALLOCATOR_PYMALLOC_DEBUG(6): asignador de memoria pymalloc de Python con ganchos de depuración.PYMEM_ALLOCATOR_MIMALLOC(6): usemimalloc, a fast malloc replacement.PYMEM_ALLOCATOR_MIMALLOC_DEBUG(7): usemimalloc, a fast malloc replacement with debug hooks.
PYMEM_ALLOCATOR_PYMALLOCyPYMEM_ALLOCATOR_PYMALLOC_DEBUGno son compatibles si Python esconfigurado usando --without-pymalloc.PYMEM_ALLOCATOR_MIMALLOCandPYMEM_ALLOCATOR_MIMALLOC_DEBUGare not supported if Python isconfigured using --without-mimallocor if the underlying atomic support isn’t available.Ver Administración de memorias.
Predeterminado:
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.Vea el locale encoding.
Predeterminado:
1en la configuración de Python,0en la configuración aislada.
-
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.Vea el locale encoding.
Predeterminado:
-1en la configuración de Python,0en la configuración aislada.
-
int coerce_c_locale_warn¶
Si no es cero, emita una advertencia si la configuración regional C está coaccionada.
Predeterminado:
-1en la configuración de Python,0en la configuración aislada.
-
int dev_mode¶
Python Development Mode: see
PyConfig.dev_mode.Por defecto:
-1en modo Python,0en modo aislado.
-
int isolated¶
Modo aislado: consulte
PyConfig.isolated.Por defecto:
0en modo Python,1en modo aislado.
-
int legacy_windows_fs_encoding¶
Si no es cero:
Establezca
PyPreConfig.utf8_modeen0,Establezca
PyConfig.filesystem_encodingen"mbcs",Establezca
PyConfig.filesystem_errorsen"replace".
Initialized from the
PYTHONLEGACYWINDOWSFSENCODINGenvironment variable value.Solo disponible en Windows. La macro
#ifdef MS_WINDOWSse puede usar para el código específico de Windows.Predeterminado:
0.
-
int parse_argv¶
Si no es cero,
Py_PreInitializeFromArgs()yPy_PreInitializeFromBytesArgs()analizan su argumentoargvde la misma manera que Python analiza los argumentos de la línea de comandos: ver Argumentos de línea de comandos.Predeterminado:
1en la configuración de Python,0en la configuración aislada.
-
int use_environment¶
¿Utiliza variables de entorno? Consulte
PyConfig.use_environment.Predeterminado:
1en la configuración de Python y0en la configuración aislada.
-
int utf8_mode¶
Si es distinto de cero, habilite Python UTF-8 Mode.
Set to
0or1by the-X utf8command line option and thePYTHONUTF8environment variable.También se pone a
1si la configuración regionalLC_CTYPEesCoPOSIX.Predeterminado:
-1en la configuración de Python y0en la configuración aislada.
-
void PyPreConfig_InitPythonConfig(PyPreConfig *preconfig)¶
Preinicialización de Python con PyPreConfig¶
La preinicialización de Python:
Establecer los asignadores de memoria de Python (
PyPreConfig.allocator)Configurar la configuración regional LC_CTYPE (locale encoding)
Establecer el Python UTF-8 Mode (
PyPreConfig.utf8_mode)
La preconfiguración actual (tipo PyPreConfig) se almacena en _PyRuntime.preconfig.
Funciones para preinicializar Python:
-
PyStatus Py_PreInitialize(const PyPreConfig *preconfig)¶
Preinicializa Python desde la preconfiguración preconfig.
preconfig no debe ser
NULL.
-
PyStatus Py_PreInitializeFromBytesArgs(const PyPreConfig *preconfig, int argc, char *const *argv)¶
Preinicializa Python desde la preconfiguración preconfig.
Analice los argumentos de la línea de comando argv (cadenas de bytes) si
parse_argvde preconfig no es cero.preconfig no debe ser
NULL.
-
PyStatus Py_PreInitializeFromArgs(const PyPreConfig *preconfig, int argc, wchar_t *const *argv)¶
Preinicializa Python desde la preconfiguración preconfig.
Analice los argumentos de la línea de comando argv (cadenas anchas) si
parse_argvde preconfig no es cero.preconfig no debe ser
NULL.
La persona que llama es responsable de manejar las excepciones (error o salida) usando PyStatus_Exception() y Py_ExitStatusException().
Para Configuración de Python (PyPreConfig_InitPythonConfig()), si Python se inicializa con argumentos de línea de comando, los argumentos de la línea de comando también deben pasarse para preinicializar Python, ya que tienen un efecto en la preconfiguración como codificaciones. Por ejemplo, la opción de línea de comando -X utf8 habilita el Python UTF-8 Mode.
PyMem_SetAllocator() se puede llamar después de Py_PreInitialize() y antes Py_InitializeFromConfig() para instalar un asignador de memoria personalizado. Se puede llamar antes Py_PreInitialize() si PyPreConfig.allocator está configurado en PYMEM_ALLOCATOR_NOT_SET.
Las funciones de asignación de memoria de Python como PyMem_RawMalloc() no deben usarse antes de la preinicialización de Python, mientras que llamar directamente a malloc() y free() siempre es seguro. No se debe llamar a Py_DecodeLocale() antes de la preinicialización de Python.
Ejemplo usando la preinicialización para habilitar el Python 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 speaks UTF-8 */
Py_Initialize();
/* ... use Python API here ... */
Py_Finalize();
PyConfig¶
-
type PyConfig¶
Estructura que contiene la mayoría de los parámetros para configurar Python.
Cuando termine, se debe utilizar la función
PyConfig_Clear()para liberar la memoria de configuración.Métodos de estructura:
-
void PyConfig_InitPythonConfig(PyConfig *config)¶
Inicialice la configuración con la Configuración de Python.
-
void PyConfig_InitIsolatedConfig(PyConfig *config)¶
Inicialice la configuración con la Configuración Aislada.
-
PyStatus PyConfig_SetString(PyConfig *config, wchar_t *const *config_str, const wchar_t *str)¶
Copia la cadena de caracteres anchos str en
*config_str.Preinicializa Python si es necesario.
-
PyStatus PyConfig_SetBytesString(PyConfig *config, wchar_t *const *config_str, const char *str)¶
Decodifique str usando
Py_DecodeLocale()y establezca el resultado en*config_str.Preinicializa Python si es necesario.
-
PyStatus PyConfig_SetArgv(PyConfig *config, int argc, wchar_t *const *argv)¶
Configure los argumentos de la línea de comando (miembro
argvde config) de la lista argv de cadenas de caracteres anchas.Preinicializa Python si es necesario.
-
PyStatus PyConfig_SetBytesArgv(PyConfig *config, int argc, char *const *argv)¶
Establezca argumentos de línea de comando (miembro
argvde config) de la lista argv de cadenas de bytes. Decodifica bytes usandoPy_DecodeLocale().Preinicializa Python si es necesario.
-
PyStatus PyConfig_SetWideStringList(PyConfig *config, PyWideStringList *list, Py_ssize_t length, wchar_t **items)¶
Establece la lista de cadenas de caracteres anchas list a length y items.
Preinicializa Python si es necesario.
-
PyStatus PyConfig_Read(PyConfig *config)¶
Lee toda la configuración de Python.
Los campos que ya están inicializados no se modifican.
Los campos para la configuración de ruta ya no se calculan ni modifican al llamar a esta función, a partir de 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.Preinicializa Python si es necesario.
Distinto en la versión 3.10: Los argumentos
PyConfig.argvahora solo se analizan una vez,PyConfig.parse_argvse establece en2después de analizar los argumentos y los argumentos solo se analizan siPyConfig.parse_argves igual a1.Distinto en la versión 3.11:
PyConfig_Read()ya no calcula todas las rutas, por lo que los campos listados en Python Path Configuration ya no pueden ser actualizados hasta que se llame aPy_InitializeFromConfig().
La mayoría de los método
PyConfigpreinitializan Python si es necesario. En ese caso, la configuración de preinicialización de Python (PyPreConfig) se basa enPyConfig. Si se ajustan los campos de configuración que son comunes conPyPreConfig, deben establecerse antes de llamar a un métodoPyConfig: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).Quien llama de estos métodos es responsable de manejar las excepciones (error o salida) usando
PyStatus_Exception()yPy_ExitStatusException().Campos de estructura:
-
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.Configure
parse_argven1para analizarargvde la misma manera que Python normal analiza los argumentos de la línea de comandos de Python y luego quita los argumentos de Python deargv.Si
argvestá vacío, se agrega una cadena vacía para garantizar quesys.argvsiempre exista y nunca esté vacío.Valor predeterminado:
NULL.Consulte también el miembro
orig_argv.
-
int safe_path¶
Si es igual a cero,
Py_RunMain()agrega una ruta potencialmente insegura asys.pathal inicio:Si
argv[0]es igual aL"-m"(python -m module), añade el directorio de trabajo actual.If running a script (
python script.py), prepend the script’s directory. If it’s a symbolic link, resolve symbolic links.En caso contrario (
python -c codeandpython), añade una cadena vacía, que significa el directorio de trabajo actual.
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¶
-
Valor predeterminado:
NULL.Parte de la salida Python Path Configuration.
See also
PyConfig.exec_prefix.
-
wchar_t *base_executable¶
Ejecutable base de Python:
sys._base_executable.Establecido por la variable de entorno
__PYVENV_LAUNCHER__.Establecido desde
PyConfig.executablesiNULL.Valor predeterminado:
NULL.Parte de la salida Python Path Configuration.
See also
PyConfig.executable.
-
wchar_t *base_prefix¶
-
Valor predeterminado:
NULL.Parte de la salida Python Path Configuration.
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 siempre se abre en modo de búfer.
Predeterminado:
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.Incrementado por la opción de línea de comando
-b.Predeterminado:
0.
-
int warn_default_encoding¶
Si no es cero, emite una advertencia
EncodingWarningcuandoio.TextIOWrapperusa su codificación predeterminada. Consulte EncodingWarning opcional para obtener más detalles.Predeterminado:
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.Predeterminado:
1.Added in version 3.11.
-
wchar_t *check_hash_pycs_mode¶
Controla el comportamiento de validación de archivos
.pycbasados en hash: valor de la opción de línea de comando--check-hash-based-pycs.Valores válidos:
L"always": Calcula el hash el archivo fuente para invalidación independientemente del valor de la marca “check_source”.L"never": suponga que los pycs basados en hash siempre son válidos.L"default": El indicador “check_source” en pycs basados en hash determina la invalidación.
Predeterminado:
L"default".Consulte también PEP 552 «Pycs deterministas».
-
int configure_c_stdio¶
Si es distinto de cero, configure los flujos estándar de C:
En Windows, configure el modo binario (
O_BINARY) en stdin, stdout y stderr.Si
buffered_stdioes igual a cero, deshabilite el almacenamiento en búfer de los flujos stdin, stdout y stderr.Si
interactiveno es cero, habilite el almacenamiento en búfer de flujo en stdin y stdout (solo stdout en Windows).
Predeterminado:
1en la configuración de Python,0en la configuración aislada.
-
int dev_mode¶
Si es distinto de cero, habilita Modo de desarrollo de Python.
Set to
1by the-X devoption and thePYTHONDEVMODEenvironment variable.Por defecto:
-1en modo Python,0en modo aislado.
-
int dump_refs¶
Dump Python references?
Si no es cero, volcar todos los objetos que aún están vivos en la salida.
Establecido en
1por la variable de entornoPYTHONDUMPREFS.Needs a special build of Python with the
Py_TRACE_REFSmacro defined: see theconfigure --with-trace-refs option.Predeterminado:
0.
-
wchar_t *dump_refs_file¶
Filename where to dump Python references.
Set by the
PYTHONDUMPREFSFILEenvironment variable.Valor predeterminado:
NULL.Added in version 3.11.
-
wchar_t *exec_prefix¶
El prefijo de directorio específico del sitio donde se instalan los archivos Python dependientes de la plataforma:
sys.exec_prefix.Valor predeterminado:
NULL.Parte de la salida Python Path Configuration.
See also
PyConfig.base_exec_prefix.
-
wchar_t *executable¶
La ruta absoluta del binario ejecutable para el intérprete de Python:
sys.executable.Valor predeterminado:
NULL.Parte de la salida Python Path Configuration.
See also
PyConfig.base_executable.
-
int faulthandler¶
¿Habilitar administrador de fallas?
Si no es cero, llama a
faulthandler.enable()al inicio.Establecido en
1por-X faulthandlery la variable de entornoPYTHONFAULTHANDLER.Por defecto:
-1en modo Python,0en modo aislado.
-
wchar_t *filesystem_encoding¶
Codificación del sistema de archvios:
sys.getfilesystemencoding().En macOS, Android y VxWorks: use
"utf-8"de forma predeterminada.En Windows: utilice
"utf-8"de forma predeterminada o"mbcs"silegacy_windows_fs_encodingdePyPreConfigno es cero.Codificación predeterminada en otras plataformas:
"utf-8"siPyPreConfig.utf8_modees distinto de cero."ascii"if Python detects thatnl_langinfo(CODESET)announces the ASCII encoding, whereas thembstowcs()function decodes from a different encoding (usually Latin1)."utf-8"sinl_langinfo(CODESET)retorna una cadena vacía.De lo contrario, utilice el resultado locale encoding:
nl_langinfo(CODESET).
Al inicio de Python, el nombre de codificación se normaliza al nombre del códec de Python. Por ejemplo,
"ANSI_X3.4-1968"se reemplaza por"ascii".Consulte también el miembro
filesystem_errors.
-
wchar_t *filesystem_errors¶
Manejador de errores del sistema de archivos:
sys.getfilesystemencodeerrors().En Windows: utilice
"surrogatepass"de forma predeterminada o"replace"silegacy_windows_fs_encodingdePyPreConfigno es cero.En otras plataformas: utilice
"surrogateescape"de forma predeterminada.Controladores de errores admitidos:
"strict""surrogateescape""surrogatepass"(solo compatible con la codificación UTF-8)
Consulte también el miembro
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¶
Funciones de semillas aleatorias hash.
Si
use_hash_seedes cero, se elige una semilla al azar en el inicio de Python y se ignorahash_seed.Establecido por la variable de entorno
PYTHONHASHSEED.Valor predeterminado de use_hash_seed:
-1en modo Python,0en modo aislado.
-
wchar_t *home¶
Set the default Python «home» directory, that is, the location of the standard Python libraries (see
PYTHONHOME).Establecido por la variable de entorno
PYTHONHOME.Valor predeterminado:
NULL.Parte de la entrada Python Path Configuration.
-
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.Predeterminado:
0.Distinto en la versión 3.14: Added support for
import_time = 2
-
int inspect¶
Ingresa al modo interactivo después de ejecutar un script o un comando.
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.Incrementado por la opción de línea de comando
-i. Establecido en1si la variable de entornoPYTHONINSPECTno está vacía.Predeterminado:
0.
-
int install_signal_handlers¶
¿Instalar controladores de señales de Python?
Por defecto:
1en modo Python,0en modo aislado.
-
int interactive¶
If greater than
0, enable the interactive mode (REPL).Incrementado por la opción de línea de comando
-i.Predeterminado:
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 no importa
readlineni habilita la configuración predeterminada de readline en mensajes interactivos.
Set to
1by the-Icommand line option.Por defecto:
0en modo Python,1en modo aislado.See also the Isolated Configuration and
PyPreConfig.isolated.
-
int legacy_windows_stdio¶
If non-zero, use
io.FileIOinstead ofio._WindowsConsoleIOforsys.stdin,sys.stdoutandsys.stderr.Establecido en
1si la variable de entornoPYTHONLEGACYWINDOWSSTDIOestá establecida en una cadena no vacía.Solo disponible en Windows. La macro
#ifdef MS_WINDOWSse puede usar para el código específico de Windows.Predeterminado:
0.Consulte también PEP 528 (Cambiar la codificación de la consola de Windows a UTF-8).
-
int malloc_stats¶
Si no es cero, volcar las estadísticas en Asignador de memoria Python pymalloc en la salida.
Establecido en
1por la variable de entornoPYTHONMALLOCSTATS.La opción se ignora si Python es
configurado usando la opción --without-pymalloc.Predeterminado:
0.
-
wchar_t *platlibdir¶
Nombre del directorio de la biblioteca de la plataforma:
sys.platlibdir.Establecido por la variable de entorno
PYTHONPLATLIBDIR.Default: value of the
PLATLIBDIRmacro which is set by theconfigure --with-platlibdir option(default:"lib", or"DLLs"on Windows).Parte de la entrada Python Path Configuration.
Added in version 3.9.
Distinto en la versión 3.11: Esta macro se utiliza ahora en Windows para localizar los módulos de extensión de la biblioteca estándar, normalmente en
DLLs. Sin embargo, por compatibilidad, tenga en cuenta que este valor se ignora para cualquier disposición no estándar, incluyendo las construcciones dentro del árbol y los entornos virtuales.
-
wchar_t *pythonpath_env¶
Module search paths (
sys.path) as a string separated byDELIM(os.pathsep).Establecido por la variable de entorno
PYTHONPATH.Valor predeterminado:
NULL.Parte de la entrada Python Path Configuration.
-
PyWideStringList module_search_paths¶
-
int module_search_paths_set¶
Rutas de búsqueda del módulo:
sys.path.If
module_search_paths_setis equal to0,Py_InitializeFromConfig()will replacemodule_search_pathsand setsmodule_search_paths_setto1.Por defecto: lista vacía (
module_search_paths) y0(module_search_paths_set).Parte de la salida Python Path Configuration.
-
int optimization_level¶
Nivel de optimización de compilación:
0: Optimizador de mirilla, configure__debug__enTrue.1: Nivel 0, elimina las aserciones, establece__debug__enFalse.2: Nivel 1, elimina docstrings.
Incrementado por la opción de línea de comando
-O. Establecido en el valor de la variable de entornoPYTHONOPTIMIZE.Predeterminado:
0.
-
PyWideStringList orig_argv¶
La lista de los argumentos originales de la línea de comandos pasados al ejecutable de Python:
sys.orig_argv.Si la lista
orig_argvestá vacía yargvno es una lista que solo contiene una cadena vacía,PyConfig_Read()copiaargvenorig_argvantes de modificarargv(siparse_argvno es cero).Consulte también el miembro
argvy la funciónPy_GetArgcArgv().Predeterminado: lista vacía.
Added in version 3.10.
-
int parse_argv¶
¿Analizar los argumentos de la línea de comando?
Si es igual a
1, analizaargvde la misma forma que Python normal analiza argumentos de línea de comando y elimina los argumentos de Python deargv.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.Por defecto:
1en modo Python,0en modo aislado.Distinto en la versión 3.10: Los argumentos
PyConfig.argvahora solo se analizan siPyConfig.parse_argves igual a1.
-
int parser_debug¶
Parser debug mode. If greater than
0, turn on parser debugging output (for expert only, depending on compilation options).Incrementado por la opción de línea de comando
-d. Establecido en el valor de la variable de entornoPYTHONDEBUG.Needs a debug build of Python (the
Py_DEBUGmacro must be defined).Predeterminado:
0.
-
int pathconfig_warnings¶
If non-zero, calculation of path configuration is allowed to log warnings into
stderr. If equals to0, suppress these warnings.Por defecto:
1en modo Python,0en modo aislado.Parte de la entrada Python Path Configuration.
Distinto en la versión 3.11: Ahora también se aplica en Windows.
-
wchar_t *prefix¶
El prefijo de directorio específico del sitio donde se instalan los archivos Python independientes de la plataforma:
sys.prefix.Valor predeterminado:
NULL.Parte de la salida Python Path Configuration.
See also
PyConfig.base_prefix.
-
wchar_t *program_name¶
Nombre del programa utilizado para inicializar
executabley en los primeros mensajes de error durante la inicialización de Python.En macOS, usa la variable de entorno
PYTHONEXECUTABLEsi está configurada.Si se define la macro
WITH_NEXT_FRAMEWORK, utiliza la variable de entorno__PYVENV_LAUNCHER__si está configurada.Utiliza
argv[0]deargvsi está disponible y no está vacío.De lo contrario, utiliza
L"python"en Windows oL"python3"en otras plataformas.
Valor predeterminado:
NULL.Parte de la entrada Python Path Configuration.
-
wchar_t *pycache_prefix¶
Directorio donde se escriben los archivos
.pycalmacenados en caché:sys.pycache_prefix.Set by the
-X pycache_prefix=PATHcommand line option and thePYTHONPYCACHEPREFIXenvironment variable. The command-line option takes precedence.Si
NULL,sys.pycache_prefixes establecido aNone.Valor predeterminado:
NULL.
-
int quiet¶
Quiet mode. If greater than
0, don’t display the copyright and version at Python startup in interactive mode.Incrementado por la opción de línea de comando
-q.Predeterminado:
0.
-
wchar_t *run_command¶
Valor de la opción de línea de comando
-c.Usado por
Py_RunMain().Valor predeterminado:
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.Valor predeterminado:
NULL.
-
wchar_t *run_module¶
Valor de la opción de línea de comando
-m.Usado por
Py_RunMain().Valor predeterminado:
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).Valor predeterminado:
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).Predeterminado:
0.
-
int site_import¶
¿Importar el módulo
siteal inicio?Si es igual a cero, desactive la importación del sitio del módulo y las manipulaciones dependientes del sitio de
sys.pathque conlleva.También deshabilite estas manipulaciones si el módulo
sitese importa explícitamente más tarde (llame asite.main()si desea que se activen).Establecido en
0mediante la opción de línea de comando-S.sys.flags.no_siteis set to the inverted value ofsite_import.Predeterminado:
1.
-
int skip_source_first_line¶
Si no es cero, omita la primera línea de la fuente
PyConfig.run_filename.Permite el uso de formas de
#!cmdque no son Unix. Esto está destinado únicamente a un truco específico de DOS.Establecido en
1mediante la opción de línea de comando-x.Predeterminado:
0.
-
wchar_t *stdio_encoding¶
-
wchar_t *stdio_errors¶
Codificación y errores de codificación de
sys.stdin,sys.stdoutysys.stderr(perosys.stderrsiempre usa el controlador de errores"backslashreplace").Utilice la variable de entorno
PYTHONIOENCODINGsi no está vacía.Codificación predeterminada:
"UTF-8"siPyPreConfig.utf8_modees distinto de cero.De lo contrario, usa el locale encoding.
Manejador de errores predeterminado:
En Windows: use
"surrogateescape"."surrogateescape"siPyPreConfig.utf8_modeno es cero o si la configuración regional LC_CTYPE es «C» o «POSIX»."strict"de lo contrario.
See also
PyConfig.legacy_windows_stdio.
-
int tracemalloc¶
¿Habilitar tracemalloc?
Si no es cero, llama a
tracemalloc.start()al inicio.Establecido por la opción de línea de comando
-X tracemalloc=Ny por la variable de entornoPYTHONTRACEMALLOC.Por defecto:
-1en modo Python,0en modo aislado.
-
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.Ver también
See Soporte de Python para el perfilador perf de Linux for more information.
Added in version 3.12.
-
wchar_t *stdlib_dir¶
Directory of the Python standard library.
Valor predeterminado:
NULL.Added in version 3.11.
-
int use_environment¶
¿Utiliza variables de entorno?
Si es igual a cero, ignora las variables de entorno.
Set to
0by the-Eenvironment variable.Predeterminado:
1en la configuración de Python y0en la configuración aislada.
-
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¶
Si es distinto de cero, agregue el directorio del sitio del usuario a
sys.path.Establecido en
0por las opciones de línea de comando-sy-I.Establecido en
0por la variable de entornoPYTHONNOUSERSITE.Por defecto:
1en modo Python,0en modo aislado.
-
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.Incrementado por la opción de línea de comando
-v.Set by the
PYTHONVERBOSEenvironment variable value.Predeterminado:
0.
-
PyWideStringList warnoptions¶
Opciones del módulo
warningspara crear filtros de advertencias, de menor a mayor prioridad:sys.warnoptions.El módulo
warningsagregasys.warnoptionsen el orden inverso: el último elementoPyConfig.warnoptionsse convierte en el primer elemento dewarnings.filtersque es verificado primero (máxima prioridad).Las opciones de la línea de comando
-Wagregan su valor awarnoptions, se puede usar varias veces.La variable de entorno
PYTHONWARNINGStambién se puede utilizar para agregar opciones de advertencia. Se pueden especificar varias opciones, separadas por comas (,).Predeterminado: lista vacía.
-
int write_bytecode¶
If equal to
0, Python won’t try to write.pycfiles on the import of source modules.Establecido en
0por la opción de línea de comando-By la variable de entornoPYTHONDONTWRITEBYTECODE.sys.dont_write_bytecodese inicializa al valor invertido dewrite_bytecode.Predeterminado:
1.
-
PyWideStringList xoptions¶
Valores de las opciones de la línea de comando
-X:sys._xoptions.Predeterminado: lista vacía.
-
int _pystats¶
If non-zero, write performance statistics at Python exit.
Need a special build with the
Py_STATSmacro: see--enable-pystats.Predeterminado:
0.
-
void PyConfig_InitPythonConfig(PyConfig *config)¶
Si parse_argv no es cero, los argumentos de argv se analizan de la misma forma que Python normal analiza argumentos de línea de comando, y los argumentos de Python se eliminan de argv.
Las opciones de xoptions se analizan para establecer otras opciones: consulte la opción de línea de comando -X.
Distinto en la versión 3.9: El campo show_alloc_count fue removido.
Inicialización con PyConfig¶
Initializing the interpreter from a populated configuration struct is handled
by calling Py_InitializeFromConfig().
La persona que llama es responsable de manejar las excepciones (error o salida) usando PyStatus_Exception() y Py_ExitStatusException().
Si se utilizan PyImport_FrozenModules(), PyImport_AppendInittab() o PyImport_ExtendInittab(), deben establecerse o llamarse después de la preinicialización de Python y antes de la inicialización de Python. Si Python se inicializa varias veces, se debe llamar a PyImport_AppendInittab() o PyImport_ExtendInittab() antes de cada inicialización de Python.
La configuración actual (tipo PyConfig) se almacena en PyInterpreterState.config.
Ejemplo de configuración del nombre del programa:
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;
}
Configuración aislada¶
PyPreConfig_InitIsolatedConfig() y las funciones PyConfig_InitIsolatedConfig() crean una configuración para aislar Python del sistema. Por ejemplo, para incrustar Python en una aplicación.
This configuration ignores global configuration variables, environment
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.
Los archivos de configuración se siguen utilizando con esta configuración para determinar las rutas que no se especifican. Asegúrese de que se especifica PyConfig.home para evitar que se calcule la configuración de la ruta por defecto.
Configuración de Python¶
PyPreConfig_InitPythonConfig() y las funciones PyConfig_InitPythonConfig() crean una configuración para construir un Python personalizado que se comporta como el Python normal.
Las variables de entorno y los argumentos de la línea de comandos se utilizan para configurar Python, mientras que las variables de configuración global se ignoran.
Esta función habilita la coerción de configuración regional C (PEP 538) y Python UTF-8 Mode (PEP 540) según la configuración regional LC_CTYPE, las variables de entorno PYTHONUTF8 y PYTHONCOERCECLOCALE.
Configuración de la ruta de Python¶
PyConfig contiene múltiples campos para la configuración de ruta:
Entradas de configuración de ruta:
directorio de trabajo actual: para obtener rutas absolutas
Variable de entorno
PATHpara obtener la ruta completa del programa (dePyConfig.program_name)Variable de entorno
__PYVENV_LAUNCHER__(Solo Windows) Rutas de aplicación en el registro en «SoftwarePythonPythonCoreX.YPythonPath» de HKEY_CURRENT_USER y HKEY_LOCAL_MACHINE (donde X.Y es la versión de Python).
Campos de salida de configuración de ruta:
Si al menos un «campo de salida» no está establecido, Python calcula la configuración de la ruta para rellenar los campos no establecidos. Si module_search_paths_set es igual a 0, module_search_paths se anula y module_search_paths_set se establece en 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).
Si base_prefix o los campos base_exec_prefix no están establecidos, heredan su valor de prefix y exec_prefix respectivamente.
Py_RunMain() y Py_Main() modifican sys.path:
Si
run_filenameestá configurado y es un directorio que contiene un script__main__.py, antepongarun_filenameasys.path.Si
isolatedes cero:Si
run_moduleestá configurado, anteponga el directorio actual asys.path. No haga nada si el directorio actual no se puede leer.Si
run_filenameestá configurado, anteponga el directorio del nombre del archivo asys.path.De lo contrario, anteponga una cadena de caracteres vacía a
sys.path.
Si site_import no es cero, sys.path puede ser modificado por el módulo site. Si user_site_directory no es cero y el directorio del paquete del sitio del usuario existe, el módulo site agrega el directorio del paquete del sitio del usuario a sys.path.
La configuración de ruta utiliza los siguientes archivos de configuración:
pyvenv.cfgarchivo
._pth(ej:python._pth)pybuilddir.txt(sólo Unix)
Si un archivo ._pth está presente:
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.
Distinto en la versión 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)¶
Obtiene los argumentos originales de la línea de comandos, antes de que Python los modificara.
Ver también el miembro
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.