blob: c198df3fb1d083e5d526c3f9daaf9a8982ee28fd [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
Victor Stinner1beb7c32019-08-23 17:59:12 +010051See 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
Victor Stinner3842f292019-08-23 16:57:54 +010077 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
Victor Stinner36242fd2019-07-01 19:13:50 +0200378 .. 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
428 .. c:member:: wchar_t* base_prefix
429
430 :data:`sys.base_prefix`.
431
432 .. c:member:: int buffered_stdio
433
434 If equals to 0, enable unbuffered mode, making the stdout and stderr
435 streams unbuffered.
436
437 stdin is always opened in buffered mode.
438
439 .. c:member:: int bytes_warning
440
441 If equals to 1, issue a warning when comparing :class:`bytes` or
442 :class:`bytearray` with :class:`str`, or comparing :class:`bytes` with
443 :class:`int`. If equal or greater to 2, raise a :exc:`BytesWarning`
444 exception.
445
446 .. c:member:: wchar_t* check_hash_pycs_mode
447
448 Control the validation behavior of hash-based ``.pyc`` files (see
449 :pep:`552`): :option:`--check-hash-based-pycs` command line option value.
450
451 Valid values: ``always``, ``never`` and ``default``.
452
453 The default value is: ``default``.
454
455 .. c:member:: int configure_c_stdio
456
457 If non-zero, configure C standard streams (``stdio``, ``stdout``,
458 ``stdout``). For example, set their mode to ``O_BINARY`` on Windows.
459
460 .. c:member:: int dev_mode
461
462 Development mode: see :option:`-X` ``dev``.
463
464 .. c:member:: int dump_refs
465
466 If non-zero, dump all objects which are still alive at exit.
467
468 Require a debug build of Python (``Py_REF_DEBUG`` macro must be defined).
469
470 .. c:member:: wchar_t* exec_prefix
471
472 :data:`sys.exec_prefix`.
473
474 .. c:member:: wchar_t* executable
475
476 :data:`sys.executable`.
477
478 .. c:member:: int faulthandler
479
480 If non-zero, call :func:`faulthandler.enable`.
481
482 .. c:member:: wchar_t* filesystem_encoding
483
484 Filesystem encoding, :func:`sys.getfilesystemencoding`.
485
486 .. c:member:: wchar_t* filesystem_errors
487
488 Filesystem encoding errors, :func:`sys.getfilesystemencodeerrors`.
489
490 .. c:member:: unsigned long hash_seed
491 .. c:member:: int use_hash_seed
492
493 Randomized hash function seed.
494
495 If :c:member:`~PyConfig.use_hash_seed` is zero, a seed is chosen randomly
496 at Pythonstartup, and :c:member:`~PyConfig.hash_seed` is ignored.
497
498 .. c:member:: wchar_t* home
499
500 Python home directory.
501
502 .. c:member:: int import_time
503
504 If non-zero, profile import time.
505
506 .. c:member:: int inspect
507
508 Enter interactive mode after executing a script or a command.
509
510 .. c:member:: int install_signal_handlers
511
512 Install signal handlers?
513
514 .. c:member:: int interactive
515
516 Interactive mode.
517
518 .. c:member:: int isolated
519
520 If greater than 0, enable isolated mode:
521
522 * :data:`sys.path` contains neither the script's directory (computed from
523 ``argv[0]`` or the current directory) nor the user's site-packages
524 directory.
525 * Python REPL doesn't import :mod:`readline` nor enable default readline
526 configuration on interactive prompts.
527 * Set :c:member:`~PyConfig.use_environment` and
528 :c:member:`~PyConfig.user_site_directory` to 0.
529
530 .. c:member:: int legacy_windows_stdio
531
532 If non-zero, use :class:`io.FileIO` instead of
533 :class:`io.WindowsConsoleIO` for :data:`sys.stdin`, :data:`sys.stdout`
534 and :data:`sys.stderr`.
535
536 Only available on Windows. ``#ifdef MS_WINDOWS`` macro can be used for
537 Windows specific code.
538
539 .. c:member:: int malloc_stats
540
541 If non-zero, dump statistics on :ref:`Python pymalloc memory allocator
542 <pymalloc>` at exit.
543
544 The option is ignored if Python is built using ``--without-pymalloc``.
545
546 .. c:member:: wchar_t* pythonpath_env
547
548 Module search paths as a string separated by ``DELIM``
549 (:data:`os.path.pathsep`).
550
551 Initialized from :envvar:`PYTHONPATH` environment variable value by
552 default.
553
554 .. c:member:: PyWideStringList module_search_paths
555 .. c:member:: int module_search_paths_set
556
557 :data:`sys.path`. If :c:member:`~PyConfig.module_search_paths_set` is
558 equal to 0, the :c:member:`~PyConfig.module_search_paths` is overridden
559 by the function computing the :ref:`Path Configuration
560 <init-path-config>`.
561
562 .. c:member:: int optimization_level
563
564 Compilation optimization level:
565
566 * 0: Peephole optimizer (and ``__debug__`` is set to ``True``)
567 * 1: Remove assertions, set ``__debug__`` to ``False``
568 * 2: Strip docstrings
569
570 .. c:member:: int parse_argv
571
572 If non-zero, parse :c:member:`~PyConfig.argv` the same way the regular
573 Python command line arguments, and strip Python arguments from
574 :c:member:`~PyConfig.argv`: see :ref:`Command Line Arguments
575 <using-on-cmdline>`.
576
577 .. c:member:: int parser_debug
578
579 If non-zero, turn on parser debugging output (for expert only, depending
580 on compilation options).
581
582 .. c:member:: int pathconfig_warnings
583
584 If equal to 0, suppress warnings when computing the path configuration
585 (Unix only, Windows does not log any warning). Otherwise, warnings are
586 written into ``stderr``.
587
588 .. c:member:: wchar_t* prefix
589
590 :data:`sys.prefix`.
591
592 .. c:member:: wchar_t* program_name
593
594 Program name.
595
596 .. c:member:: wchar_t* pycache_prefix
597
598 ``.pyc`` cache prefix.
599
600 .. c:member:: int quiet
601
602 Quiet mode. For example, don't display the copyright and version messages
603 even in interactive mode.
604
605 .. c:member:: wchar_t* run_command
606
607 ``python3 -c COMMAND`` argument.
608
609 .. c:member:: wchar_t* run_filename
610
611 ``python3 FILENAME`` argument.
612
613 .. c:member:: wchar_t* run_module
614
615 ``python3 -m MODULE`` argument.
616
617 .. c:member:: int show_alloc_count
618
619 Show allocation counts at exit?
620
621 Need a special Python build with ``COUNT_ALLOCS`` macro defined.
622
623 .. c:member:: int show_ref_count
624
625 Show total reference count at exit?
626
627 Need a debug build of Python (``Py_REF_DEBUG`` macro must be defined).
628
629 .. c:member:: int site_import
630
631 Import the :mod:`site` module at startup?
632
633 .. c:member:: int skip_source_first_line
634
635 Skip the first line of the source?
636
637 .. c:member:: wchar_t* stdio_encoding
638 .. c:member:: wchar_t* stdio_errors
639
640 Encoding and encoding errors of :data:`sys.stdin`, :data:`sys.stdout` and
641 :data:`sys.stderr`.
642
643 .. c:member:: int tracemalloc
644
645 If non-zero, call :func:`tracemalloc.start`.
646
647 .. c:member:: int use_environment
648
649 If greater than 0, use :ref:`environment variables <using-on-envvars>`.
650
651 .. c:member:: int user_site_directory
652
653 If non-zero, add user site directory to :data:`sys.path`.
654
655 .. c:member:: int verbose
656
657 If non-zero, enable verbose mode.
658
659 .. c:member:: PyWideStringList warnoptions
660
661 Options of the :mod:`warnings` module to build warnings filters.
662
663 .. c:member:: int write_bytecode
664
665 If non-zero, write ``.pyc`` files.
666
667 .. c:member:: PyWideStringList xoptions
668
669 :data:`sys._xoptions`.
670
671If ``parse_argv`` is non-zero, ``argv`` arguments are parsed the same
672way the regular Python parses command line arguments, and Python
673arguments are stripped from ``argv``: see :ref:`Command Line Arguments
674<using-on-cmdline>`.
675
676The ``xoptions`` options are parsed to set other options: see :option:`-X`
677option.
678
679
680Initialization with PyConfig
681----------------------------
682
683Function to initialize Python:
684
685.. c:function:: PyStatus Py_InitializeFromConfig(const PyConfig *config)
686
687 Initialize Python from *config* configuration.
688
689The caller is responsible to handle exceptions (error or exit) using
690:c:func:`PyStatus_Exception` and :c:func:`Py_ExitStatusException`.
691
692``PyImport_FrozenModules``, ``PyImport_AppendInittab()`` or
693``PyImport_ExtendInittab()`` is used: they must be set or called after Python
694preinitialization and before the Python initialization.
695
696Example setting the program name::
697
698 void init_python(void)
699 {
700 PyStatus status;
701 PyConfig config;
702
703 status = PyConfig_InitPythonConfig(&config);
704 if (PyStatus_Exception(status)) {
705 goto fail;
706 }
707
708 /* Set the program name. Implicitly preinitialize Python. */
709 status = PyConfig_SetString(&config, &config.program_name,
710 L"/path/to/my_program");
711 if (PyStatus_Exception(status)) {
712 goto fail;
713 }
714
715 status = Py_InitializeFromConfig(&config);
716 if (PyStatus_Exception(status)) {
717 goto fail;
718 }
719 PyConfig_Clear(&config);
720 return;
721
722 fail:
723 PyConfig_Clear(&config);
724 Py_ExitStatusException(status);
725 }
726
727More complete example modifying the default configuration, read the
728configuration, and then override some parameters::
729
730 PyStatus init_python(const char *program_name)
731 {
732 PyStatus status;
733 PyConfig config;
734
735 status = PyConfig_InitPythonConfig(&config);
736 if (PyStatus_Exception(status)) {
737 goto done;
738 }
739
740 /* Set the program name before reading the configuraton
741 (decode byte string from the locale encoding).
742
743 Implicitly preinitialize Python. */
744 status = PyConfig_SetBytesString(&config, &config.program_name,
745 program_name);
746 if (PyStatus_Exception(status)) {
747 goto done;
748 }
749
750 /* Read all configuration at once */
751 status = PyConfig_Read(&config);
752 if (PyStatus_Exception(status)) {
753 goto done;
754 }
755
756 /* Append our custom search path to sys.path */
757 status = PyWideStringList_Append(&config.module_search_paths,
758 L"/path/to/more/modules");
759 if (PyStatus_Exception(status)) {
760 goto done;
761 }
762
763 /* Override executable computed by PyConfig_Read() */
764 status = PyConfig_SetString(&config, &config.executable,
765 L"/path/to/my_executable");
766 if (PyStatus_Exception(status)) {
767 goto done;
768 }
769
770 status = Py_InitializeFromConfig(&config);
771
772 done:
773 PyConfig_Clear(&config);
774 return status;
775 }
776
777
778.. _init-isolated-conf:
779
780Isolated Configuration
781----------------------
782
783:c:func:`PyPreConfig_InitIsolatedConfig` and
784:c:func:`PyConfig_InitIsolatedConfig` functions create a configuration to
785isolate Python from the system. For example, to embed Python into an
786application.
787
788This configuration ignores global configuration variables, environments
789variables and command line arguments (:c:member:`PyConfig.argv` is not parsed).
790The C standard streams (ex: ``stdout``) and the LC_CTYPE locale are left
791unchanged by default.
792
793Configuration files are still used with this configuration. Set the
794:ref:`Path Configuration <init-path-config>` ("output fields") to ignore these
795configuration files and avoid the function computing the default path
796configuration.
797
798
799.. _init-python-config:
800
801Python Configuration
802--------------------
803
804:c:func:`PyPreConfig_InitPythonConfig` and :c:func:`PyConfig_InitPythonConfig`
805functions create a configuration to build a customized Python which behaves as
806the regular Python.
807
808Environments variables and command line arguments are used to configure
809Python, whereas global configuration variables are ignored.
810
811This function enables C locale coercion (:pep:`538`) and UTF-8 Mode
812(:pep:`540`) depending on the LC_CTYPE locale, :envvar:`PYTHONUTF8` and
813:envvar:`PYTHONCOERCECLOCALE` environment variables.
814
815Example of customized Python always running in isolated mode::
816
817 int main(int argc, char **argv)
818 {
819 PyConfig config;
820 PyStatus status;
821
822 status = PyConfig_InitPythonConfig(&config);
823 if (PyStatus_Exception(status)) {
824 goto fail;
825 }
826
827 config.isolated = 1;
828
829 /* Decode command line arguments.
830 Implicitly preinitialize Python (in isolated mode). */
831 status = PyConfig_SetBytesArgv(&config, argc, argv);
832 if (PyStatus_Exception(status)) {
833 goto fail;
834 }
835
836 status = Py_InitializeFromConfig(&config);
837 if (PyStatus_Exception(status)) {
838 goto fail;
839 }
840 PyConfig_Clear(&config);
841
842 return Py_RunMain();
843
844 fail:
845 PyConfig_Clear(&config);
846 if (PyStatus_IsExit(status)) {
847 return status.exitcode;
848 }
849 /* Display the error message and exit the process with
850 non-zero exit code */
851 Py_ExitStatusException(status);
852 }
853
854
855.. _init-path-config:
856
857Path Configuration
858------------------
859
860:c:type:`PyConfig` contains multiple fields for the path configuration:
861
862* Path configuration input fields:
863
864 * :c:member:`PyConfig.home`
865 * :c:member:`PyConfig.pythonpath_env`
866 * :c:member:`PyConfig.pathconfig_warnings`
867
868* Path configuration output fields:
869
870 * :c:member:`PyConfig.exec_prefix`
871 * :c:member:`PyConfig.executable`
872 * :c:member:`PyConfig.prefix`
873 * :c:member:`PyConfig.module_search_paths_set`,
874 :c:member:`PyConfig.module_search_paths`
875
876If at least one "output field" is not set, Python computes the path
877configuration to fill unset fields. If
878:c:member:`~PyConfig.module_search_paths_set` is equal to 0,
Min ho Kim39d87b52019-08-31 06:21:19 +1000879:c:member:`~PyConfig.module_search_paths` is overridden and
Victor Stinner331a6a52019-05-27 16:39:22 +0200880:c:member:`~PyConfig.module_search_paths_set` is set to 1.
881
882It is possible to completely ignore the function computing the default
883path configuration by setting explicitly all path configuration output
884fields listed above. A string is considered as set even if it is non-empty.
885``module_search_paths`` is considered as set if
886``module_search_paths_set`` is set to 1. In this case, path
887configuration input fields are ignored as well.
888
889Set :c:member:`~PyConfig.pathconfig_warnings` to 0 to suppress warnings when
890computing the path configuration (Unix only, Windows does not log any warning).
891
892If :c:member:`~PyConfig.base_prefix` or :c:member:`~PyConfig.base_exec_prefix`
893fields are not set, they inherit their value from :c:member:`~PyConfig.prefix`
894and :c:member:`~PyConfig.exec_prefix` respectively.
895
896:c:func:`Py_RunMain` and :c:func:`Py_Main` modify :data:`sys.path`:
897
898* If :c:member:`~PyConfig.run_filename` is set and is a directory which contains a
899 ``__main__.py`` script, prepend :c:member:`~PyConfig.run_filename` to
900 :data:`sys.path`.
901* If :c:member:`~PyConfig.isolated` is zero:
902
903 * If :c:member:`~PyConfig.run_module` is set, prepend the current directory
904 to :data:`sys.path`. Do nothing if the current directory cannot be read.
905 * If :c:member:`~PyConfig.run_filename` is set, prepend the directory of the
906 filename to :data:`sys.path`.
907 * Otherwise, prepend an empty string to :data:`sys.path`.
908
909If :c:member:`~PyConfig.site_import` is non-zero, :data:`sys.path` can be
910modified by the :mod:`site` module. If
911:c:member:`~PyConfig.user_site_directory` is non-zero and the user's
912site-package directory exists, the :mod:`site` module appends the user's
913site-package directory to :data:`sys.path`.
914
915The following configuration files are used by the path configuration:
916
917* ``pyvenv.cfg``
918* ``python._pth`` (Windows only)
919* ``pybuilddir.txt`` (Unix only)
920
921
922Py_RunMain()
923------------
924
925.. c:function:: int Py_RunMain(void)
926
927 Execute the command (:c:member:`PyConfig.run_command`), the script
928 (:c:member:`PyConfig.run_filename`) or the module
929 (:c:member:`PyConfig.run_module`) specified on the command line or in the
930 configuration.
931
932 By default and when if :option:`-i` option is used, run the REPL.
933
934 Finally, finalizes Python and returns an exit status that can be passed to
935 the ``exit()`` function.
936
937See :ref:`Python Configuration <init-python-config>` for an example of
938customized Python always running in isolated mode using
939:c:func:`Py_RunMain`.
940
941
942Multi-Phase Initialization Private Provisional API
943--------------------------------------------------
944
945This section is a private provisional API introducing multi-phase
946initialization, the core feature of the :pep:`432`:
947
948* "Core" initialization phase, "bare minimum Python":
949
950 * Builtin types;
951 * Builtin exceptions;
952 * Builtin and frozen modules;
953 * The :mod:`sys` module is only partially initialized
954 (ex: :data:`sys.path` doesn't exist yet);
955
956* "Main" initialization phase, Python is fully initialized:
957
958 * Install and configure :mod:`importlib`;
959 * Apply the :ref:`Path Configuration <init-path-config>`;
960 * Install signal handlers;
961 * Finish :mod:`sys` module initialization (ex: create :data:`sys.stdout`
962 and :data:`sys.path`);
963 * Enable optional features like :mod:`faulthandler` and :mod:`tracemalloc`;
964 * Import the :mod:`site` module;
965 * etc.
966
967Private provisional API:
968
969* :c:member:`PyConfig._init_main`: if set to 0,
970 :c:func:`Py_InitializeFromConfig` stops at the "Core" initialization phase.
971
972.. c:function:: PyStatus _Py_InitializeMain(void)
973
974 Move to the "Main" initialization phase, finish the Python initialization.
975
976No module is imported during the "Core" phase and the ``importlib`` module is
977not configured: the :ref:`Path Configuration <init-path-config>` is only
978applied during the "Main" phase. It may allow to customize Python in Python to
979override or tune the :ref:`Path Configuration <init-path-config>`, maybe
980install a custom sys.meta_path importer or an import hook, etc.
981
982It may become possible to compute the :ref:`Path Configuration
983<init-path-config>` in Python, after the Core phase and before the Main phase,
984which is one of the :pep:`432` motivation.
985
986The "Core" phase is not properly defined: what should be and what should
987not be available at this phase is not specified yet. The API is marked
988as private and provisional: the API can be modified or even be removed
989anytime until a proper public API is designed.
990
991Example running Python code between "Core" and "Main" initialization
992phases::
993
994 void init_python(void)
995 {
996 PyStatus status;
997 PyConfig config;
998
999 status = PyConfig_InitPythonConfig(&config);
1000 if (PyStatus_Exception(status)) {
1001 PyConfig_Clear(&config);
1002 Py_ExitStatusException(status);
1003 }
1004
1005 config._init_main = 0;
1006
1007 /* ... customize 'config' configuration ... */
1008
1009 status = Py_InitializeFromConfig(&config);
1010 PyConfig_Clear(&config);
1011 if (PyStatus_Exception(status)) {
1012 Py_ExitStatusException(status);
1013 }
1014
1015 /* Use sys.stderr because sys.stdout is only created
1016 by _Py_InitializeMain() */
1017 int res = PyRun_SimpleString(
1018 "import sys; "
1019 "print('Run Python code before _Py_InitializeMain', "
1020 "file=sys.stderr)");
1021 if (res < 0) {
1022 exit(1);
1023 }
1024
1025 /* ... put more configuration code here ... */
1026
1027 status = _Py_InitializeMain();
1028 if (PyStatus_Exception(status)) {
1029 Py_ExitStatusException(status);
1030 }
1031 }