1.. highlight:: c 2 3.. _init-config: 4 5*********************************** 6Python Initialization Configuration 7*********************************** 8 9.. versionadded:: 3.8 10 11Structures: 12 13* :c:type:`PyConfig` 14* :c:type:`PyPreConfig` 15* :c:type:`PyStatus` 16* :c:type:`PyWideStringList` 17 18Functions: 19 20* :c:func:`PyConfig_Clear` 21* :c:func:`PyConfig_InitIsolatedConfig` 22* :c:func:`PyConfig_InitPythonConfig` 23* :c:func:`PyConfig_Read` 24* :c:func:`PyConfig_SetArgv` 25* :c:func:`PyConfig_SetBytesArgv` 26* :c:func:`PyConfig_SetBytesString` 27* :c:func:`PyConfig_SetString` 28* :c:func:`PyConfig_SetWideStringList` 29* :c:func:`PyPreConfig_InitIsolatedConfig` 30* :c:func:`PyPreConfig_InitPythonConfig` 31* :c:func:`PyStatus_Error` 32* :c:func:`PyStatus_Exception` 33* :c:func:`PyStatus_Exit` 34* :c:func:`PyStatus_IsError` 35* :c:func:`PyStatus_IsExit` 36* :c:func:`PyStatus_NoMemory` 37* :c:func:`PyStatus_Ok` 38* :c:func:`PyWideStringList_Append` 39* :c:func:`PyWideStringList_Insert` 40* :c:func:`Py_ExitStatusException` 41* :c:func:`Py_InitializeFromConfig` 42* :c:func:`Py_PreInitialize` 43* :c:func:`Py_PreInitializeFromArgs` 44* :c:func:`Py_PreInitializeFromBytesArgs` 45* :c:func:`Py_RunMain` 46* :c:func:`Py_GetArgcArgv` 47 48The preconfiguration (``PyPreConfig`` type) is stored in 49``_PyRuntime.preconfig`` and the configuration (``PyConfig`` type) is stored in 50``PyInterpreterState.config``. 51 52See also :ref:`Initialization, Finalization, and Threads <initialization>`. 53 54.. seealso:: 55 :pep:`587` "Python Initialization Configuration". 56 57 58PyWideStringList 59---------------- 60 61.. c:type:: PyWideStringList 62 63 List of ``wchar_t*`` strings. 64 65 If *length* is non-zero, *items* must be non-``NULL`` and all strings must be 66 non-``NULL``. 67 68 Methods: 69 70 .. c:function:: PyStatus PyWideStringList_Append(PyWideStringList *list, const wchar_t *item) 71 72 Append *item* to *list*. 73 74 Python must be preinitialized to call this function. 75 76 .. c:function:: PyStatus PyWideStringList_Insert(PyWideStringList *list, Py_ssize_t index, const wchar_t *item) 77 78 Insert *item* into *list* at *index*. 79 80 If *index* is greater than or equal to *list* length, append *item* to 81 *list*. 82 83 *index* must be greater than or equal to 0. 84 85 Python must be preinitialized to call this function. 86 87 Structure fields: 88 89 .. c:member:: Py_ssize_t length 90 91 List length. 92 93 .. c:member:: wchar_t** items 94 95 List items. 96 97PyStatus 98-------- 99 100.. c:type:: PyStatus 101 102 Structure to store an initialization function status: success, error 103 or exit. 104 105 For an error, it can store the C function name which created the error. 106 107 Structure fields: 108 109 .. c:member:: int exitcode 110 111 Exit code. Argument passed to ``exit()``. 112 113 .. c:member:: const char *err_msg 114 115 Error message. 116 117 .. c:member:: const char *func 118 119 Name of the function which created an error, can be ``NULL``. 120 121 Functions to create a status: 122 123 .. c:function:: PyStatus PyStatus_Ok(void) 124 125 Success. 126 127 .. c:function:: PyStatus PyStatus_Error(const char *err_msg) 128 129 Initialization error with a message. 130 131 .. c:function:: PyStatus PyStatus_NoMemory(void) 132 133 Memory allocation failure (out of memory). 134 135 .. c:function:: PyStatus PyStatus_Exit(int exitcode) 136 137 Exit Python with the specified exit code. 138 139 Functions to handle a status: 140 141 .. c:function:: int PyStatus_Exception(PyStatus status) 142 143 Is the status an error or an exit? If true, the exception must be 144 handled; by calling :c:func:`Py_ExitStatusException` for example. 145 146 .. c:function:: int PyStatus_IsError(PyStatus status) 147 148 Is the result an error? 149 150 .. c:function:: int PyStatus_IsExit(PyStatus status) 151 152 Is the result an exit? 153 154 .. c:function:: void Py_ExitStatusException(PyStatus status) 155 156 Call ``exit(exitcode)`` if *status* is an exit. Print the error 157 message and exit with a non-zero exit code if *status* is an error. Must 158 only be called if ``PyStatus_Exception(status)`` is non-zero. 159 160.. note:: 161 Internally, Python uses macros which set ``PyStatus.func``, 162 whereas functions to create a status set ``func`` to ``NULL``. 163 164Example:: 165 166 PyStatus alloc(void **ptr, size_t size) 167 { 168 *ptr = PyMem_RawMalloc(size); 169 if (*ptr == NULL) { 170 return PyStatus_NoMemory(); 171 } 172 return PyStatus_Ok(); 173 } 174 175 int main(int argc, char **argv) 176 { 177 void *ptr; 178 PyStatus status = alloc(&ptr, 16); 179 if (PyStatus_Exception(status)) { 180 Py_ExitStatusException(status); 181 } 182 PyMem_Free(ptr); 183 return 0; 184 } 185 186 187PyPreConfig 188----------- 189 190.. c:type:: PyPreConfig 191 192 Structure used to preinitialize Python: 193 194 * Set the Python memory allocator 195 * Configure the LC_CTYPE locale 196 * Set the UTF-8 mode 197 198 Function to initialize a preconfiguration: 199 200 .. c:function:: void PyPreConfig_InitPythonConfig(PyPreConfig *preconfig) 201 202 Initialize the preconfiguration with :ref:`Python Configuration 203 <init-python-config>`. 204 205 .. c:function:: void PyPreConfig_InitIsolatedConfig(PyPreConfig *preconfig) 206 207 Initialize the preconfiguration with :ref:`Isolated Configuration 208 <init-isolated-conf>`. 209 210 Structure fields: 211 212 .. c:member:: int allocator 213 214 Name of the memory allocator: 215 216 * ``PYMEM_ALLOCATOR_NOT_SET`` (``0``): don't change memory allocators 217 (use defaults) 218 * ``PYMEM_ALLOCATOR_DEFAULT`` (``1``): default memory allocators 219 * ``PYMEM_ALLOCATOR_DEBUG`` (``2``): default memory allocators with 220 debug hooks 221 * ``PYMEM_ALLOCATOR_MALLOC`` (``3``): force usage of ``malloc()`` 222 * ``PYMEM_ALLOCATOR_MALLOC_DEBUG`` (``4``): force usage of 223 ``malloc()`` with debug hooks 224 * ``PYMEM_ALLOCATOR_PYMALLOC`` (``5``): :ref:`Python pymalloc memory 225 allocator <pymalloc>` 226 * ``PYMEM_ALLOCATOR_PYMALLOC_DEBUG`` (``6``): :ref:`Python pymalloc 227 memory allocator <pymalloc>` with debug hooks 228 229 ``PYMEM_ALLOCATOR_PYMALLOC`` and ``PYMEM_ALLOCATOR_PYMALLOC_DEBUG`` 230 are not supported if Python is configured using ``--without-pymalloc`` 231 232 See :ref:`Memory Management <memory>`. 233 234 .. c:member:: int configure_locale 235 236 Set the LC_CTYPE locale to the user preferred locale? If equals to 0, set 237 :c:member:`coerce_c_locale` and :c:member:`coerce_c_locale_warn` to 0. 238 239 .. c:member:: int coerce_c_locale 240 241 If equals to 2, coerce the C locale; if equals to 1, read the LC_CTYPE 242 locale to decide if it should be coerced. 243 244 .. c:member:: int coerce_c_locale_warn 245 246 If non-zero, emit a warning if the C locale is coerced. 247 248 .. c:member:: int dev_mode 249 250 See :c:member:`PyConfig.dev_mode`. 251 252 .. c:member:: int isolated 253 254 See :c:member:`PyConfig.isolated`. 255 256 .. c:member:: int legacy_windows_fs_encoding (Windows only) 257 258 If non-zero, disable UTF-8 Mode, set the Python filesystem encoding to 259 ``mbcs``, set the filesystem error handler to ``replace``. 260 261 Only available on Windows. ``#ifdef MS_WINDOWS`` macro can be used for 262 Windows specific code. 263 264 .. c:member:: int parse_argv 265 266 If non-zero, :c:func:`Py_PreInitializeFromArgs` and 267 :c:func:`Py_PreInitializeFromBytesArgs` parse their ``argv`` argument the 268 same way the regular Python parses command line arguments: see 269 :ref:`Command Line Arguments <using-on-cmdline>`. 270 271 .. c:member:: int use_environment 272 273 See :c:member:`PyConfig.use_environment`. 274 275 .. c:member:: int utf8_mode 276 277 If non-zero, enable the UTF-8 mode. 278 279Preinitialization with PyPreConfig 280---------------------------------- 281 282Functions to preinitialize Python: 283 284.. c:function:: PyStatus Py_PreInitialize(const PyPreConfig *preconfig) 285 286 Preinitialize Python from *preconfig* preconfiguration. 287 288.. c:function:: PyStatus Py_PreInitializeFromBytesArgs(const PyPreConfig *preconfig, int argc, char * const *argv) 289 290 Preinitialize Python from *preconfig* preconfiguration and command line 291 arguments (bytes strings). 292 293.. c:function:: PyStatus Py_PreInitializeFromArgs(const PyPreConfig *preconfig, int argc, wchar_t * const * argv) 294 295 Preinitialize Python from *preconfig* preconfiguration and command line 296 arguments (wide strings). 297 298The caller is responsible to handle exceptions (error or exit) using 299:c:func:`PyStatus_Exception` and :c:func:`Py_ExitStatusException`. 300 301For :ref:`Python Configuration <init-python-config>` 302(:c:func:`PyPreConfig_InitPythonConfig`), if Python is initialized with 303command line arguments, the command line arguments must also be passed to 304preinitialize Python, since they have an effect on the pre-configuration 305like encodings. For example, the :option:`-X utf8 <-X>` command line option 306enables the UTF-8 Mode. 307 308``PyMem_SetAllocator()`` can be called after :c:func:`Py_PreInitialize` and 309before :c:func:`Py_InitializeFromConfig` to install a custom memory allocator. 310It can be called before :c:func:`Py_PreInitialize` if 311:c:member:`PyPreConfig.allocator` is set to ``PYMEM_ALLOCATOR_NOT_SET``. 312 313Python memory allocation functions like :c:func:`PyMem_RawMalloc` must not be 314used before Python preinitialization, whereas calling directly ``malloc()`` and 315``free()`` is always safe. :c:func:`Py_DecodeLocale` must not be called before 316the preinitialization. 317 318Example using the preinitialization to enable the UTF-8 Mode:: 319 320 PyStatus status; 321 PyPreConfig preconfig; 322 PyPreConfig_InitPythonConfig(&preconfig); 323 324 preconfig.utf8_mode = 1; 325 326 status = Py_PreInitialize(&preconfig); 327 if (PyStatus_Exception(status)) { 328 Py_ExitStatusException(status); 329 } 330 331 /* at this point, Python will speak UTF-8 */ 332 333 Py_Initialize(); 334 /* ... use Python API here ... */ 335 Py_Finalize(); 336 337 338PyConfig 339-------- 340 341.. c:type:: PyConfig 342 343 Structure containing most parameters to configure Python. 344 345 Structure methods: 346 347 .. c:function:: void PyConfig_InitPythonConfig(PyConfig *config) 348 349 Initialize configuration with :ref:`Python Configuration 350 <init-python-config>`. 351 352 .. c:function:: void PyConfig_InitIsolatedConfig(PyConfig *config) 353 354 Initialize configuration with :ref:`Isolated Configuration 355 <init-isolated-conf>`. 356 357 .. c:function:: PyStatus PyConfig_SetString(PyConfig *config, wchar_t * const *config_str, const wchar_t *str) 358 359 Copy the wide character string *str* into ``*config_str``. 360 361 Preinitialize Python if needed. 362 363 .. c:function:: PyStatus PyConfig_SetBytesString(PyConfig *config, wchar_t * const *config_str, const char *str) 364 365 Decode *str* using ``Py_DecodeLocale()`` and set the result into ``*config_str``. 366 367 Preinitialize Python if needed. 368 369 .. c:function:: PyStatus PyConfig_SetArgv(PyConfig *config, int argc, wchar_t * const *argv) 370 371 Set command line arguments from wide character strings. 372 373 Preinitialize Python if needed. 374 375 .. c:function:: PyStatus PyConfig_SetBytesArgv(PyConfig *config, int argc, char * const *argv) 376 377 Set command line arguments: decode bytes using :c:func:`Py_DecodeLocale`. 378 379 Preinitialize Python if needed. 380 381 .. c:function:: PyStatus PyConfig_SetWideStringList(PyConfig *config, PyWideStringList *list, Py_ssize_t length, wchar_t **items) 382 383 Set the list of wide strings *list* to *length* and *items*. 384 385 Preinitialize Python if needed. 386 387 .. c:function:: PyStatus PyConfig_Read(PyConfig *config) 388 389 Read all Python configuration. 390 391 Fields which are already initialized are left unchanged. 392 393 Preinitialize Python if needed. 394 395 .. c:function:: void PyConfig_Clear(PyConfig *config) 396 397 Release configuration memory. 398 399 Most ``PyConfig`` methods preinitialize Python if needed. In that case, the 400 Python preinitialization configuration in based on the :c:type:`PyConfig`. 401 If configuration fields which are in common with :c:type:`PyPreConfig` are 402 tuned, they must be set before calling a :c:type:`PyConfig` method: 403 404 * :c:member:`~PyConfig.dev_mode` 405 * :c:member:`~PyConfig.isolated` 406 * :c:member:`~PyConfig.parse_argv` 407 * :c:member:`~PyConfig.use_environment` 408 409 Moreover, if :c:func:`PyConfig_SetArgv` or :c:func:`PyConfig_SetBytesArgv` 410 is used, this method must be called first, before other methods, since the 411 preinitialization configuration depends on command line arguments (if 412 :c:member:`parse_argv` is non-zero). 413 414 The caller of these methods is responsible to handle exceptions (error or 415 exit) using ``PyStatus_Exception()`` and ``Py_ExitStatusException()``. 416 417 Structure fields: 418 419 .. c:member:: PyWideStringList argv 420 421 Command line arguments, :data:`sys.argv`. See 422 :c:member:`~PyConfig.parse_argv` to parse :c:member:`~PyConfig.argv` the 423 same way the regular Python parses Python command line arguments. If 424 :c:member:`~PyConfig.argv` is empty, an empty string is added to ensure 425 that :data:`sys.argv` always exists and is never empty. 426 427 .. c:member:: wchar_t* base_exec_prefix 428 429 :data:`sys.base_exec_prefix`. 430 431 .. c:member:: wchar_t* base_executable 432 433 :data:`sys._base_executable`: ``__PYVENV_LAUNCHER__`` environment 434 variable value, or copy of :c:member:`PyConfig.executable`. 435 436 .. c:member:: wchar_t* base_prefix 437 438 :data:`sys.base_prefix`. 439 440 .. c:member:: wchar_t* platlibdir 441 442 :data:`sys.platlibdir`: platform library directory name, set at configure time 443 by ``--with-platlibdir``, overrideable by the ``PYTHONPLATLIBDIR`` 444 environment variable. 445 446 .. versionadded:: 3.9 447 448 .. c:member:: int buffered_stdio 449 450 If equals to 0, enable unbuffered mode, making the stdout and stderr 451 streams unbuffered. 452 453 stdin is always opened in buffered mode. 454 455 .. c:member:: int bytes_warning 456 457 If equals to 1, issue a warning when comparing :class:`bytes` or 458 :class:`bytearray` with :class:`str`, or comparing :class:`bytes` with 459 :class:`int`. If equal or greater to 2, raise a :exc:`BytesWarning` 460 exception. 461 462 .. c:member:: wchar_t* check_hash_pycs_mode 463 464 Control the validation behavior of hash-based ``.pyc`` files (see 465 :pep:`552`): :option:`--check-hash-based-pycs` command line option value. 466 467 Valid values: ``always``, ``never`` and ``default``. 468 469 The default value is: ``default``. 470 471 .. c:member:: int configure_c_stdio 472 473 If non-zero, configure C standard streams (``stdio``, ``stdout``, 474 ``stdout``). For example, set their mode to ``O_BINARY`` on Windows. 475 476 .. c:member:: int dev_mode 477 478 If non-zero, enable the :ref:`Python Development Mode <devmode>`. 479 480 .. c:member:: int dump_refs 481 482 If non-zero, dump all objects which are still alive at exit. 483 484 ``Py_TRACE_REFS`` macro must be defined in build. 485 486 .. c:member:: wchar_t* exec_prefix 487 488 :data:`sys.exec_prefix`. 489 490 .. c:member:: wchar_t* executable 491 492 :data:`sys.executable`. 493 494 .. c:member:: int faulthandler 495 496 If non-zero, call :func:`faulthandler.enable` at startup. 497 498 .. c:member:: wchar_t* filesystem_encoding 499 500 Filesystem encoding, :func:`sys.getfilesystemencoding`. 501 502 .. c:member:: wchar_t* filesystem_errors 503 504 Filesystem encoding errors, :func:`sys.getfilesystemencodeerrors`. 505 506 .. c:member:: unsigned long hash_seed 507 .. c:member:: int use_hash_seed 508 509 Randomized hash function seed. 510 511 If :c:member:`~PyConfig.use_hash_seed` is zero, a seed is chosen randomly 512 at Pythonstartup, and :c:member:`~PyConfig.hash_seed` is ignored. 513 514 .. c:member:: wchar_t* home 515 516 Python home directory. 517 518 Initialized from :envvar:`PYTHONHOME` environment variable value by 519 default. 520 521 .. c:member:: int import_time 522 523 If non-zero, profile import time. 524 525 .. c:member:: int inspect 526 527 Enter interactive mode after executing a script or a command. 528 529 .. c:member:: int install_signal_handlers 530 531 Install signal handlers? 532 533 .. c:member:: int interactive 534 535 Interactive mode. 536 537 .. c:member:: int isolated 538 539 If greater than 0, enable isolated mode: 540 541 * :data:`sys.path` contains neither the script's directory (computed from 542 ``argv[0]`` or the current directory) nor the user's site-packages 543 directory. 544 * Python REPL doesn't import :mod:`readline` nor enable default readline 545 configuration on interactive prompts. 546 * Set :c:member:`~PyConfig.use_environment` and 547 :c:member:`~PyConfig.user_site_directory` to 0. 548 549 .. c:member:: int legacy_windows_stdio 550 551 If non-zero, use :class:`io.FileIO` instead of 552 :class:`io.WindowsConsoleIO` for :data:`sys.stdin`, :data:`sys.stdout` 553 and :data:`sys.stderr`. 554 555 Only available on Windows. ``#ifdef MS_WINDOWS`` macro can be used for 556 Windows specific code. 557 558 .. c:member:: int malloc_stats 559 560 If non-zero, dump statistics on :ref:`Python pymalloc memory allocator 561 <pymalloc>` at exit. 562 563 The option is ignored if Python is built using ``--without-pymalloc``. 564 565 .. c:member:: wchar_t* pythonpath_env 566 567 Module search paths as a string separated by ``DELIM`` 568 (:data:`os.path.pathsep`). 569 570 Initialized from :envvar:`PYTHONPATH` environment variable value by 571 default. 572 573 .. c:member:: PyWideStringList module_search_paths 574 .. c:member:: int module_search_paths_set 575 576 :data:`sys.path`. If :c:member:`~PyConfig.module_search_paths_set` is 577 equal to 0, the :c:member:`~PyConfig.module_search_paths` is overridden 578 by the function calculating the :ref:`Path Configuration 579 <init-path-config>`. 580 581 .. c:member:: int optimization_level 582 583 Compilation optimization level: 584 585 * 0: Peephole optimizer (and ``__debug__`` is set to ``True``) 586 * 1: Remove assertions, set ``__debug__`` to ``False`` 587 * 2: Strip docstrings 588 589 .. c:member:: int parse_argv 590 591 If non-zero, parse :c:member:`~PyConfig.argv` the same way the regular 592 Python command line arguments, and strip Python arguments from 593 :c:member:`~PyConfig.argv`: see :ref:`Command Line Arguments 594 <using-on-cmdline>`. 595 596 .. c:member:: int parser_debug 597 598 If non-zero, turn on parser debugging output (for expert only, depending 599 on compilation options). 600 601 .. c:member:: int pathconfig_warnings 602 603 If equal to 0, suppress warnings when calculating the :ref:`Path 604 Configuration <init-path-config>` (Unix only, Windows does not log any 605 warning). Otherwise, warnings are written into ``stderr``. 606 607 .. c:member:: wchar_t* prefix 608 609 :data:`sys.prefix`. 610 611 .. c:member:: wchar_t* program_name 612 613 Program name. Used to initialize :c:member:`~PyConfig.executable`, and in 614 early error messages. 615 616 .. c:member:: wchar_t* pycache_prefix 617 618 :data:`sys.pycache_prefix`: ``.pyc`` cache prefix. 619 620 If ``NULL``, :data:`sys.pycache_prefix` is set to ``None``. 621 622 .. c:member:: int quiet 623 624 Quiet mode. For example, don't display the copyright and version messages 625 in interactive mode. 626 627 .. c:member:: wchar_t* run_command 628 629 ``python3 -c COMMAND`` argument. Used by :c:func:`Py_RunMain`. 630 631 .. c:member:: wchar_t* run_filename 632 633 ``python3 FILENAME`` argument. Used by :c:func:`Py_RunMain`. 634 635 .. c:member:: wchar_t* run_module 636 637 ``python3 -m MODULE`` argument. Used by :c:func:`Py_RunMain`. 638 639 .. c:member:: int show_ref_count 640 641 Show total reference count at exit? 642 643 Set to 1 by :option:`-X showrefcount <-X>` command line option. 644 645 Need a debug build of Python (``Py_REF_DEBUG`` macro must be defined). 646 647 .. c:member:: int site_import 648 649 Import the :mod:`site` module at startup? 650 651 .. c:member:: int skip_source_first_line 652 653 Skip the first line of the source? 654 655 .. c:member:: wchar_t* stdio_encoding 656 .. c:member:: wchar_t* stdio_errors 657 658 Encoding and encoding errors of :data:`sys.stdin`, :data:`sys.stdout` and 659 :data:`sys.stderr`. 660 661 .. c:member:: int tracemalloc 662 663 If non-zero, call :func:`tracemalloc.start` at startup. 664 665 .. c:member:: int use_environment 666 667 If greater than 0, use :ref:`environment variables <using-on-envvars>`. 668 669 .. c:member:: int user_site_directory 670 671 If non-zero, add user site directory to :data:`sys.path`. 672 673 .. c:member:: int verbose 674 675 If non-zero, enable verbose mode. 676 677 .. c:member:: PyWideStringList warnoptions 678 679 :data:`sys.warnoptions`: options of the :mod:`warnings` module to build 680 warnings filters: lowest to highest priority. 681 682 The :mod:`warnings` module adds :data:`sys.warnoptions` in the reverse 683 order: the last :c:member:`PyConfig.warnoptions` item becomes the first 684 item of :data:`warnings.filters` which is checked first (highest 685 priority). 686 687 .. c:member:: int write_bytecode 688 689 If non-zero, write ``.pyc`` files. 690 691 :data:`sys.dont_write_bytecode` is initialized to the inverted value of 692 :c:member:`~PyConfig.write_bytecode`. 693 694 .. c:member:: PyWideStringList xoptions 695 696 :data:`sys._xoptions`. 697 698 .. c:member:: int _use_peg_parser 699 700 Enable PEG parser? Default: 1. 701 702 Set to 0 by :option:`-X oldparser <-X>` and :envvar:`PYTHONOLDPARSER`. 703 704 See also :pep:`617`. 705 706 .. deprecated-removed:: 3.9 3.10 707 708If ``parse_argv`` is non-zero, ``argv`` arguments are parsed the same 709way the regular Python parses command line arguments, and Python 710arguments are stripped from ``argv``: see :ref:`Command Line Arguments 711<using-on-cmdline>`. 712 713The ``xoptions`` options are parsed to set other options: see :option:`-X` 714option. 715 716.. versionchanged:: 3.9 717 718 The ``show_alloc_count`` field has been removed. 719 720 721Initialization with PyConfig 722---------------------------- 723 724Function to initialize Python: 725 726.. c:function:: PyStatus Py_InitializeFromConfig(const PyConfig *config) 727 728 Initialize Python from *config* configuration. 729 730The caller is responsible to handle exceptions (error or exit) using 731:c:func:`PyStatus_Exception` and :c:func:`Py_ExitStatusException`. 732 733If ``PyImport_FrozenModules``, ``PyImport_AppendInittab()`` or 734``PyImport_ExtendInittab()`` are used, they must be set or called after Python 735preinitialization and before the Python initialization. 736 737Example setting the program name:: 738 739 void init_python(void) 740 { 741 PyStatus status; 742 743 PyConfig config; 744 PyConfig_InitPythonConfig(&config); 745 746 /* Set the program name. Implicitly preinitialize Python. */ 747 status = PyConfig_SetString(&config, &config.program_name, 748 L"/path/to/my_program"); 749 if (PyStatus_Exception(status)) { 750 goto fail; 751 } 752 753 status = Py_InitializeFromConfig(&config); 754 if (PyStatus_Exception(status)) { 755 goto fail; 756 } 757 PyConfig_Clear(&config); 758 return; 759 760 fail: 761 PyConfig_Clear(&config); 762 Py_ExitStatusException(status); 763 } 764 765More complete example modifying the default configuration, read the 766configuration, and then override some parameters:: 767 768 PyStatus init_python(const char *program_name) 769 { 770 PyStatus status; 771 772 PyConfig config; 773 PyConfig_InitPythonConfig(&config); 774 775 /* Set the program name before reading the configuration 776 (decode byte string from the locale encoding). 777 778 Implicitly preinitialize Python. */ 779 status = PyConfig_SetBytesString(&config, &config.program_name, 780 program_name); 781 if (PyStatus_Exception(status)) { 782 goto done; 783 } 784 785 /* Read all configuration at once */ 786 status = PyConfig_Read(&config); 787 if (PyStatus_Exception(status)) { 788 goto done; 789 } 790 791 /* Append our custom search path to sys.path */ 792 status = PyWideStringList_Append(&config.module_search_paths, 793 L"/path/to/more/modules"); 794 if (PyStatus_Exception(status)) { 795 goto done; 796 } 797 798 /* Override executable computed by PyConfig_Read() */ 799 status = PyConfig_SetString(&config, &config.executable, 800 L"/path/to/my_executable"); 801 if (PyStatus_Exception(status)) { 802 goto done; 803 } 804 805 status = Py_InitializeFromConfig(&config); 806 807 done: 808 PyConfig_Clear(&config); 809 return status; 810 } 811 812 813.. _init-isolated-conf: 814 815Isolated Configuration 816---------------------- 817 818:c:func:`PyPreConfig_InitIsolatedConfig` and 819:c:func:`PyConfig_InitIsolatedConfig` functions create a configuration to 820isolate Python from the system. For example, to embed Python into an 821application. 822 823This configuration ignores global configuration variables, environments 824variables, command line arguments (:c:member:`PyConfig.argv` is not parsed) 825and user site directory. The C standard streams (ex: ``stdout``) and the 826LC_CTYPE locale are left unchanged. Signal handlers are not installed. 827 828Configuration files are still used with this configuration. Set the 829:ref:`Path Configuration <init-path-config>` ("output fields") to ignore these 830configuration files and avoid the function computing the default path 831configuration. 832 833 834.. _init-python-config: 835 836Python Configuration 837-------------------- 838 839:c:func:`PyPreConfig_InitPythonConfig` and :c:func:`PyConfig_InitPythonConfig` 840functions create a configuration to build a customized Python which behaves as 841the regular Python. 842 843Environments variables and command line arguments are used to configure 844Python, whereas global configuration variables are ignored. 845 846This function enables C locale coercion (:pep:`538`) and UTF-8 Mode 847(:pep:`540`) depending on the LC_CTYPE locale, :envvar:`PYTHONUTF8` and 848:envvar:`PYTHONCOERCECLOCALE` environment variables. 849 850Example of customized Python always running in isolated mode:: 851 852 int main(int argc, char **argv) 853 { 854 PyStatus status; 855 856 PyConfig config; 857 PyConfig_InitPythonConfig(&config); 858 config.isolated = 1; 859 860 /* Decode command line arguments. 861 Implicitly preinitialize Python (in isolated mode). */ 862 status = PyConfig_SetBytesArgv(&config, argc, argv); 863 if (PyStatus_Exception(status)) { 864 goto fail; 865 } 866 867 status = Py_InitializeFromConfig(&config); 868 if (PyStatus_Exception(status)) { 869 goto fail; 870 } 871 PyConfig_Clear(&config); 872 873 return Py_RunMain(); 874 875 fail: 876 PyConfig_Clear(&config); 877 if (PyStatus_IsExit(status)) { 878 return status.exitcode; 879 } 880 /* Display the error message and exit the process with 881 non-zero exit code */ 882 Py_ExitStatusException(status); 883 } 884 885 886.. _init-path-config: 887 888Path Configuration 889------------------ 890 891:c:type:`PyConfig` contains multiple fields for the path configuration: 892 893* Path configuration inputs: 894 895 * :c:member:`PyConfig.home` 896 * :c:member:`PyConfig.platlibdir` 897 * :c:member:`PyConfig.pathconfig_warnings` 898 * :c:member:`PyConfig.program_name` 899 * :c:member:`PyConfig.pythonpath_env` 900 * current working directory: to get absolute paths 901 * ``PATH`` environment variable to get the program full path 902 (from :c:member:`PyConfig.program_name`) 903 * ``__PYVENV_LAUNCHER__`` environment variable 904 * (Windows only) Application paths in the registry under 905 "Software\Python\PythonCore\X.Y\PythonPath" of HKEY_CURRENT_USER and 906 HKEY_LOCAL_MACHINE (where X.Y is the Python version). 907 908* Path configuration output fields: 909 910 * :c:member:`PyConfig.base_exec_prefix` 911 * :c:member:`PyConfig.base_executable` 912 * :c:member:`PyConfig.base_prefix` 913 * :c:member:`PyConfig.exec_prefix` 914 * :c:member:`PyConfig.executable` 915 * :c:member:`PyConfig.module_search_paths_set`, 916 :c:member:`PyConfig.module_search_paths` 917 * :c:member:`PyConfig.prefix` 918 919If at least one "output field" is not set, Python calculates the path 920configuration to fill unset fields. If 921:c:member:`~PyConfig.module_search_paths_set` is equal to 0, 922:c:member:`~PyConfig.module_search_paths` is overridden and 923:c:member:`~PyConfig.module_search_paths_set` is set to 1. 924 925It is possible to completely ignore the function calculating the default 926path configuration by setting explicitly all path configuration output 927fields listed above. A string is considered as set even if it is non-empty. 928``module_search_paths`` is considered as set if 929``module_search_paths_set`` is set to 1. In this case, path 930configuration input fields are ignored as well. 931 932Set :c:member:`~PyConfig.pathconfig_warnings` to 0 to suppress warnings when 933calculating the path configuration (Unix only, Windows does not log any warning). 934 935If :c:member:`~PyConfig.base_prefix` or :c:member:`~PyConfig.base_exec_prefix` 936fields are not set, they inherit their value from :c:member:`~PyConfig.prefix` 937and :c:member:`~PyConfig.exec_prefix` respectively. 938 939:c:func:`Py_RunMain` and :c:func:`Py_Main` modify :data:`sys.path`: 940 941* If :c:member:`~PyConfig.run_filename` is set and is a directory which contains a 942 ``__main__.py`` script, prepend :c:member:`~PyConfig.run_filename` to 943 :data:`sys.path`. 944* If :c:member:`~PyConfig.isolated` is zero: 945 946 * If :c:member:`~PyConfig.run_module` is set, prepend the current directory 947 to :data:`sys.path`. Do nothing if the current directory cannot be read. 948 * If :c:member:`~PyConfig.run_filename` is set, prepend the directory of the 949 filename to :data:`sys.path`. 950 * Otherwise, prepend an empty string to :data:`sys.path`. 951 952If :c:member:`~PyConfig.site_import` is non-zero, :data:`sys.path` can be 953modified by the :mod:`site` module. If 954:c:member:`~PyConfig.user_site_directory` is non-zero and the user's 955site-package directory exists, the :mod:`site` module appends the user's 956site-package directory to :data:`sys.path`. 957 958The following configuration files are used by the path configuration: 959 960* ``pyvenv.cfg`` 961* ``python._pth`` (Windows only) 962* ``pybuilddir.txt`` (Unix only) 963 964The ``__PYVENV_LAUNCHER__`` environment variable is used to set 965:c:member:`PyConfig.base_executable` 966 967 968Py_RunMain() 969------------ 970 971.. c:function:: int Py_RunMain(void) 972 973 Execute the command (:c:member:`PyConfig.run_command`), the script 974 (:c:member:`PyConfig.run_filename`) or the module 975 (:c:member:`PyConfig.run_module`) specified on the command line or in the 976 configuration. 977 978 By default and when if :option:`-i` option is used, run the REPL. 979 980 Finally, finalizes Python and returns an exit status that can be passed to 981 the ``exit()`` function. 982 983See :ref:`Python Configuration <init-python-config>` for an example of 984customized Python always running in isolated mode using 985:c:func:`Py_RunMain`. 986 987 988Py_GetArgcArgv() 989---------------- 990 991.. c:function:: void Py_GetArgcArgv(int *argc, wchar_t ***argv) 992 993 Get the original command line arguments, before Python modified them. 994 995 996Multi-Phase Initialization Private Provisional API 997-------------------------------------------------- 998 999This section is a private provisional API introducing multi-phase 1000initialization, the core feature of the :pep:`432`: 1001 1002* "Core" initialization phase, "bare minimum Python": 1003 1004 * Builtin types; 1005 * Builtin exceptions; 1006 * Builtin and frozen modules; 1007 * The :mod:`sys` module is only partially initialized 1008 (ex: :data:`sys.path` doesn't exist yet). 1009 1010* "Main" initialization phase, Python is fully initialized: 1011 1012 * Install and configure :mod:`importlib`; 1013 * Apply the :ref:`Path Configuration <init-path-config>`; 1014 * Install signal handlers; 1015 * Finish :mod:`sys` module initialization (ex: create :data:`sys.stdout` 1016 and :data:`sys.path`); 1017 * Enable optional features like :mod:`faulthandler` and :mod:`tracemalloc`; 1018 * Import the :mod:`site` module; 1019 * etc. 1020 1021Private provisional API: 1022 1023* :c:member:`PyConfig._init_main`: if set to 0, 1024 :c:func:`Py_InitializeFromConfig` stops at the "Core" initialization phase. 1025* :c:member:`PyConfig._isolated_interpreter`: if non-zero, 1026 disallow threads, subprocesses and fork. 1027 1028.. c:function:: PyStatus _Py_InitializeMain(void) 1029 1030 Move to the "Main" initialization phase, finish the Python initialization. 1031 1032No module is imported during the "Core" phase and the ``importlib`` module is 1033not configured: the :ref:`Path Configuration <init-path-config>` is only 1034applied during the "Main" phase. It may allow to customize Python in Python to 1035override or tune the :ref:`Path Configuration <init-path-config>`, maybe 1036install a custom :data:`sys.meta_path` importer or an import hook, etc. 1037 1038It may become possible to calculatin the :ref:`Path Configuration 1039<init-path-config>` in Python, after the Core phase and before the Main phase, 1040which is one of the :pep:`432` motivation. 1041 1042The "Core" phase is not properly defined: what should be and what should 1043not be available at this phase is not specified yet. The API is marked 1044as private and provisional: the API can be modified or even be removed 1045anytime until a proper public API is designed. 1046 1047Example running Python code between "Core" and "Main" initialization 1048phases:: 1049 1050 void init_python(void) 1051 { 1052 PyStatus status; 1053 1054 PyConfig config; 1055 PyConfig_InitPythonConfig(&config); 1056 config._init_main = 0; 1057 1058 /* ... customize 'config' configuration ... */ 1059 1060 status = Py_InitializeFromConfig(&config); 1061 PyConfig_Clear(&config); 1062 if (PyStatus_Exception(status)) { 1063 Py_ExitStatusException(status); 1064 } 1065 1066 /* Use sys.stderr because sys.stdout is only created 1067 by _Py_InitializeMain() */ 1068 int res = PyRun_SimpleString( 1069 "import sys; " 1070 "print('Run Python code before _Py_InitializeMain', " 1071 "file=sys.stderr)"); 1072 if (res < 0) { 1073 exit(1); 1074 } 1075 1076 /* ... put more configuration code here ... */ 1077 1078 status = _Py_InitializeMain(); 1079 if (PyStatus_Exception(status)) { 1080 Py_ExitStatusException(status); 1081 } 1082 } 1083