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