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