13518219792

建站动态

根据您的个性需求进行定制 先人一步 抢占小程序红利时代

创新互联Python教程:Python初始化配置

python初始化配置

3.8 新版功能.

创新互联是一家专业提供千山企业网站建设,专注与成都做网站、成都网站建设、H5高端网站建设、小程序制作等业务。10年已为千山众多企业、政府机构等服务。创新互联专业的建站公司优惠进行中。

Python 可以使用 Py_InitializeFromConfig() 和 PyConfig 结构体来初始化。 它可以使用 Py_PreInitialize() 和 PyPreConfig 结构体来预初始化。

有两种配置方式:

Py_RunMain() 函数可被用来编写定制的 Python 程序。

参见 Initialization, Finalization, and Threads.

参见

PEP 587 “Python 初始化配置”.

示例

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

 
 
 
 
  1. int main(int argc, char **argv)
  2. {
  3. PyStatus status;
  4. PyConfig config;
  5. PyConfig_InitPythonConfig(&config);
  6. config.isolated = 1;
  7. /* Decode command line arguments.
  8. Implicitly preinitialize Python (in isolated mode). */
  9. status = PyConfig_SetBytesArgv(&config, argc, argv);
  10. if (PyStatus_Exception(status)) {
  11. goto exception;
  12. }
  13. status = Py_InitializeFromConfig(&config);
  14. if (PyStatus_Exception(status)) {
  15. goto exception;
  16. }
  17. PyConfig_Clear(&config);
  18. return Py_RunMain();
  19. exception:
  20. PyConfig_Clear(&config);
  21. if (PyStatus_IsExit(status)) {
  22. return status.exitcode;
  23. }
  24. /* Display the error message and exit the process with
  25. non-zero exit code */
  26. Py_ExitStatusException(status);
  27. }

PyWideStringList

type PyWideStringList

wchar_t* 字符串组成的列表。

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

方法

Structure fields:

PyStatus

type PyStatus

Structure to store an initialization function status: success, error or exit.

For an error, it can store the C function name which created the error.

Structure fields:

Functions to create a status:

Functions to handle a status:

备注

Internally, Python uses macros which set PyStatus.func, whereas functions to create a status set func to NULL.

示例:

 
 
 
 
  1. PyStatus alloc(void **ptr, size_t size)
  2. {
  3. *ptr = PyMem_RawMalloc(size);
  4. if (*ptr == NULL) {
  5. return PyStatus_NoMemory();
  6. }
  7. return PyStatus_Ok();
  8. }
  9. int main(int argc, char **argv)
  10. {
  11. void *ptr;
  12. PyStatus status = alloc(&ptr, 16);
  13. if (PyStatus_Exception(status)) {
  14. Py_ExitStatusException(status);
  15. }
  16. PyMem_Free(ptr);
  17. return 0;
  18. }

PyPreConfig

type PyPreConfig

Structure used to preinitialize Python.

Function to initialize a preconfiguration:

Structure fields:

Preinitialize Python with PyPreConfig

The preinitialization of Python:

The current preconfiguration (PyPreConfig type) is stored in _PyRuntime.preconfig.

Functions to preinitialize Python:

PyStatus Py_PreInitialize(const PyPreConfig *preconfig)

Preinitialize Python from preconfig preconfiguration.

preconfig must not be NULL.

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

Preinitialize Python from preconfig preconfiguration.

Parse argv command line arguments (bytes strings) if parse_argv of preconfig is non-zero.

preconfig must not be NULL.

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

Preinitialize Python from preconfig preconfiguration.

Parse argv command line arguments (wide strings) if parse_argv of preconfig is non-zero.

preconfig must not be NULL.

The caller is responsible to handle exceptions (error or exit) using PyStatus_Exception() and Py_ExitStatusException().

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

PyMem_SetAllocator() can be called after Py_PreInitialize() and before Py_InitializeFromConfig() to install a custom memory allocator. It can be called before Py_PreInitialize() if PyPreConfig.allocator is set to PYMEM_ALLOCATOR_NOT_SET.

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

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

 
 
 
 
  1. PyStatus status;
  2. PyPreConfig preconfig;
  3. PyPreConfig_InitPythonConfig(&preconfig);
  4. preconfig.utf8_mode = 1;
  5. status = Py_PreInitialize(&preconfig);
  6. if (PyStatus_Exception(status)) {
  7. Py_ExitStatusException(status);
  8. }
  9. /* at this point, Python speaks UTF-8 */
  10. Py_Initialize();
  11. /* ... use Python API here ... */
  12. Py_Finalize();

PyConfig

type PyConfig

Structure containing most parameters to configure Python.

When done, the PyConfig_Clear() function must be used to release the configuration memory.

Structure methods:

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

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

The caller of these methods is responsible to handle exceptions (error or exit) using PyStatus_Exception() and Py_ExitStatusException().

Structure fields:

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

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

在 3.9 版更改: The show_alloc_count field has been removed.

Initialization with PyConfig

Function to initialize Python:

PyStatus Py_InitializeFromConfig(const PyConfig *config)

Initialize Python from config configuration.

The caller is responsible to handle exceptions (error or exit) using PyStatus_Exception() and Py_ExitStatusException().

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

The current configuration (PyConfig type) is stored in PyInterpreterState.config.

Example setting the program name:

 
 
 
 
  1. void init_python(void)
  2. {
  3. PyStatus status;
  4. PyConfig config;
  5. PyConfig_InitPythonConfig(&config);
  6. /* Set the program name. Implicitly preinitialize Python. */
  7. status = PyConfig_SetString(&config, &config.program_name,
  8. L"/path/to/my_program");
  9. if (PyStatus_Exception(status)) {
  10. goto exception;
  11. }
  12. status = Py_InitializeFromConfig(&config);
  13. if (PyStatus_Exception(status)) {
  14. goto exception;
  15. }
  16. PyConfig_Clear(&config);
  17. return;
  18. exception:
  19. PyConfig_Clear(&config);
  20. Py_ExitStatusException(status);
  21. }

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:

 
 
 
 
  1. PyStatus init_python(const char *program_name)
  2. {
  3. PyStatus status;
  4. PyConfig config;
  5. PyConfig_InitPythonConfig(&config);
  6. /* Set the program name before reading the configuration
  7. (decode byte string from the locale encoding).
  8. Implicitly preinitialize Python. */
  9. status = PyConfig_SetBytesString(&config, &config.program_name,
  10. program_name);
  11. if (PyStatus_Exception(status)) {
  12. goto done;
  13. }
  14. /* Read all configuration at once */
  15. status = PyConfig_Read(&config);
  16. if (PyStatus_Exception(status)) {
  17. goto done;
  18. }
  19. /* Specify sys.path explicitly */
  20. /* If you want to modify the default set of paths, finish
  21. initialization first and then use PySys_GetObject("path") */
  22. config.module_search_paths_set = 1;
  23. status = PyWideStringList_Append(&config.module_search_paths,
  24. L"/path/to/stdlib");
  25. if (PyStatus_Exception(status)) {
  26. goto done;
  27. }
  28. status = PyWideStringList_Append(&config.module_search_paths,
  29. L"/path/to/more/modules");
  30. if (PyStatus_Exception(status)) {
  31. goto done;
  32. }
  33. /* Override executable computed by PyConfig_Read() */
  34. status = PyConfig_SetString(&config, &config.executable,
  35. L"/path/to/my_executable");
  36. if (PyStatus_Exception(status)) {
  37. goto done;
  38. }
  39. status = Py_InitializeFromConfig(&config);
  40. done:
  41. PyConfig_Clear(&config);
  42. return status;
  43. }

Isolated Configuration

PyPreConfig_InitIsolatedConfig() and PyConfig_InitIsolatedConfig() functions create a configuration to isolate Python from the system. For example, to embed Python into an application.

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.

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 Configuration

PyPreConfig_InitPythonConfig() and PyConfig_InitPythonConfig() functions create a configuration to build a customized Python which behaves as the regular Python.

Environments variables and command line arguments are used to configure Python, whereas global configuration variables are ignored.

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

Python Path Configuration

PyConfig contains multiple fields for the path configuration:

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).

If base_prefix or base_exec_prefix fields are not set, they inherit their value from prefix and exec_prefix respectively.

Py_RunMain() and Py_Main() modify sys.path:

If site_import is non-zero, sys.path can be modified by the site module. If user_site_directory is non-zero and the user’s site-package directory exists, the site module appends the user’s site-package directory to sys.path.

The following configuration files are used by the path configuration:

If a ._pth file is present:

The __PYVENV_LAUNCHER__ environment variable is used to set PyConfig.base_executable

Py_RunMain()

int Py_RunMain(void)

Execute the command (PyConfig.run_command), the script (PyConfig.run_filename) or the module (PyConfig.run_module) specified on the command line or in the configuration.

By default and when if -i option is used, run the REPL.

Finally, finalizes Python and returns an exit status that can be passed to the exit() function.

See Python Configuration for an example of customized Python always running in isolated mode using Py_RunMain().

Py_GetArgcArgv()

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

Get the original command line arguments, before Python modified them.

See also PyConfig.orig_argv member.

Multi-Phase Initialization Private Provisional API

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

私有临时API:

PyStatus _Py_InitializeMain(void)

Move to the “Main” initialization phase, finish the Python initialization.

No module is imported during the “Core” phase and the importlib module is not configured: the Path Configuration is only applied during the “Main” phase. It may allow to customize Python in Python to override or tune the Path Configuration, maybe install a custom sys.meta_path importer or an import hook, etc.

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

The “Core” phase is not properly defined: what should be and what should not be available at this phase is not specified yet. The API is marked as private and provisional: the API can be modified or even be removed anytime until a proper public API is designed.

Example running Python code between “Core” and “Main” initialization phases:

 
 
 
 
  1. void init_python(void)
  2. {
  3. PyStatus status;
  4. PyConfig config;
  5. PyConfig_InitPythonConfig(&config);
  6. config._init_main = 0;
  7. /* ... customize 'config' configuration ... */
  8. status = Py_InitializeFromConfig(&config);
  9. PyConfig_Clear(&config);
  10. if (PyStatus_Exception(status)) {
  11. Py_ExitStatusException(status);
  12. }
  13. /* Use sys.stderr because sys.stdout is only created
  14. by _Py_InitializeMain() */
  15. int res = PyRun_SimpleString(
  16. "import sys; "
  17. "print('Run Python code before _Py_InitializeMain', "
  18. "file=sys.stderr)");
  19. if (res < 0) {
  20. exit(1);
  21. }
  22. /* ... put more configuration code here ... */
  23. status = _Py_InitializeMain();
  24. if (PyStatus_Exception(status)) {
  25. Py_ExitStatusException(status);
  26. }
  27. }

文章标题:创新互联Python教程:Python初始化配置
URL标题:http://cdbrznjsb.com/article/djdshig.html

其他资讯

让你的专属顾问为你服务