1.. highlight:: c 2 3.. _init-config: 4 5*********************************** 6Python Initialization Configuration 7*********************************** 8 9.. versionadded:: 3.8 10 11Python can be initialized with :c:func:`Py_InitializeFromConfig` and the 12:c:type:`PyConfig` structure. It can be preinitialized with 13:c:func:`Py_PreInitialize` and the :c:type:`PyPreConfig` structure. 14 15There are two kinds of configuration: 16 17* The :ref:`Python Configuration <init-python-config>` can be used to build a 18 customized Python which behaves as the regular Python. For example, 19 environment variables and command line arguments are used to configure 20 Python. 21 22* The :ref:`Isolated Configuration <init-isolated-conf>` can be used to embed 23 Python into an application. It isolates Python from the system. For example, 24 environment variables are ignored, the LC_CTYPE locale is left unchanged and 25 no signal handler is registered. 26 27The :c:func:`Py_RunMain` function can be used to write a customized Python 28program. 29 30See also :ref:`Initialization, Finalization, and Threads <initialization>`. 31 32.. seealso:: 33 :pep:`587` "Python Initialization Configuration". 34 35 36Example 37======= 38 39Example of customized Python always running in isolated mode:: 40 41 int main(int argc, char **argv) 42 { 43 PyStatus status; 44 45 PyConfig config; 46 PyConfig_InitPythonConfig(&config); 47 config.isolated = 1; 48 49 /* Decode command line arguments. 50 Implicitly preinitialize Python (in isolated mode). */ 51 status = PyConfig_SetBytesArgv(&config, argc, argv); 52 if (PyStatus_Exception(status)) { 53 goto exception; 54 } 55 56 status = Py_InitializeFromConfig(&config); 57 if (PyStatus_Exception(status)) { 58 goto exception; 59 } 60 PyConfig_Clear(&config); 61 62 return Py_RunMain(); 63 64 exception: 65 PyConfig_Clear(&config); 66 if (PyStatus_IsExit(status)) { 67 return status.exitcode; 68 } 69 /* Display the error message and exit the process with 70 non-zero exit code */ 71 Py_ExitStatusException(status); 72 } 73 74 75PyWideStringList 76================ 77 78.. c:type:: PyWideStringList 79 80 List of ``wchar_t*`` strings. 81 82 If *length* is non-zero, *items* must be non-``NULL`` and all strings must be 83 non-``NULL``. 84 85 .. c:namespace:: NULL 86 87 Methods: 88 89 .. c:function:: PyStatus PyWideStringList_Append(PyWideStringList *list, const wchar_t *item) 90 91 Append *item* to *list*. 92 93 Python must be preinitialized to call this function. 94 95 .. c:function:: PyStatus PyWideStringList_Insert(PyWideStringList *list, Py_ssize_t index, const wchar_t *item) 96 97 Insert *item* into *list* at *index*. 98 99 If *index* is greater than or equal to *list* length, append *item* to 100 *list*. 101 102 *index* must be greater than or equal to ``0``. 103 104 Python must be preinitialized to call this function. 105 106 .. c:namespace:: PyWideStringList 107 108 Structure fields: 109 110 .. c:member:: Py_ssize_t length 111 112 List length. 113 114 .. c:member:: wchar_t** items 115 116 List items. 117 118PyStatus 119======== 120 121.. c:type:: PyStatus 122 123 Structure to store an initialization function status: success, error 124 or exit. 125 126 For an error, it can store the C function name which created the error. 127 128 Structure fields: 129 130 .. c:member:: int exitcode 131 132 Exit code. Argument passed to ``exit()``. 133 134 .. c:member:: const char *err_msg 135 136 Error message. 137 138 .. c:member:: const char *func 139 140 Name of the function which created an error, can be ``NULL``. 141 142 .. c:namespace:: NULL 143 144 Functions to create a status: 145 146 .. c:function:: PyStatus PyStatus_Ok(void) 147 148 Success. 149 150 .. c:function:: PyStatus PyStatus_Error(const char *err_msg) 151 152 Initialization error with a message. 153 154 *err_msg* must not be ``NULL``. 155 156 .. c:function:: PyStatus PyStatus_NoMemory(void) 157 158 Memory allocation failure (out of memory). 159 160 .. c:function:: PyStatus PyStatus_Exit(int exitcode) 161 162 Exit Python with the specified exit code. 163 164 Functions to handle a status: 165 166 .. c:function:: int PyStatus_Exception(PyStatus status) 167 168 Is the status an error or an exit? If true, the exception must be 169 handled; by calling :c:func:`Py_ExitStatusException` for example. 170 171 .. c:function:: int PyStatus_IsError(PyStatus status) 172 173 Is the result an error? 174 175 .. c:function:: int PyStatus_IsExit(PyStatus status) 176 177 Is the result an exit? 178 179 .. c:function:: void Py_ExitStatusException(PyStatus status) 180 181 Call ``exit(exitcode)`` if *status* is an exit. Print the error 182 message and exit with a non-zero exit code if *status* is an error. Must 183 only be called if ``PyStatus_Exception(status)`` is non-zero. 184 185.. note:: 186 Internally, Python uses macros which set ``PyStatus.func``, 187 whereas functions to create a status set ``func`` to ``NULL``. 188 189Example:: 190 191 PyStatus alloc(void **ptr, size_t size) 192 { 193 *ptr = PyMem_RawMalloc(size); 194 if (*ptr == NULL) { 195 return PyStatus_NoMemory(); 196 } 197 return PyStatus_Ok(); 198 } 199 200 int main(int argc, char **argv) 201 { 202 void *ptr; 203 PyStatus status = alloc(&ptr, 16); 204 if (PyStatus_Exception(status)) { 205 Py_ExitStatusException(status); 206 } 207 PyMem_Free(ptr); 208 return 0; 209 } 210 211 212PyPreConfig 213=========== 214 215.. c:type:: PyPreConfig 216 217 Structure used to preinitialize Python. 218 219 .. c:namespace:: NULL 220 221 Function to initialize a preconfiguration: 222 223 .. c:function:: void PyPreConfig_InitPythonConfig(PyPreConfig *preconfig) 224 225 Initialize the preconfiguration with :ref:`Python Configuration 226 <init-python-config>`. 227 228 .. c:function:: void PyPreConfig_InitIsolatedConfig(PyPreConfig *preconfig) 229 230 Initialize the preconfiguration with :ref:`Isolated Configuration 231 <init-isolated-conf>`. 232 233 .. c:namespace:: PyPreConfig 234 235 Structure fields: 236 237 .. c:member:: int allocator 238 239 Name of the Python memory allocators: 240 241 * ``PYMEM_ALLOCATOR_NOT_SET`` (``0``): don't change memory allocators 242 (use defaults). 243 * ``PYMEM_ALLOCATOR_DEFAULT`` (``1``): :ref:`default memory allocators 244 <default-memory-allocators>`. 245 * ``PYMEM_ALLOCATOR_DEBUG`` (``2``): :ref:`default memory allocators 246 <default-memory-allocators>` with :ref:`debug hooks 247 <pymem-debug-hooks>`. 248 * ``PYMEM_ALLOCATOR_MALLOC`` (``3``): use ``malloc()`` of the C library. 249 * ``PYMEM_ALLOCATOR_MALLOC_DEBUG`` (``4``): force usage of 250 ``malloc()`` with :ref:`debug hooks <pymem-debug-hooks>`. 251 * ``PYMEM_ALLOCATOR_PYMALLOC`` (``5``): :ref:`Python pymalloc memory 252 allocator <pymalloc>`. 253 * ``PYMEM_ALLOCATOR_PYMALLOC_DEBUG`` (``6``): :ref:`Python pymalloc 254 memory allocator <pymalloc>` with :ref:`debug hooks 255 <pymem-debug-hooks>`. 256 * ``PYMEM_ALLOCATOR_MIMALLOC`` (``6``): use ``mimalloc``, a fast 257 malloc replacement. 258 * ``PYMEM_ALLOCATOR_MIMALLOC_DEBUG`` (``7``): use ``mimalloc``, a fast 259 malloc replacement with :ref:`debug hooks <pymem-debug-hooks>`. 260 261 262 ``PYMEM_ALLOCATOR_PYMALLOC`` and ``PYMEM_ALLOCATOR_PYMALLOC_DEBUG`` are 263 not supported if Python is :option:`configured using --without-pymalloc 264 <--without-pymalloc>`. 265 266 ``PYMEM_ALLOCATOR_MIMALLOC`` and ``PYMEM_ALLOCATOR_MIMALLOC_DEBUG`` are 267 not supported if Python is :option:`configured using --without-mimalloc 268 <--without-mimalloc>` or if the underlying atomic support isn't 269 available. 270 271 See :ref:`Memory Management <memory>`. 272 273 Default: ``PYMEM_ALLOCATOR_NOT_SET``. 274 275 .. c:member:: int configure_locale 276 277 Set the LC_CTYPE locale to the user preferred locale. 278 279 If equals to ``0``, set :c:member:`~PyPreConfig.coerce_c_locale` and 280 :c:member:`~PyPreConfig.coerce_c_locale_warn` members to ``0``. 281 282 See the :term:`locale encoding`. 283 284 Default: ``1`` in Python config, ``0`` in isolated config. 285 286 .. c:member:: int coerce_c_locale 287 288 If equals to ``2``, coerce the C locale. 289 290 If equals to ``1``, read the LC_CTYPE locale to decide if it should be 291 coerced. 292 293 See the :term:`locale encoding`. 294 295 Default: ``-1`` in Python config, ``0`` in isolated config. 296 297 .. c:member:: int coerce_c_locale_warn 298 299 If non-zero, emit a warning if the C locale is coerced. 300 301 Default: ``-1`` in Python config, ``0`` in isolated config. 302 303 .. c:member:: int dev_mode 304 305 :ref:`Python Development Mode <devmode>`: see 306 :c:member:`PyConfig.dev_mode`. 307 308 Default: ``-1`` in Python mode, ``0`` in isolated mode. 309 310 .. c:member:: int isolated 311 312 Isolated mode: see :c:member:`PyConfig.isolated`. 313 314 Default: ``0`` in Python mode, ``1`` in isolated mode. 315 316 .. c:member:: int legacy_windows_fs_encoding 317 318 If non-zero: 319 320 * Set :c:member:`PyPreConfig.utf8_mode` to ``0``, 321 * Set :c:member:`PyConfig.filesystem_encoding` to ``"mbcs"``, 322 * Set :c:member:`PyConfig.filesystem_errors` to ``"replace"``. 323 324 Initialized from the :envvar:`PYTHONLEGACYWINDOWSFSENCODING` environment 325 variable value. 326 327 Only available on Windows. ``#ifdef MS_WINDOWS`` macro can be used for 328 Windows specific code. 329 330 Default: ``0``. 331 332 .. c:member:: int parse_argv 333 334 If non-zero, :c:func:`Py_PreInitializeFromArgs` and 335 :c:func:`Py_PreInitializeFromBytesArgs` parse their ``argv`` argument the 336 same way the regular Python parses command line arguments: see 337 :ref:`Command Line Arguments <using-on-cmdline>`. 338 339 Default: ``1`` in Python config, ``0`` in isolated config. 340 341 .. c:member:: int use_environment 342 343 Use :ref:`environment variables <using-on-envvars>`? See 344 :c:member:`PyConfig.use_environment`. 345 346 Default: ``1`` in Python config and ``0`` in isolated config. 347 348 .. c:member:: int utf8_mode 349 350 If non-zero, enable the :ref:`Python UTF-8 Mode <utf8-mode>`. 351 352 Set to ``0`` or ``1`` by the :option:`-X utf8 <-X>` command line option 353 and the :envvar:`PYTHONUTF8` environment variable. 354 355 Also set to ``1`` if the ``LC_CTYPE`` locale is ``C`` or ``POSIX``. 356 357 Default: ``-1`` in Python config and ``0`` in isolated config. 358 359 360.. _c-preinit: 361 362Preinitialize Python with PyPreConfig 363===================================== 364 365The preinitialization of Python: 366 367* Set the Python memory allocators (:c:member:`PyPreConfig.allocator`) 368* Configure the LC_CTYPE locale (:term:`locale encoding`) 369* Set the :ref:`Python UTF-8 Mode <utf8-mode>` 370 (:c:member:`PyPreConfig.utf8_mode`) 371 372The current preconfiguration (``PyPreConfig`` type) is stored in 373``_PyRuntime.preconfig``. 374 375Functions to preinitialize Python: 376 377.. c:function:: PyStatus Py_PreInitialize(const PyPreConfig *preconfig) 378 379 Preinitialize Python from *preconfig* preconfiguration. 380 381 *preconfig* must not be ``NULL``. 382 383.. c:function:: PyStatus Py_PreInitializeFromBytesArgs(const PyPreConfig *preconfig, int argc, char * const *argv) 384 385 Preinitialize Python from *preconfig* preconfiguration. 386 387 Parse *argv* command line arguments (bytes strings) if 388 :c:member:`~PyPreConfig.parse_argv` of *preconfig* is non-zero. 389 390 *preconfig* must not be ``NULL``. 391 392.. c:function:: PyStatus Py_PreInitializeFromArgs(const PyPreConfig *preconfig, int argc, wchar_t * const * argv) 393 394 Preinitialize Python from *preconfig* preconfiguration. 395 396 Parse *argv* command line arguments (wide strings) if 397 :c:member:`~PyPreConfig.parse_argv` of *preconfig* is non-zero. 398 399 *preconfig* must not be ``NULL``. 400 401The caller is responsible to handle exceptions (error or exit) using 402:c:func:`PyStatus_Exception` and :c:func:`Py_ExitStatusException`. 403 404For :ref:`Python Configuration <init-python-config>` 405(:c:func:`PyPreConfig_InitPythonConfig`), if Python is initialized with 406command line arguments, the command line arguments must also be passed to 407preinitialize Python, since they have an effect on the pre-configuration 408like encodings. For example, the :option:`-X utf8 <-X>` command line option 409enables the :ref:`Python UTF-8 Mode <utf8-mode>`. 410 411``PyMem_SetAllocator()`` can be called after :c:func:`Py_PreInitialize` and 412before :c:func:`Py_InitializeFromConfig` to install a custom memory allocator. 413It can be called before :c:func:`Py_PreInitialize` if 414:c:member:`PyPreConfig.allocator` is set to ``PYMEM_ALLOCATOR_NOT_SET``. 415 416Python memory allocation functions like :c:func:`PyMem_RawMalloc` must not be 417used before the Python preinitialization, whereas calling directly ``malloc()`` 418and ``free()`` is always safe. :c:func:`Py_DecodeLocale` must not be called 419before the Python preinitialization. 420 421Example using the preinitialization to enable 422the :ref:`Python UTF-8 Mode <utf8-mode>`:: 423 424 PyStatus status; 425 PyPreConfig preconfig; 426 PyPreConfig_InitPythonConfig(&preconfig); 427 428 preconfig.utf8_mode = 1; 429 430 status = Py_PreInitialize(&preconfig); 431 if (PyStatus_Exception(status)) { 432 Py_ExitStatusException(status); 433 } 434 435 /* at this point, Python speaks UTF-8 */ 436 437 Py_Initialize(); 438 /* ... use Python API here ... */ 439 Py_Finalize(); 440 441 442PyConfig 443======== 444 445.. c:type:: PyConfig 446 447 Structure containing most parameters to configure Python. 448 449 When done, the :c:func:`PyConfig_Clear` function must be used to release the 450 configuration memory. 451 452 .. c:namespace:: NULL 453 454 Structure methods: 455 456 .. c:function:: void PyConfig_InitPythonConfig(PyConfig *config) 457 458 Initialize configuration with the :ref:`Python Configuration 459 <init-python-config>`. 460 461 .. c:function:: void PyConfig_InitIsolatedConfig(PyConfig *config) 462 463 Initialize configuration with the :ref:`Isolated Configuration 464 <init-isolated-conf>`. 465 466 .. c:function:: PyStatus PyConfig_SetString(PyConfig *config, wchar_t * const *config_str, const wchar_t *str) 467 468 Copy the wide character string *str* into ``*config_str``. 469 470 :ref:`Preinitialize Python <c-preinit>` if needed. 471 472 .. c:function:: PyStatus PyConfig_SetBytesString(PyConfig *config, wchar_t * const *config_str, const char *str) 473 474 Decode *str* using :c:func:`Py_DecodeLocale` and set the result into 475 ``*config_str``. 476 477 :ref:`Preinitialize Python <c-preinit>` if needed. 478 479 .. c:function:: PyStatus PyConfig_SetArgv(PyConfig *config, int argc, wchar_t * const *argv) 480 481 Set command line arguments (:c:member:`~PyConfig.argv` member of 482 *config*) from the *argv* list of wide character strings. 483 484 :ref:`Preinitialize Python <c-preinit>` if needed. 485 486 .. c:function:: PyStatus PyConfig_SetBytesArgv(PyConfig *config, int argc, char * const *argv) 487 488 Set command line arguments (:c:member:`~PyConfig.argv` member of 489 *config*) from the *argv* list of bytes strings. Decode bytes using 490 :c:func:`Py_DecodeLocale`. 491 492 :ref:`Preinitialize Python <c-preinit>` if needed. 493 494 .. c:function:: PyStatus PyConfig_SetWideStringList(PyConfig *config, PyWideStringList *list, Py_ssize_t length, wchar_t **items) 495 496 Set the list of wide strings *list* to *length* and *items*. 497 498 :ref:`Preinitialize Python <c-preinit>` if needed. 499 500 .. c:function:: PyStatus PyConfig_Read(PyConfig *config) 501 502 Read all Python configuration. 503 504 Fields which are already initialized are left unchanged. 505 506 Fields for :ref:`path configuration <init-path-config>` are no longer 507 calculated or modified when calling this function, as of Python 3.11. 508 509 The :c:func:`PyConfig_Read` function only parses 510 :c:member:`PyConfig.argv` arguments once: :c:member:`PyConfig.parse_argv` 511 is set to ``2`` after arguments are parsed. Since Python arguments are 512 stripped from :c:member:`PyConfig.argv`, parsing arguments twice would 513 parse the application options as Python options. 514 515 :ref:`Preinitialize Python <c-preinit>` if needed. 516 517 .. versionchanged:: 3.10 518 The :c:member:`PyConfig.argv` arguments are now only parsed once, 519 :c:member:`PyConfig.parse_argv` is set to ``2`` after arguments are 520 parsed, and arguments are only parsed if 521 :c:member:`PyConfig.parse_argv` equals ``1``. 522 523 .. versionchanged:: 3.11 524 :c:func:`PyConfig_Read` no longer calculates all paths, and so fields 525 listed under :ref:`Python Path Configuration <init-path-config>` may 526 no longer be updated until :c:func:`Py_InitializeFromConfig` is 527 called. 528 529 .. c:function:: void PyConfig_Clear(PyConfig *config) 530 531 Release configuration memory. 532 533 Most ``PyConfig`` methods :ref:`preinitialize Python <c-preinit>` if needed. 534 In that case, the Python preinitialization configuration 535 (:c:type:`PyPreConfig`) in based on the :c:type:`PyConfig`. If configuration 536 fields which are in common with :c:type:`PyPreConfig` are tuned, they must 537 be set before calling a :c:type:`PyConfig` method: 538 539 * :c:member:`PyConfig.dev_mode` 540 * :c:member:`PyConfig.isolated` 541 * :c:member:`PyConfig.parse_argv` 542 * :c:member:`PyConfig.use_environment` 543 544 Moreover, if :c:func:`PyConfig_SetArgv` or :c:func:`PyConfig_SetBytesArgv` 545 is used, this method must be called before other methods, since the 546 preinitialization configuration depends on command line arguments (if 547 :c:member:`~PyConfig.parse_argv` is non-zero). 548 549 The caller of these methods is responsible to handle exceptions (error or 550 exit) using ``PyStatus_Exception()`` and ``Py_ExitStatusException()``. 551 552 .. c:namespace:: PyConfig 553 554 Structure fields: 555 556 .. c:member:: PyWideStringList argv 557 558 .. index:: 559 single: main() 560 single: argv (in module sys) 561 562 Set :data:`sys.argv` command line arguments based on 563 :c:member:`~PyConfig.argv`. These parameters are similar to those passed 564 to the program's :c:func:`main` function with the difference that the 565 first entry should refer to the script file to be executed rather than 566 the executable hosting the Python interpreter. If there isn't a script 567 that will be run, the first entry in :c:member:`~PyConfig.argv` can be an 568 empty string. 569 570 Set :c:member:`~PyConfig.parse_argv` to ``1`` to parse 571 :c:member:`~PyConfig.argv` the same way the regular Python parses Python 572 command line arguments and then to strip Python arguments from 573 :c:member:`~PyConfig.argv`. 574 575 If :c:member:`~PyConfig.argv` is empty, an empty string is added to 576 ensure that :data:`sys.argv` always exists and is never empty. 577 578 Default: ``NULL``. 579 580 See also the :c:member:`~PyConfig.orig_argv` member. 581 582 .. c:member:: int safe_path 583 584 If equals to zero, ``Py_RunMain()`` prepends a potentially unsafe path to 585 :data:`sys.path` at startup: 586 587 * If :c:member:`argv[0] <PyConfig.argv>` is equal to ``L"-m"`` 588 (``python -m module``), prepend the current working directory. 589 * If running a script (``python script.py``), prepend the script's 590 directory. If it's a symbolic link, resolve symbolic links. 591 * Otherwise (``python -c code`` and ``python``), prepend an empty string, 592 which means the current working directory. 593 594 Set to ``1`` by the :option:`-P` command line option and the 595 :envvar:`PYTHONSAFEPATH` environment variable. 596 597 Default: ``0`` in Python config, ``1`` in isolated config. 598 599 .. versionadded:: 3.11 600 601 .. c:member:: wchar_t* base_exec_prefix 602 603 :data:`sys.base_exec_prefix`. 604 605 Default: ``NULL``. 606 607 Part of the :ref:`Python Path Configuration <init-path-config>` output. 608 609 See also :c:member:`PyConfig.exec_prefix`. 610 611 .. c:member:: wchar_t* base_executable 612 613 Python base executable: :data:`sys._base_executable`. 614 615 Set by the :envvar:`__PYVENV_LAUNCHER__` environment variable. 616 617 Set from :c:member:`PyConfig.executable` if ``NULL``. 618 619 Default: ``NULL``. 620 621 Part of the :ref:`Python Path Configuration <init-path-config>` output. 622 623 See also :c:member:`PyConfig.executable`. 624 625 .. c:member:: wchar_t* base_prefix 626 627 :data:`sys.base_prefix`. 628 629 Default: ``NULL``. 630 631 Part of the :ref:`Python Path Configuration <init-path-config>` output. 632 633 See also :c:member:`PyConfig.prefix`. 634 635 .. c:member:: int buffered_stdio 636 637 If equals to ``0`` and :c:member:`~PyConfig.configure_c_stdio` is non-zero, 638 disable buffering on the C streams stdout and stderr. 639 640 Set to ``0`` by the :option:`-u` command line option and the 641 :envvar:`PYTHONUNBUFFERED` environment variable. 642 643 stdin is always opened in buffered mode. 644 645 Default: ``1``. 646 647 .. c:member:: int bytes_warning 648 649 If equals to ``1``, issue a warning when comparing :class:`bytes` or 650 :class:`bytearray` with :class:`str`, or comparing :class:`bytes` with 651 :class:`int`. 652 653 If equal or greater to ``2``, raise a :exc:`BytesWarning` exception in these 654 cases. 655 656 Incremented by the :option:`-b` command line option. 657 658 Default: ``0``. 659 660 .. c:member:: int warn_default_encoding 661 662 If non-zero, emit a :exc:`EncodingWarning` warning when :class:`io.TextIOWrapper` 663 uses its default encoding. See :ref:`io-encoding-warning` for details. 664 665 Default: ``0``. 666 667 .. versionadded:: 3.10 668 669 .. c:member:: int code_debug_ranges 670 671 If equals to ``0``, disables the inclusion of the end line and column 672 mappings in code objects. Also disables traceback printing carets to 673 specific error locations. 674 675 Set to ``0`` by the :envvar:`PYTHONNODEBUGRANGES` environment variable 676 and by the :option:`-X no_debug_ranges <-X>` command line option. 677 678 Default: ``1``. 679 680 .. versionadded:: 3.11 681 682 .. c:member:: wchar_t* check_hash_pycs_mode 683 684 Control the validation behavior of hash-based ``.pyc`` files: 685 value of the :option:`--check-hash-based-pycs` command line option. 686 687 Valid values: 688 689 - ``L"always"``: Hash the source file for invalidation regardless of 690 value of the 'check_source' flag. 691 - ``L"never"``: Assume that hash-based pycs always are valid. 692 - ``L"default"``: The 'check_source' flag in hash-based pycs 693 determines invalidation. 694 695 Default: ``L"default"``. 696 697 See also :pep:`552` "Deterministic pycs". 698 699 .. c:member:: int configure_c_stdio 700 701 If non-zero, configure C standard streams: 702 703 * On Windows, set the binary mode (``O_BINARY``) on stdin, stdout and 704 stderr. 705 * If :c:member:`~PyConfig.buffered_stdio` equals zero, disable buffering 706 of stdin, stdout and stderr streams. 707 * If :c:member:`~PyConfig.interactive` is non-zero, enable stream 708 buffering on stdin and stdout (only stdout on Windows). 709 710 Default: ``1`` in Python config, ``0`` in isolated config. 711 712 .. c:member:: int dev_mode 713 714 If non-zero, enable the :ref:`Python Development Mode <devmode>`. 715 716 Set to ``1`` by the :option:`-X dev <-X>` option and the 717 :envvar:`PYTHONDEVMODE` environment variable. 718 719 Default: ``-1`` in Python mode, ``0`` in isolated mode. 720 721 .. c:member:: int dump_refs 722 723 Dump Python references? 724 725 If non-zero, dump all objects which are still alive at exit. 726 727 Set to ``1`` by the :envvar:`PYTHONDUMPREFS` environment variable. 728 729 Needs a special build of Python with the ``Py_TRACE_REFS`` macro defined: 730 see the :option:`configure --with-trace-refs option <--with-trace-refs>`. 731 732 Default: ``0``. 733 734 .. c:member:: wchar_t* exec_prefix 735 736 The site-specific directory prefix where the platform-dependent Python 737 files are installed: :data:`sys.exec_prefix`. 738 739 Default: ``NULL``. 740 741 Part of the :ref:`Python Path Configuration <init-path-config>` output. 742 743 See also :c:member:`PyConfig.base_exec_prefix`. 744 745 .. c:member:: wchar_t* executable 746 747 The absolute path of the executable binary for the Python interpreter: 748 :data:`sys.executable`. 749 750 Default: ``NULL``. 751 752 Part of the :ref:`Python Path Configuration <init-path-config>` output. 753 754 See also :c:member:`PyConfig.base_executable`. 755 756 .. c:member:: int faulthandler 757 758 Enable faulthandler? 759 760 If non-zero, call :func:`faulthandler.enable` at startup. 761 762 Set to ``1`` by :option:`-X faulthandler <-X>` and the 763 :envvar:`PYTHONFAULTHANDLER` environment variable. 764 765 Default: ``-1`` in Python mode, ``0`` in isolated mode. 766 767 .. c:member:: wchar_t* filesystem_encoding 768 769 :term:`Filesystem encoding <filesystem encoding and error handler>`: 770 :func:`sys.getfilesystemencoding`. 771 772 On macOS, Android and VxWorks: use ``"utf-8"`` by default. 773 774 On Windows: use ``"utf-8"`` by default, or ``"mbcs"`` if 775 :c:member:`~PyPreConfig.legacy_windows_fs_encoding` of 776 :c:type:`PyPreConfig` is non-zero. 777 778 Default encoding on other platforms: 779 780 * ``"utf-8"`` if :c:member:`PyPreConfig.utf8_mode` is non-zero. 781 * ``"ascii"`` if Python detects that ``nl_langinfo(CODESET)`` announces 782 the ASCII encoding, whereas the ``mbstowcs()`` function 783 decodes from a different encoding (usually Latin1). 784 * ``"utf-8"`` if ``nl_langinfo(CODESET)`` returns an empty string. 785 * Otherwise, use the :term:`locale encoding`: 786 ``nl_langinfo(CODESET)`` result. 787 788 At Python startup, the encoding name is normalized to the Python codec 789 name. For example, ``"ANSI_X3.4-1968"`` is replaced with ``"ascii"``. 790 791 See also the :c:member:`~PyConfig.filesystem_errors` member. 792 793 .. c:member:: wchar_t* filesystem_errors 794 795 :term:`Filesystem error handler <filesystem encoding and error handler>`: 796 :func:`sys.getfilesystemencodeerrors`. 797 798 On Windows: use ``"surrogatepass"`` by default, or ``"replace"`` if 799 :c:member:`~PyPreConfig.legacy_windows_fs_encoding` of 800 :c:type:`PyPreConfig` is non-zero. 801 802 On other platforms: use ``"surrogateescape"`` by default. 803 804 Supported error handlers: 805 806 * ``"strict"`` 807 * ``"surrogateescape"`` 808 * ``"surrogatepass"`` (only supported with the UTF-8 encoding) 809 810 See also the :c:member:`~PyConfig.filesystem_encoding` member. 811 812 .. c:member:: unsigned long hash_seed 813 .. c:member:: int use_hash_seed 814 815 Randomized hash function seed. 816 817 If :c:member:`~PyConfig.use_hash_seed` is zero, a seed is chosen randomly 818 at Python startup, and :c:member:`~PyConfig.hash_seed` is ignored. 819 820 Set by the :envvar:`PYTHONHASHSEED` environment variable. 821 822 Default *use_hash_seed* value: ``-1`` in Python mode, ``0`` in isolated 823 mode. 824 825 .. c:member:: wchar_t* home 826 827 Set the default Python "home" directory, that is, the location of the 828 standard Python libraries (see :envvar:`PYTHONHOME`). 829 830 Set by the :envvar:`PYTHONHOME` environment variable. 831 832 Default: ``NULL``. 833 834 Part of the :ref:`Python Path Configuration <init-path-config>` input. 835 836 .. c:member:: int import_time 837 838 If non-zero, profile import time. 839 840 Set the ``1`` by the :option:`-X importtime <-X>` option and the 841 :envvar:`PYTHONPROFILEIMPORTTIME` environment variable. 842 843 Default: ``0``. 844 845 .. c:member:: int inspect 846 847 Enter interactive mode after executing a script or a command. 848 849 If greater than ``0``, enable inspect: when a script is passed as first 850 argument or the -c option is used, enter interactive mode after executing 851 the script or the command, even when :data:`sys.stdin` does not appear to 852 be a terminal. 853 854 Incremented by the :option:`-i` command line option. Set to ``1`` if the 855 :envvar:`PYTHONINSPECT` environment variable is non-empty. 856 857 Default: ``0``. 858 859 .. c:member:: int install_signal_handlers 860 861 Install Python signal handlers? 862 863 Default: ``1`` in Python mode, ``0`` in isolated mode. 864 865 .. c:member:: int interactive 866 867 If greater than ``0``, enable the interactive mode (REPL). 868 869 Incremented by the :option:`-i` command line option. 870 871 Default: ``0``. 872 873 .. c:member:: int int_max_str_digits 874 875 Configures the :ref:`integer string conversion length limitation 876 <int_max_str_digits>`. An initial value of ``-1`` means the value will 877 be taken from the command line or environment or otherwise default to 878 4300 (:data:`sys.int_info.default_max_str_digits`). A value of ``0`` 879 disables the limitation. Values greater than zero but less than 640 880 (:data:`sys.int_info.str_digits_check_threshold`) are unsupported and 881 will produce an error. 882 883 Configured by the :option:`-X int_max_str_digits <-X>` command line 884 flag or the :envvar:`PYTHONINTMAXSTRDIGITS` environment variable. 885 886 Default: ``-1`` in Python mode. 4300 887 (:data:`sys.int_info.default_max_str_digits`) in isolated mode. 888 889 .. versionadded:: 3.12 890 891 .. c:member:: int cpu_count 892 893 If the value of :c:member:`~PyConfig.cpu_count` is not ``-1`` then it will 894 override the return values of :func:`os.cpu_count`, 895 :func:`os.process_cpu_count`, and :func:`multiprocessing.cpu_count`. 896 897 Configured by the :samp:`-X cpu_count={n|default}` command line 898 flag or the :envvar:`PYTHON_CPU_COUNT` environment variable. 899 900 Default: ``-1``. 901 902 .. versionadded:: 3.13 903 904 .. c:member:: int isolated 905 906 If greater than ``0``, enable isolated mode: 907 908 * Set :c:member:`~PyConfig.safe_path` to ``1``: 909 don't prepend a potentially unsafe path to :data:`sys.path` at Python 910 startup, such as the current directory, the script's directory or an 911 empty string. 912 * Set :c:member:`~PyConfig.use_environment` to ``0``: ignore ``PYTHON`` 913 environment variables. 914 * Set :c:member:`~PyConfig.user_site_directory` to ``0``: don't add the user 915 site directory to :data:`sys.path`. 916 * Python REPL doesn't import :mod:`readline` nor enable default readline 917 configuration on interactive prompts. 918 919 Set to ``1`` by the :option:`-I` command line option. 920 921 Default: ``0`` in Python mode, ``1`` in isolated mode. 922 923 See also the :ref:`Isolated Configuration <init-isolated-conf>` and 924 :c:member:`PyPreConfig.isolated`. 925 926 .. c:member:: int legacy_windows_stdio 927 928 If non-zero, use :class:`io.FileIO` instead of 929 :class:`!io._WindowsConsoleIO` for :data:`sys.stdin`, :data:`sys.stdout` 930 and :data:`sys.stderr`. 931 932 Set to ``1`` if the :envvar:`PYTHONLEGACYWINDOWSSTDIO` environment 933 variable is set to a non-empty string. 934 935 Only available on Windows. ``#ifdef MS_WINDOWS`` macro can be used for 936 Windows specific code. 937 938 Default: ``0``. 939 940 See also the :pep:`528` (Change Windows console encoding to UTF-8). 941 942 .. c:member:: int malloc_stats 943 944 If non-zero, dump statistics on :ref:`Python pymalloc memory allocator 945 <pymalloc>` at exit. 946 947 Set to ``1`` by the :envvar:`PYTHONMALLOCSTATS` environment variable. 948 949 The option is ignored if Python is :option:`configured using 950 the --without-pymalloc option <--without-pymalloc>`. 951 952 Default: ``0``. 953 954 .. c:member:: wchar_t* platlibdir 955 956 Platform library directory name: :data:`sys.platlibdir`. 957 958 Set by the :envvar:`PYTHONPLATLIBDIR` environment variable. 959 960 Default: value of the ``PLATLIBDIR`` macro which is set by the 961 :option:`configure --with-platlibdir option <--with-platlibdir>` 962 (default: ``"lib"``, or ``"DLLs"`` on Windows). 963 964 Part of the :ref:`Python Path Configuration <init-path-config>` input. 965 966 .. versionadded:: 3.9 967 968 .. versionchanged:: 3.11 969 This macro is now used on Windows to locate the standard 970 library extension modules, typically under ``DLLs``. However, 971 for compatibility, note that this value is ignored for any 972 non-standard layouts, including in-tree builds and virtual 973 environments. 974 975 .. c:member:: wchar_t* pythonpath_env 976 977 Module search paths (:data:`sys.path`) as a string separated by ``DELIM`` 978 (:data:`os.pathsep`). 979 980 Set by the :envvar:`PYTHONPATH` environment variable. 981 982 Default: ``NULL``. 983 984 Part of the :ref:`Python Path Configuration <init-path-config>` input. 985 986 .. c:member:: PyWideStringList module_search_paths 987 .. c:member:: int module_search_paths_set 988 989 Module search paths: :data:`sys.path`. 990 991 If :c:member:`~PyConfig.module_search_paths_set` is equal to ``0``, 992 :c:func:`Py_InitializeFromConfig` will replace 993 :c:member:`~PyConfig.module_search_paths` and sets 994 :c:member:`~PyConfig.module_search_paths_set` to ``1``. 995 996 Default: empty list (``module_search_paths``) and ``0`` 997 (``module_search_paths_set``). 998 999 Part of the :ref:`Python Path Configuration <init-path-config>` output. 1000 1001 .. c:member:: int optimization_level 1002 1003 Compilation optimization level: 1004 1005 * ``0``: Peephole optimizer, set ``__debug__`` to ``True``. 1006 * ``1``: Level 0, remove assertions, set ``__debug__`` to ``False``. 1007 * ``2``: Level 1, strip docstrings. 1008 1009 Incremented by the :option:`-O` command line option. Set to the 1010 :envvar:`PYTHONOPTIMIZE` environment variable value. 1011 1012 Default: ``0``. 1013 1014 .. c:member:: PyWideStringList orig_argv 1015 1016 The list of the original command line arguments passed to the Python 1017 executable: :data:`sys.orig_argv`. 1018 1019 If :c:member:`~PyConfig.orig_argv` list is empty and 1020 :c:member:`~PyConfig.argv` is not a list only containing an empty 1021 string, :c:func:`PyConfig_Read` copies :c:member:`~PyConfig.argv` into 1022 :c:member:`~PyConfig.orig_argv` before modifying 1023 :c:member:`~PyConfig.argv` (if :c:member:`~PyConfig.parse_argv` is 1024 non-zero). 1025 1026 See also the :c:member:`~PyConfig.argv` member and the 1027 :c:func:`Py_GetArgcArgv` function. 1028 1029 Default: empty list. 1030 1031 .. versionadded:: 3.10 1032 1033 .. c:member:: int parse_argv 1034 1035 Parse command line arguments? 1036 1037 If equals to ``1``, parse :c:member:`~PyConfig.argv` the same way the regular 1038 Python parses :ref:`command line arguments <using-on-cmdline>`, and strip 1039 Python arguments from :c:member:`~PyConfig.argv`. 1040 1041 The :c:func:`PyConfig_Read` function only parses 1042 :c:member:`PyConfig.argv` arguments once: :c:member:`PyConfig.parse_argv` 1043 is set to ``2`` after arguments are parsed. Since Python arguments are 1044 stripped from :c:member:`PyConfig.argv`, parsing arguments twice would 1045 parse the application options as Python options. 1046 1047 Default: ``1`` in Python mode, ``0`` in isolated mode. 1048 1049 .. versionchanged:: 3.10 1050 The :c:member:`PyConfig.argv` arguments are now only parsed if 1051 :c:member:`PyConfig.parse_argv` equals to ``1``. 1052 1053 .. c:member:: int parser_debug 1054 1055 Parser debug mode. If greater than ``0``, turn on parser debugging output (for expert only, depending 1056 on compilation options). 1057 1058 Incremented by the :option:`-d` command line option. Set to the 1059 :envvar:`PYTHONDEBUG` environment variable value. 1060 1061 Needs a :ref:`debug build of Python <debug-build>` (the ``Py_DEBUG`` macro 1062 must be defined). 1063 1064 Default: ``0``. 1065 1066 .. c:member:: int pathconfig_warnings 1067 1068 If non-zero, calculation of path configuration is allowed to log 1069 warnings into ``stderr``. If equals to ``0``, suppress these warnings. 1070 1071 Default: ``1`` in Python mode, ``0`` in isolated mode. 1072 1073 Part of the :ref:`Python Path Configuration <init-path-config>` input. 1074 1075 .. versionchanged:: 3.11 1076 Now also applies on Windows. 1077 1078 .. c:member:: wchar_t* prefix 1079 1080 The site-specific directory prefix where the platform independent Python 1081 files are installed: :data:`sys.prefix`. 1082 1083 Default: ``NULL``. 1084 1085 Part of the :ref:`Python Path Configuration <init-path-config>` output. 1086 1087 See also :c:member:`PyConfig.base_prefix`. 1088 1089 .. c:member:: wchar_t* program_name 1090 1091 Program name used to initialize :c:member:`~PyConfig.executable` and in 1092 early error messages during Python initialization. 1093 1094 * On macOS, use :envvar:`PYTHONEXECUTABLE` environment variable if set. 1095 * If the ``WITH_NEXT_FRAMEWORK`` macro is defined, use 1096 :envvar:`__PYVENV_LAUNCHER__` environment variable if set. 1097 * Use ``argv[0]`` of :c:member:`~PyConfig.argv` if available and 1098 non-empty. 1099 * Otherwise, use ``L"python"`` on Windows, or ``L"python3"`` on other 1100 platforms. 1101 1102 Default: ``NULL``. 1103 1104 Part of the :ref:`Python Path Configuration <init-path-config>` input. 1105 1106 .. c:member:: wchar_t* pycache_prefix 1107 1108 Directory where cached ``.pyc`` files are written: 1109 :data:`sys.pycache_prefix`. 1110 1111 Set by the :option:`-X pycache_prefix=PATH <-X>` command line option and 1112 the :envvar:`PYTHONPYCACHEPREFIX` environment variable. 1113 The command-line option takes precedence. 1114 1115 If ``NULL``, :data:`sys.pycache_prefix` is set to ``None``. 1116 1117 Default: ``NULL``. 1118 1119 .. c:member:: int quiet 1120 1121 Quiet mode. If greater than ``0``, don't display the copyright and version at 1122 Python startup in interactive mode. 1123 1124 Incremented by the :option:`-q` command line option. 1125 1126 Default: ``0``. 1127 1128 .. c:member:: wchar_t* run_command 1129 1130 Value of the :option:`-c` command line option. 1131 1132 Used by :c:func:`Py_RunMain`. 1133 1134 Default: ``NULL``. 1135 1136 .. c:member:: wchar_t* run_filename 1137 1138 Filename passed on the command line: trailing command line argument 1139 without :option:`-c` or :option:`-m`. It is used by the 1140 :c:func:`Py_RunMain` function. 1141 1142 For example, it is set to ``script.py`` by the ``python3 script.py arg`` 1143 command line. 1144 1145 See also the :c:member:`PyConfig.skip_source_first_line` option. 1146 1147 Default: ``NULL``. 1148 1149 .. c:member:: wchar_t* run_module 1150 1151 Value of the :option:`-m` command line option. 1152 1153 Used by :c:func:`Py_RunMain`. 1154 1155 Default: ``NULL``. 1156 1157 .. c:member:: wchar_t* run_presite 1158 1159 ``package.module`` path to module that should be imported before 1160 ``site.py`` is run. 1161 1162 Set by the :option:`-X presite=package.module <-X>` command-line 1163 option and the :envvar:`PYTHON_PRESITE` environment variable. 1164 The command-line option takes precedence. 1165 1166 Needs a :ref:`debug build of Python <debug-build>` (the ``Py_DEBUG`` macro 1167 must be defined). 1168 1169 Default: ``NULL``. 1170 1171 .. c:member:: int show_ref_count 1172 1173 Show total reference count at exit (excluding :term:`immortal` objects)? 1174 1175 Set to ``1`` by :option:`-X showrefcount <-X>` command line option. 1176 1177 Needs a :ref:`debug build of Python <debug-build>` (the ``Py_REF_DEBUG`` 1178 macro must be defined). 1179 1180 Default: ``0``. 1181 1182 .. c:member:: int site_import 1183 1184 Import the :mod:`site` module at startup? 1185 1186 If equal to zero, disable the import of the module site and the 1187 site-dependent manipulations of :data:`sys.path` that it entails. 1188 1189 Also disable these manipulations if the :mod:`site` module is explicitly 1190 imported later (call :func:`site.main` if you want them to be triggered). 1191 1192 Set to ``0`` by the :option:`-S` command line option. 1193 1194 :data:`sys.flags.no_site <sys.flags>` is set to the inverted value of 1195 :c:member:`~PyConfig.site_import`. 1196 1197 Default: ``1``. 1198 1199 .. c:member:: int skip_source_first_line 1200 1201 If non-zero, skip the first line of the :c:member:`PyConfig.run_filename` 1202 source. 1203 1204 It allows the usage of non-Unix forms of ``#!cmd``. This is intended for 1205 a DOS specific hack only. 1206 1207 Set to ``1`` by the :option:`-x` command line option. 1208 1209 Default: ``0``. 1210 1211 .. c:member:: wchar_t* stdio_encoding 1212 .. c:member:: wchar_t* stdio_errors 1213 1214 Encoding and encoding errors of :data:`sys.stdin`, :data:`sys.stdout` and 1215 :data:`sys.stderr` (but :data:`sys.stderr` always uses 1216 ``"backslashreplace"`` error handler). 1217 1218 Use the :envvar:`PYTHONIOENCODING` environment variable if it is 1219 non-empty. 1220 1221 Default encoding: 1222 1223 * ``"UTF-8"`` if :c:member:`PyPreConfig.utf8_mode` is non-zero. 1224 * Otherwise, use the :term:`locale encoding`. 1225 1226 Default error handler: 1227 1228 * On Windows: use ``"surrogateescape"``. 1229 * ``"surrogateescape"`` if :c:member:`PyPreConfig.utf8_mode` is non-zero, 1230 or if the LC_CTYPE locale is "C" or "POSIX". 1231 * ``"strict"`` otherwise. 1232 1233 See also :c:member:`PyConfig.legacy_windows_stdio`. 1234 1235 .. c:member:: int tracemalloc 1236 1237 Enable tracemalloc? 1238 1239 If non-zero, call :func:`tracemalloc.start` at startup. 1240 1241 Set by :option:`-X tracemalloc=N <-X>` command line option and by the 1242 :envvar:`PYTHONTRACEMALLOC` environment variable. 1243 1244 Default: ``-1`` in Python mode, ``0`` in isolated mode. 1245 1246 .. c:member:: int perf_profiling 1247 1248 Enable compatibility mode with the perf profiler? 1249 1250 If non-zero, initialize the perf trampoline. See :ref:`perf_profiling` 1251 for more information. 1252 1253 Set by :option:`-X perf <-X>` command-line option and by the 1254 :envvar:`PYTHON_PERF_JIT_SUPPORT` environment variable for perf support 1255 with stack pointers and :option:`-X perf_jit <-X>` command-line option 1256 and by the :envvar:`PYTHON_PERF_JIT_SUPPORT` environment variable for perf 1257 support with DWARF JIT information. 1258 1259 Default: ``-1``. 1260 1261 .. versionadded:: 3.12 1262 1263 .. c:member:: int use_environment 1264 1265 Use :ref:`environment variables <using-on-envvars>`? 1266 1267 If equals to zero, ignore the :ref:`environment variables 1268 <using-on-envvars>`. 1269 1270 Set to ``0`` by the :option:`-E` environment variable. 1271 1272 Default: ``1`` in Python config and ``0`` in isolated config. 1273 1274 .. c:member:: int user_site_directory 1275 1276 If non-zero, add the user site directory to :data:`sys.path`. 1277 1278 Set to ``0`` by the :option:`-s` and :option:`-I` command line options. 1279 1280 Set to ``0`` by the :envvar:`PYTHONNOUSERSITE` environment variable. 1281 1282 Default: ``1`` in Python mode, ``0`` in isolated mode. 1283 1284 .. c:member:: int verbose 1285 1286 Verbose mode. If greater than ``0``, print a message each time a module is 1287 imported, showing the place (filename or built-in module) from which 1288 it is loaded. 1289 1290 If greater than or equal to ``2``, print a message for each file that is 1291 checked for when searching for a module. Also provides information on 1292 module cleanup at exit. 1293 1294 Incremented by the :option:`-v` command line option. 1295 1296 Set by the :envvar:`PYTHONVERBOSE` environment variable value. 1297 1298 Default: ``0``. 1299 1300 .. c:member:: PyWideStringList warnoptions 1301 1302 Options of the :mod:`warnings` module to build warnings filters, lowest 1303 to highest priority: :data:`sys.warnoptions`. 1304 1305 The :mod:`warnings` module adds :data:`sys.warnoptions` in the reverse 1306 order: the last :c:member:`PyConfig.warnoptions` item becomes the first 1307 item of :data:`warnings.filters` which is checked first (highest 1308 priority). 1309 1310 The :option:`-W` command line options adds its value to 1311 :c:member:`~PyConfig.warnoptions`, it can be used multiple times. 1312 1313 The :envvar:`PYTHONWARNINGS` environment variable can also be used to add 1314 warning options. Multiple options can be specified, separated by commas 1315 (``,``). 1316 1317 Default: empty list. 1318 1319 .. c:member:: int write_bytecode 1320 1321 If equal to ``0``, Python won't try to write ``.pyc`` files on the import of 1322 source modules. 1323 1324 Set to ``0`` by the :option:`-B` command line option and the 1325 :envvar:`PYTHONDONTWRITEBYTECODE` environment variable. 1326 1327 :data:`sys.dont_write_bytecode` is initialized to the inverted value of 1328 :c:member:`~PyConfig.write_bytecode`. 1329 1330 Default: ``1``. 1331 1332 .. c:member:: PyWideStringList xoptions 1333 1334 Values of the :option:`-X` command line options: :data:`sys._xoptions`. 1335 1336 Default: empty list. 1337 1338If :c:member:`~PyConfig.parse_argv` is non-zero, :c:member:`~PyConfig.argv` 1339arguments are parsed the same way the regular Python parses :ref:`command line 1340arguments <using-on-cmdline>`, and Python arguments are stripped from 1341:c:member:`~PyConfig.argv`. 1342 1343The :c:member:`~PyConfig.xoptions` options are parsed to set other options: see 1344the :option:`-X` command line option. 1345 1346.. versionchanged:: 3.9 1347 1348 The ``show_alloc_count`` field has been removed. 1349 1350 1351.. _init-from-config: 1352 1353Initialization with PyConfig 1354============================ 1355 1356Initializing the interpreter from a populated configuration struct is handled 1357by calling :c:func:`Py_InitializeFromConfig`. 1358 1359The caller is responsible to handle exceptions (error or exit) using 1360:c:func:`PyStatus_Exception` and :c:func:`Py_ExitStatusException`. 1361 1362If :c:func:`PyImport_FrozenModules`, :c:func:`PyImport_AppendInittab` or 1363:c:func:`PyImport_ExtendInittab` are used, they must be set or called after 1364Python preinitialization and before the Python initialization. If Python is 1365initialized multiple times, :c:func:`PyImport_AppendInittab` or 1366:c:func:`PyImport_ExtendInittab` must be called before each Python 1367initialization. 1368 1369The current configuration (``PyConfig`` type) is stored in 1370``PyInterpreterState.config``. 1371 1372Example setting the program name:: 1373 1374 void init_python(void) 1375 { 1376 PyStatus status; 1377 1378 PyConfig config; 1379 PyConfig_InitPythonConfig(&config); 1380 1381 /* Set the program name. Implicitly preinitialize Python. */ 1382 status = PyConfig_SetString(&config, &config.program_name, 1383 L"/path/to/my_program"); 1384 if (PyStatus_Exception(status)) { 1385 goto exception; 1386 } 1387 1388 status = Py_InitializeFromConfig(&config); 1389 if (PyStatus_Exception(status)) { 1390 goto exception; 1391 } 1392 PyConfig_Clear(&config); 1393 return; 1394 1395 exception: 1396 PyConfig_Clear(&config); 1397 Py_ExitStatusException(status); 1398 } 1399 1400More complete example modifying the default configuration, read the 1401configuration, and then override some parameters. Note that since 14023.11, many parameters are not calculated until initialization, and 1403so values cannot be read from the configuration structure. Any values 1404set before initialize is called will be left unchanged by 1405initialization:: 1406 1407 PyStatus init_python(const char *program_name) 1408 { 1409 PyStatus status; 1410 1411 PyConfig config; 1412 PyConfig_InitPythonConfig(&config); 1413 1414 /* Set the program name before reading the configuration 1415 (decode byte string from the locale encoding). 1416 1417 Implicitly preinitialize Python. */ 1418 status = PyConfig_SetBytesString(&config, &config.program_name, 1419 program_name); 1420 if (PyStatus_Exception(status)) { 1421 goto done; 1422 } 1423 1424 /* Read all configuration at once */ 1425 status = PyConfig_Read(&config); 1426 if (PyStatus_Exception(status)) { 1427 goto done; 1428 } 1429 1430 /* Specify sys.path explicitly */ 1431 /* If you want to modify the default set of paths, finish 1432 initialization first and then use PySys_GetObject("path") */ 1433 config.module_search_paths_set = 1; 1434 status = PyWideStringList_Append(&config.module_search_paths, 1435 L"/path/to/stdlib"); 1436 if (PyStatus_Exception(status)) { 1437 goto done; 1438 } 1439 status = PyWideStringList_Append(&config.module_search_paths, 1440 L"/path/to/more/modules"); 1441 if (PyStatus_Exception(status)) { 1442 goto done; 1443 } 1444 1445 /* Override executable computed by PyConfig_Read() */ 1446 status = PyConfig_SetString(&config, &config.executable, 1447 L"/path/to/my_executable"); 1448 if (PyStatus_Exception(status)) { 1449 goto done; 1450 } 1451 1452 status = Py_InitializeFromConfig(&config); 1453 1454 done: 1455 PyConfig_Clear(&config); 1456 return status; 1457 } 1458 1459 1460.. _init-isolated-conf: 1461 1462Isolated Configuration 1463====================== 1464 1465:c:func:`PyPreConfig_InitIsolatedConfig` and 1466:c:func:`PyConfig_InitIsolatedConfig` functions create a configuration to 1467isolate Python from the system. For example, to embed Python into an 1468application. 1469 1470This configuration ignores global configuration variables, environment 1471variables, command line arguments (:c:member:`PyConfig.argv` is not parsed) 1472and user site directory. The C standard streams (ex: ``stdout``) and the 1473LC_CTYPE locale are left unchanged. Signal handlers are not installed. 1474 1475Configuration files are still used with this configuration to determine 1476paths that are unspecified. Ensure :c:member:`PyConfig.home` is specified 1477to avoid computing the default path configuration. 1478 1479 1480.. _init-python-config: 1481 1482Python Configuration 1483==================== 1484 1485:c:func:`PyPreConfig_InitPythonConfig` and :c:func:`PyConfig_InitPythonConfig` 1486functions create a configuration to build a customized Python which behaves as 1487the regular Python. 1488 1489Environments variables and command line arguments are used to configure 1490Python, whereas global configuration variables are ignored. 1491 1492This function enables C locale coercion (:pep:`538`) 1493and :ref:`Python UTF-8 Mode <utf8-mode>` 1494(:pep:`540`) depending on the LC_CTYPE locale, :envvar:`PYTHONUTF8` and 1495:envvar:`PYTHONCOERCECLOCALE` environment variables. 1496 1497 1498.. _init-path-config: 1499 1500Python Path Configuration 1501========================= 1502 1503:c:type:`PyConfig` contains multiple fields for the path configuration: 1504 1505* Path configuration inputs: 1506 1507 * :c:member:`PyConfig.home` 1508 * :c:member:`PyConfig.platlibdir` 1509 * :c:member:`PyConfig.pathconfig_warnings` 1510 * :c:member:`PyConfig.program_name` 1511 * :c:member:`PyConfig.pythonpath_env` 1512 * current working directory: to get absolute paths 1513 * ``PATH`` environment variable to get the program full path 1514 (from :c:member:`PyConfig.program_name`) 1515 * ``__PYVENV_LAUNCHER__`` environment variable 1516 * (Windows only) Application paths in the registry under 1517 "Software\Python\PythonCore\X.Y\PythonPath" of HKEY_CURRENT_USER and 1518 HKEY_LOCAL_MACHINE (where X.Y is the Python version). 1519 1520* Path configuration output fields: 1521 1522 * :c:member:`PyConfig.base_exec_prefix` 1523 * :c:member:`PyConfig.base_executable` 1524 * :c:member:`PyConfig.base_prefix` 1525 * :c:member:`PyConfig.exec_prefix` 1526 * :c:member:`PyConfig.executable` 1527 * :c:member:`PyConfig.module_search_paths_set`, 1528 :c:member:`PyConfig.module_search_paths` 1529 * :c:member:`PyConfig.prefix` 1530 1531If at least one "output field" is not set, Python calculates the path 1532configuration to fill unset fields. If 1533:c:member:`~PyConfig.module_search_paths_set` is equal to ``0``, 1534:c:member:`~PyConfig.module_search_paths` is overridden and 1535:c:member:`~PyConfig.module_search_paths_set` is set to ``1``. 1536 1537It is possible to completely ignore the function calculating the default 1538path configuration by setting explicitly all path configuration output 1539fields listed above. A string is considered as set even if it is non-empty. 1540``module_search_paths`` is considered as set if 1541``module_search_paths_set`` is set to ``1``. In this case, 1542``module_search_paths`` will be used without modification. 1543 1544Set :c:member:`~PyConfig.pathconfig_warnings` to ``0`` to suppress warnings when 1545calculating the path configuration (Unix only, Windows does not log any warning). 1546 1547If :c:member:`~PyConfig.base_prefix` or :c:member:`~PyConfig.base_exec_prefix` 1548fields are not set, they inherit their value from :c:member:`~PyConfig.prefix` 1549and :c:member:`~PyConfig.exec_prefix` respectively. 1550 1551:c:func:`Py_RunMain` and :c:func:`Py_Main` modify :data:`sys.path`: 1552 1553* If :c:member:`~PyConfig.run_filename` is set and is a directory which contains a 1554 ``__main__.py`` script, prepend :c:member:`~PyConfig.run_filename` to 1555 :data:`sys.path`. 1556* If :c:member:`~PyConfig.isolated` is zero: 1557 1558 * If :c:member:`~PyConfig.run_module` is set, prepend the current directory 1559 to :data:`sys.path`. Do nothing if the current directory cannot be read. 1560 * If :c:member:`~PyConfig.run_filename` is set, prepend the directory of the 1561 filename to :data:`sys.path`. 1562 * Otherwise, prepend an empty string to :data:`sys.path`. 1563 1564If :c:member:`~PyConfig.site_import` is non-zero, :data:`sys.path` can be 1565modified by the :mod:`site` module. If 1566:c:member:`~PyConfig.user_site_directory` is non-zero and the user's 1567site-package directory exists, the :mod:`site` module appends the user's 1568site-package directory to :data:`sys.path`. 1569 1570The following configuration files are used by the path configuration: 1571 1572* ``pyvenv.cfg`` 1573* ``._pth`` file (ex: ``python._pth``) 1574* ``pybuilddir.txt`` (Unix only) 1575 1576If a ``._pth`` file is present: 1577 1578* Set :c:member:`~PyConfig.isolated` to ``1``. 1579* Set :c:member:`~PyConfig.use_environment` to ``0``. 1580* Set :c:member:`~PyConfig.site_import` to ``0``. 1581* Set :c:member:`~PyConfig.safe_path` to ``1``. 1582 1583The ``__PYVENV_LAUNCHER__`` environment variable is used to set 1584:c:member:`PyConfig.base_executable`. 1585 1586 1587Py_GetArgcArgv() 1588================ 1589 1590.. c:function:: void Py_GetArgcArgv(int *argc, wchar_t ***argv) 1591 1592 Get the original command line arguments, before Python modified them. 1593 1594 See also :c:member:`PyConfig.orig_argv` member. 1595 1596 1597Multi-Phase Initialization Private Provisional API 1598================================================== 1599 1600This section is a private provisional API introducing multi-phase 1601initialization, the core feature of :pep:`432`: 1602 1603* "Core" initialization phase, "bare minimum Python": 1604 1605 * Builtin types; 1606 * Builtin exceptions; 1607 * Builtin and frozen modules; 1608 * The :mod:`sys` module is only partially initialized 1609 (ex: :data:`sys.path` doesn't exist yet). 1610 1611* "Main" initialization phase, Python is fully initialized: 1612 1613 * Install and configure :mod:`importlib`; 1614 * Apply the :ref:`Path Configuration <init-path-config>`; 1615 * Install signal handlers; 1616 * Finish :mod:`sys` module initialization (ex: create :data:`sys.stdout` 1617 and :data:`sys.path`); 1618 * Enable optional features like :mod:`faulthandler` and :mod:`tracemalloc`; 1619 * Import the :mod:`site` module; 1620 * etc. 1621 1622Private provisional API: 1623 1624* :c:member:`PyConfig._init_main`: if set to ``0``, 1625 :c:func:`Py_InitializeFromConfig` stops at the "Core" initialization phase. 1626 1627.. c:function:: PyStatus _Py_InitializeMain(void) 1628 1629 Move to the "Main" initialization phase, finish the Python initialization. 1630 1631No module is imported during the "Core" phase and the ``importlib`` module is 1632not configured: the :ref:`Path Configuration <init-path-config>` is only 1633applied during the "Main" phase. It may allow to customize Python in Python to 1634override or tune the :ref:`Path Configuration <init-path-config>`, maybe 1635install a custom :data:`sys.meta_path` importer or an import hook, etc. 1636 1637It may become possible to calculate the :ref:`Path Configuration 1638<init-path-config>` in Python, after the Core phase and before the Main phase, 1639which is one of the :pep:`432` motivation. 1640 1641The "Core" phase is not properly defined: what should be and what should 1642not be available at this phase is not specified yet. The API is marked 1643as private and provisional: the API can be modified or even be removed 1644anytime until a proper public API is designed. 1645 1646Example running Python code between "Core" and "Main" initialization 1647phases:: 1648 1649 void init_python(void) 1650 { 1651 PyStatus status; 1652 1653 PyConfig config; 1654 PyConfig_InitPythonConfig(&config); 1655 config._init_main = 0; 1656 1657 /* ... customize 'config' configuration ... */ 1658 1659 status = Py_InitializeFromConfig(&config); 1660 PyConfig_Clear(&config); 1661 if (PyStatus_Exception(status)) { 1662 Py_ExitStatusException(status); 1663 } 1664 1665 /* Use sys.stderr because sys.stdout is only created 1666 by _Py_InitializeMain() */ 1667 int res = PyRun_SimpleString( 1668 "import sys; " 1669 "print('Run Python code before _Py_InitializeMain', " 1670 "file=sys.stderr)"); 1671 if (res < 0) { 1672 exit(1); 1673 } 1674 1675 /* ... put more configuration code here ... */ 1676 1677 status = _Py_InitializeMain(); 1678 if (PyStatus_Exception(status)) { 1679 Py_ExitStatusException(status); 1680 } 1681 } 1682