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