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