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