blob: 84064d93ea3b145d5644a4099f2a25e0488d42d4 [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`
Victor Stinnere81f6e62020-06-08 18:12:59 +020046* :c:func:`Py_GetArgcArgv`
Victor Stinner331a6a52019-05-27 16:39:22 +020047
48The preconfiguration (``PyPreConfig`` type) is stored in
49``_PyRuntime.preconfig`` and the configuration (``PyConfig`` type) is stored in
50``PyInterpreterState.config``.
51
Victor Stinner1beb7c32019-08-23 17:59:12 +010052See also :ref:`Initialization, Finalization, and Threads <initialization>`.
53
Victor Stinner331a6a52019-05-27 16:39:22 +020054.. seealso::
55 :pep:`587` "Python Initialization Configuration".
56
57
58PyWideStringList
59----------------
60
61.. c:type:: PyWideStringList
62
63 List of ``wchar_t*`` strings.
64
Serhiy Storchakae835b312019-10-30 21:37:16 +020065 If *length* is non-zero, *items* must be non-``NULL`` and all strings must be
66 non-``NULL``.
Victor Stinner331a6a52019-05-27 16:39:22 +020067
68 Methods:
69
70 .. c:function:: PyStatus PyWideStringList_Append(PyWideStringList *list, const wchar_t *item)
71
72 Append *item* to *list*.
73
74 Python must be preinitialized to call this function.
75
76 .. c:function:: PyStatus PyWideStringList_Insert(PyWideStringList *list, Py_ssize_t index, const wchar_t *item)
77
Victor Stinner3842f292019-08-23 16:57:54 +010078 Insert *item* into *list* at *index*.
79
80 If *index* is greater than or equal to *list* length, append *item* to
81 *list*.
82
83 *index* must be greater than or equal to 0.
Victor Stinner331a6a52019-05-27 16:39:22 +020084
85 Python must be preinitialized to call this function.
86
87 Structure fields:
88
89 .. c:member:: Py_ssize_t length
90
91 List length.
92
93 .. c:member:: wchar_t** items
94
95 List items.
96
97PyStatus
98--------
99
100.. c:type:: PyStatus
101
102 Structure to store an initialization function status: success, error
103 or exit.
104
105 For an error, it can store the C function name which created the error.
106
107 Structure fields:
108
109 .. c:member:: int exitcode
110
111 Exit code. Argument passed to ``exit()``.
112
113 .. c:member:: const char *err_msg
114
115 Error message.
116
117 .. c:member:: const char *func
118
119 Name of the function which created an error, can be ``NULL``.
120
121 Functions to create a status:
122
123 .. c:function:: PyStatus PyStatus_Ok(void)
124
125 Success.
126
127 .. c:function:: PyStatus PyStatus_Error(const char *err_msg)
128
129 Initialization error with a message.
130
131 .. c:function:: PyStatus PyStatus_NoMemory(void)
132
133 Memory allocation failure (out of memory).
134
135 .. c:function:: PyStatus PyStatus_Exit(int exitcode)
136
137 Exit Python with the specified exit code.
138
139 Functions to handle a status:
140
141 .. c:function:: int PyStatus_Exception(PyStatus status)
142
143 Is the status an error or an exit? If true, the exception must be
144 handled; by calling :c:func:`Py_ExitStatusException` for example.
145
146 .. c:function:: int PyStatus_IsError(PyStatus status)
147
148 Is the result an error?
149
150 .. c:function:: int PyStatus_IsExit(PyStatus status)
151
152 Is the result an exit?
153
154 .. c:function:: void Py_ExitStatusException(PyStatus status)
155
156 Call ``exit(exitcode)`` if *status* is an exit. Print the error
157 message and exit with a non-zero exit code if *status* is an error. Must
158 only be called if ``PyStatus_Exception(status)`` is non-zero.
159
160.. note::
161 Internally, Python uses macros which set ``PyStatus.func``,
162 whereas functions to create a status set ``func`` to ``NULL``.
163
164Example::
165
166 PyStatus alloc(void **ptr, size_t size)
167 {
168 *ptr = PyMem_RawMalloc(size);
169 if (*ptr == NULL) {
170 return PyStatus_NoMemory();
171 }
172 return PyStatus_Ok();
173 }
174
175 int main(int argc, char **argv)
176 {
177 void *ptr;
178 PyStatus status = alloc(&ptr, 16);
179 if (PyStatus_Exception(status)) {
180 Py_ExitStatusException(status);
181 }
182 PyMem_Free(ptr);
183 return 0;
184 }
185
186
187PyPreConfig
188-----------
189
190.. c:type:: PyPreConfig
191
192 Structure used to preinitialize Python:
193
194 * Set the Python memory allocator
195 * Configure the LC_CTYPE locale
196 * Set the UTF-8 mode
197
198 Function to initialize a preconfiguration:
199
Victor Stinner3c30a762019-10-01 10:56:37 +0200200 .. c:function:: void PyPreConfig_InitIsolatedConfig(PyPreConfig *preconfig)
Victor Stinner331a6a52019-05-27 16:39:22 +0200201
202 Initialize the preconfiguration with :ref:`Python Configuration
203 <init-python-config>`.
204
Victor Stinner3c30a762019-10-01 10:56:37 +0200205 .. c:function:: void PyPreConfig_InitPythonConfig(PyPreConfig *preconfig)
Victor Stinner331a6a52019-05-27 16:39:22 +0200206
207 Initialize the preconfiguration with :ref:`Isolated Configuration
208 <init-isolated-conf>`.
209
210 Structure fields:
211
212 .. c:member:: int allocator
213
214 Name of the memory allocator:
215
216 * ``PYMEM_ALLOCATOR_NOT_SET`` (``0``): don't change memory allocators
217 (use defaults)
218 * ``PYMEM_ALLOCATOR_DEFAULT`` (``1``): default memory allocators
219 * ``PYMEM_ALLOCATOR_DEBUG`` (``2``): default memory allocators with
220 debug hooks
221 * ``PYMEM_ALLOCATOR_MALLOC`` (``3``): force usage of ``malloc()``
222 * ``PYMEM_ALLOCATOR_MALLOC_DEBUG`` (``4``): force usage of
223 ``malloc()`` with debug hooks
224 * ``PYMEM_ALLOCATOR_PYMALLOC`` (``5``): :ref:`Python pymalloc memory
225 allocator <pymalloc>`
226 * ``PYMEM_ALLOCATOR_PYMALLOC_DEBUG`` (``6``): :ref:`Python pymalloc
227 memory allocator <pymalloc>` with debug hooks
228
229 ``PYMEM_ALLOCATOR_PYMALLOC`` and ``PYMEM_ALLOCATOR_PYMALLOC_DEBUG``
230 are not supported if Python is configured using ``--without-pymalloc``
231
232 See :ref:`Memory Management <memory>`.
233
234 .. c:member:: int configure_locale
235
236 Set the LC_CTYPE locale to the user preferred locale? If equals to 0, set
237 :c:member:`coerce_c_locale` and :c:member:`coerce_c_locale_warn` to 0.
238
239 .. c:member:: int coerce_c_locale
240
241 If equals to 2, coerce the C locale; if equals to 1, read the LC_CTYPE
242 locale to decide if it should be coerced.
243
244 .. c:member:: int coerce_c_locale_warn
Victor Stinner88feaec2019-09-26 03:15:07 +0200245
Victor Stinner331a6a52019-05-27 16:39:22 +0200246 If non-zero, emit a warning if the C locale is coerced.
247
248 .. c:member:: int dev_mode
249
250 See :c:member:`PyConfig.dev_mode`.
251
252 .. c:member:: int isolated
253
254 See :c:member:`PyConfig.isolated`.
255
256 .. c:member:: int legacy_windows_fs_encoding (Windows only)
257
258 If non-zero, disable UTF-8 Mode, set the Python filesystem encoding to
259 ``mbcs``, set the filesystem error handler to ``replace``.
260
261 Only available on Windows. ``#ifdef MS_WINDOWS`` macro can be used for
262 Windows specific code.
263
264 .. c:member:: int parse_argv
265
266 If non-zero, :c:func:`Py_PreInitializeFromArgs` and
267 :c:func:`Py_PreInitializeFromBytesArgs` parse their ``argv`` argument the
268 same way the regular Python parses command line arguments: see
269 :ref:`Command Line Arguments <using-on-cmdline>`.
270
271 .. c:member:: int use_environment
272
273 See :c:member:`PyConfig.use_environment`.
274
275 .. c:member:: int utf8_mode
276
277 If non-zero, enable the UTF-8 mode.
278
279Preinitialization with PyPreConfig
280----------------------------------
281
282Functions to preinitialize Python:
283
284.. c:function:: PyStatus Py_PreInitialize(const PyPreConfig *preconfig)
285
286 Preinitialize Python from *preconfig* preconfiguration.
287
288.. c:function:: PyStatus Py_PreInitializeFromBytesArgs(const PyPreConfig *preconfig, int argc, char * const *argv)
289
290 Preinitialize Python from *preconfig* preconfiguration and command line
291 arguments (bytes strings).
292
293.. c:function:: PyStatus Py_PreInitializeFromArgs(const PyPreConfig *preconfig, int argc, wchar_t * const * argv)
294
295 Preinitialize Python from *preconfig* preconfiguration and command line
296 arguments (wide strings).
297
298The caller is responsible to handle exceptions (error or exit) using
299:c:func:`PyStatus_Exception` and :c:func:`Py_ExitStatusException`.
300
301For :ref:`Python Configuration <init-python-config>`
302(:c:func:`PyPreConfig_InitPythonConfig`), if Python is initialized with
303command line arguments, the command line arguments must also be passed to
304preinitialize Python, since they have an effect on the pre-configuration
Victor Stinner88feaec2019-09-26 03:15:07 +0200305like encodings. For example, the :option:`-X utf8 <-X>` command line option
Victor Stinner331a6a52019-05-27 16:39:22 +0200306enables the UTF-8 Mode.
307
308``PyMem_SetAllocator()`` can be called after :c:func:`Py_PreInitialize` and
309before :c:func:`Py_InitializeFromConfig` to install a custom memory allocator.
310It can be called before :c:func:`Py_PreInitialize` if
311:c:member:`PyPreConfig.allocator` is set to ``PYMEM_ALLOCATOR_NOT_SET``.
312
313Python memory allocation functions like :c:func:`PyMem_RawMalloc` must not be
314used before Python preinitialization, whereas calling directly ``malloc()`` and
315``free()`` is always safe. :c:func:`Py_DecodeLocale` must not be called before
316the preinitialization.
317
318Example using the preinitialization to enable the UTF-8 Mode::
319
Victor Stinner441b10c2019-09-28 04:28:35 +0200320 PyStatus status;
Victor Stinner331a6a52019-05-27 16:39:22 +0200321 PyPreConfig preconfig;
Victor Stinner3c30a762019-10-01 10:56:37 +0200322 PyPreConfig_InitPythonConfig(&preconfig);
Victor Stinner331a6a52019-05-27 16:39:22 +0200323
324 preconfig.utf8_mode = 1;
325
Victor Stinner441b10c2019-09-28 04:28:35 +0200326 status = Py_PreInitialize(&preconfig);
Victor Stinner331a6a52019-05-27 16:39:22 +0200327 if (PyStatus_Exception(status)) {
328 Py_ExitStatusException(status);
329 }
330
331 /* at this point, Python will speak UTF-8 */
332
333 Py_Initialize();
334 /* ... use Python API here ... */
335 Py_Finalize();
336
337
338PyConfig
339--------
340
341.. c:type:: PyConfig
342
343 Structure containing most parameters to configure Python.
344
345 Structure methods:
346
Victor Stinner8462a492019-10-01 12:06:16 +0200347 .. c:function:: void PyConfig_InitPythonConfig(PyConfig *config)
Victor Stinner331a6a52019-05-27 16:39:22 +0200348
349 Initialize configuration with :ref:`Python Configuration
350 <init-python-config>`.
351
Victor Stinner8462a492019-10-01 12:06:16 +0200352 .. c:function:: void PyConfig_InitIsolatedConfig(PyConfig *config)
Victor Stinner331a6a52019-05-27 16:39:22 +0200353
354 Initialize configuration with :ref:`Isolated Configuration
355 <init-isolated-conf>`.
356
357 .. c:function:: PyStatus PyConfig_SetString(PyConfig *config, wchar_t * const *config_str, const wchar_t *str)
358
359 Copy the wide character string *str* into ``*config_str``.
360
361 Preinitialize Python if needed.
362
363 .. c:function:: PyStatus PyConfig_SetBytesString(PyConfig *config, wchar_t * const *config_str, const char *str)
364
365 Decode *str* using ``Py_DecodeLocale()`` and set the result into ``*config_str``.
366
367 Preinitialize Python if needed.
368
369 .. c:function:: PyStatus PyConfig_SetArgv(PyConfig *config, int argc, wchar_t * const *argv)
370
371 Set command line arguments from wide character strings.
372
373 Preinitialize Python if needed.
374
375 .. c:function:: PyStatus PyConfig_SetBytesArgv(PyConfig *config, int argc, char * const *argv)
376
377 Set command line arguments: decode bytes using :c:func:`Py_DecodeLocale`.
378
379 Preinitialize Python if needed.
380
Victor Stinner36242fd2019-07-01 19:13:50 +0200381 .. c:function:: PyStatus PyConfig_SetWideStringList(PyConfig *config, PyWideStringList *list, Py_ssize_t length, wchar_t **items)
382
383 Set the list of wide strings *list* to *length* and *items*.
384
385 Preinitialize Python if needed.
386
Victor Stinner331a6a52019-05-27 16:39:22 +0200387 .. c:function:: PyStatus PyConfig_Read(PyConfig *config)
388
389 Read all Python configuration.
390
391 Fields which are already initialized are left unchanged.
392
393 Preinitialize Python if needed.
394
395 .. c:function:: void PyConfig_Clear(PyConfig *config)
396
397 Release configuration memory.
398
399 Most ``PyConfig`` methods preinitialize Python if needed. In that case, the
400 Python preinitialization configuration in based on the :c:type:`PyConfig`.
401 If configuration fields which are in common with :c:type:`PyPreConfig` are
402 tuned, they must be set before calling a :c:type:`PyConfig` method:
403
404 * :c:member:`~PyConfig.dev_mode`
405 * :c:member:`~PyConfig.isolated`
406 * :c:member:`~PyConfig.parse_argv`
407 * :c:member:`~PyConfig.use_environment`
408
409 Moreover, if :c:func:`PyConfig_SetArgv` or :c:func:`PyConfig_SetBytesArgv`
410 is used, this method must be called first, before other methods, since the
411 preinitialization configuration depends on command line arguments (if
412 :c:member:`parse_argv` is non-zero).
413
414 The caller of these methods is responsible to handle exceptions (error or
415 exit) using ``PyStatus_Exception()`` and ``Py_ExitStatusException()``.
416
417 Structure fields:
418
419 .. c:member:: PyWideStringList argv
420
421 Command line arguments, :data:`sys.argv`. See
422 :c:member:`~PyConfig.parse_argv` to parse :c:member:`~PyConfig.argv` the
423 same way the regular Python parses Python command line arguments. If
424 :c:member:`~PyConfig.argv` is empty, an empty string is added to ensure
425 that :data:`sys.argv` always exists and is never empty.
426
Victor Stinnerdd8a93e2020-06-30 00:49:03 +0200427 See also the :c:member:`~PyConfig.orig_argv` member.
428
Victor Stinner331a6a52019-05-27 16:39:22 +0200429 .. c:member:: wchar_t* base_exec_prefix
430
431 :data:`sys.base_exec_prefix`.
432
Victor Stinnerfcdb0272019-09-23 14:45:47 +0200433 .. c:member:: wchar_t* base_executable
434
435 :data:`sys._base_executable`: ``__PYVENV_LAUNCHER__`` environment
436 variable value, or copy of :c:member:`PyConfig.executable`.
437
Victor Stinner331a6a52019-05-27 16:39:22 +0200438 .. c:member:: wchar_t* base_prefix
439
440 :data:`sys.base_prefix`.
441
Sandro Mani8f023a22020-06-08 17:28:11 +0200442 .. c:member:: wchar_t* platlibdir
443
444 :data:`sys.platlibdir`: platform library directory name, set at configure time
445 by ``--with-platlibdir``, overrideable by the ``PYTHONPLATLIBDIR``
446 environment variable.
447
Victor Stinner5edb8322020-06-08 20:04:47 +0200448 .. versionadded:: 3.9
Sandro Mani8f023a22020-06-08 17:28:11 +0200449
Victor Stinner331a6a52019-05-27 16:39:22 +0200450 .. c:member:: int buffered_stdio
451
452 If equals to 0, enable unbuffered mode, making the stdout and stderr
453 streams unbuffered.
454
455 stdin is always opened in buffered mode.
456
457 .. c:member:: int bytes_warning
458
459 If equals to 1, issue a warning when comparing :class:`bytes` or
460 :class:`bytearray` with :class:`str`, or comparing :class:`bytes` with
461 :class:`int`. If equal or greater to 2, raise a :exc:`BytesWarning`
462 exception.
463
464 .. c:member:: wchar_t* check_hash_pycs_mode
465
466 Control the validation behavior of hash-based ``.pyc`` files (see
467 :pep:`552`): :option:`--check-hash-based-pycs` command line option value.
468
469 Valid values: ``always``, ``never`` and ``default``.
470
471 The default value is: ``default``.
472
473 .. c:member:: int configure_c_stdio
474
475 If non-zero, configure C standard streams (``stdio``, ``stdout``,
476 ``stdout``). For example, set their mode to ``O_BINARY`` on Windows.
477
478 .. c:member:: int dev_mode
479
Victor Stinnerb9783d22020-01-24 10:22:18 +0100480 If non-zero, enable the :ref:`Python Development Mode <devmode>`.
Victor Stinner331a6a52019-05-27 16:39:22 +0200481
482 .. c:member:: int dump_refs
483
484 If non-zero, dump all objects which are still alive at exit.
485
Hai Shia7847592020-02-17 17:18:19 +0800486 ``Py_TRACE_REFS`` macro must be defined in build.
Victor Stinner331a6a52019-05-27 16:39:22 +0200487
488 .. c:member:: wchar_t* exec_prefix
489
490 :data:`sys.exec_prefix`.
491
492 .. c:member:: wchar_t* executable
493
494 :data:`sys.executable`.
495
496 .. c:member:: int faulthandler
497
Victor Stinner88feaec2019-09-26 03:15:07 +0200498 If non-zero, call :func:`faulthandler.enable` at startup.
Victor Stinner331a6a52019-05-27 16:39:22 +0200499
500 .. c:member:: wchar_t* filesystem_encoding
501
502 Filesystem encoding, :func:`sys.getfilesystemencoding`.
503
504 .. c:member:: wchar_t* filesystem_errors
505
506 Filesystem encoding errors, :func:`sys.getfilesystemencodeerrors`.
507
508 .. c:member:: unsigned long hash_seed
509 .. c:member:: int use_hash_seed
510
511 Randomized hash function seed.
512
513 If :c:member:`~PyConfig.use_hash_seed` is zero, a seed is chosen randomly
514 at Pythonstartup, and :c:member:`~PyConfig.hash_seed` is ignored.
515
516 .. c:member:: wchar_t* home
517
518 Python home directory.
519
Victor Stinner88feaec2019-09-26 03:15:07 +0200520 Initialized from :envvar:`PYTHONHOME` environment variable value by
521 default.
522
Victor Stinner331a6a52019-05-27 16:39:22 +0200523 .. c:member:: int import_time
524
525 If non-zero, profile import time.
526
527 .. c:member:: int inspect
528
529 Enter interactive mode after executing a script or a command.
530
531 .. c:member:: int install_signal_handlers
532
533 Install signal handlers?
534
535 .. c:member:: int interactive
536
537 Interactive mode.
538
539 .. c:member:: int isolated
540
541 If greater than 0, enable isolated mode:
542
543 * :data:`sys.path` contains neither the script's directory (computed from
544 ``argv[0]`` or the current directory) nor the user's site-packages
545 directory.
546 * Python REPL doesn't import :mod:`readline` nor enable default readline
547 configuration on interactive prompts.
548 * Set :c:member:`~PyConfig.use_environment` and
549 :c:member:`~PyConfig.user_site_directory` to 0.
550
551 .. c:member:: int legacy_windows_stdio
552
553 If non-zero, use :class:`io.FileIO` instead of
554 :class:`io.WindowsConsoleIO` for :data:`sys.stdin`, :data:`sys.stdout`
555 and :data:`sys.stderr`.
556
557 Only available on Windows. ``#ifdef MS_WINDOWS`` macro can be used for
558 Windows specific code.
559
560 .. c:member:: int malloc_stats
561
562 If non-zero, dump statistics on :ref:`Python pymalloc memory allocator
563 <pymalloc>` at exit.
564
565 The option is ignored if Python is built using ``--without-pymalloc``.
566
567 .. c:member:: wchar_t* pythonpath_env
568
569 Module search paths as a string separated by ``DELIM``
570 (:data:`os.path.pathsep`).
571
572 Initialized from :envvar:`PYTHONPATH` environment variable value by
573 default.
574
575 .. c:member:: PyWideStringList module_search_paths
576 .. c:member:: int module_search_paths_set
577
578 :data:`sys.path`. If :c:member:`~PyConfig.module_search_paths_set` is
579 equal to 0, the :c:member:`~PyConfig.module_search_paths` is overridden
Victor Stinner88feaec2019-09-26 03:15:07 +0200580 by the function calculating the :ref:`Path Configuration
Victor Stinner331a6a52019-05-27 16:39:22 +0200581 <init-path-config>`.
582
583 .. c:member:: int optimization_level
584
585 Compilation optimization level:
586
587 * 0: Peephole optimizer (and ``__debug__`` is set to ``True``)
588 * 1: Remove assertions, set ``__debug__`` to ``False``
589 * 2: Strip docstrings
590
Victor Stinnerdd8a93e2020-06-30 00:49:03 +0200591 .. c:member:: PyWideStringList orig_argv
592
593 The list of the original command line arguments passed to the Python
594 executable.
595
596 If :c:member:`~PyConfig.orig_argv` list is empty and
597 :c:member:`~PyConfig.argv` is not a list only containing an empty
598 string, :c:func:`PyConfig_Read()` copies :c:member:`~PyConfig.argv` into
599 :c:member:`~PyConfig.orig_argv` before modifying
600 :c:member:`~PyConfig.argv` (if :c:member:`~PyConfig.parse_argv` is
601 non-zero).
602
603 See also the :c:member:`~PyConfig.argv` member and the
604 :c:func:`Py_GetArgcArgv` function.
605
606 .. versionadded:: 3.10
607
Victor Stinner331a6a52019-05-27 16:39:22 +0200608 .. c:member:: int parse_argv
609
610 If non-zero, parse :c:member:`~PyConfig.argv` the same way the regular
611 Python command line arguments, and strip Python arguments from
612 :c:member:`~PyConfig.argv`: see :ref:`Command Line Arguments
613 <using-on-cmdline>`.
614
615 .. c:member:: int parser_debug
616
617 If non-zero, turn on parser debugging output (for expert only, depending
618 on compilation options).
619
620 .. c:member:: int pathconfig_warnings
621
Victor Stinner88feaec2019-09-26 03:15:07 +0200622 If equal to 0, suppress warnings when calculating the :ref:`Path
623 Configuration <init-path-config>` (Unix only, Windows does not log any
624 warning). Otherwise, warnings are written into ``stderr``.
Victor Stinner331a6a52019-05-27 16:39:22 +0200625
626 .. c:member:: wchar_t* prefix
627
628 :data:`sys.prefix`.
629
630 .. c:member:: wchar_t* program_name
631
Victor Stinner88feaec2019-09-26 03:15:07 +0200632 Program name. Used to initialize :c:member:`~PyConfig.executable`, and in
633 early error messages.
Victor Stinner331a6a52019-05-27 16:39:22 +0200634
635 .. c:member:: wchar_t* pycache_prefix
636
Victor Stinner88feaec2019-09-26 03:15:07 +0200637 :data:`sys.pycache_prefix`: ``.pyc`` cache prefix.
638
Serhiy Storchakae835b312019-10-30 21:37:16 +0200639 If ``NULL``, :data:`sys.pycache_prefix` is set to ``None``.
Victor Stinner331a6a52019-05-27 16:39:22 +0200640
641 .. c:member:: int quiet
642
643 Quiet mode. For example, don't display the copyright and version messages
Victor Stinner88feaec2019-09-26 03:15:07 +0200644 in interactive mode.
Victor Stinner331a6a52019-05-27 16:39:22 +0200645
646 .. c:member:: wchar_t* run_command
647
Victor Stinner88feaec2019-09-26 03:15:07 +0200648 ``python3 -c COMMAND`` argument. Used by :c:func:`Py_RunMain`.
Victor Stinner331a6a52019-05-27 16:39:22 +0200649
650 .. c:member:: wchar_t* run_filename
651
Victor Stinner88feaec2019-09-26 03:15:07 +0200652 ``python3 FILENAME`` argument. Used by :c:func:`Py_RunMain`.
Victor Stinner331a6a52019-05-27 16:39:22 +0200653
654 .. c:member:: wchar_t* run_module
655
Victor Stinner88feaec2019-09-26 03:15:07 +0200656 ``python3 -m MODULE`` argument. Used by :c:func:`Py_RunMain`.
Victor Stinner331a6a52019-05-27 16:39:22 +0200657
Victor Stinner331a6a52019-05-27 16:39:22 +0200658 .. c:member:: int show_ref_count
659
660 Show total reference count at exit?
661
Victor Stinner88feaec2019-09-26 03:15:07 +0200662 Set to 1 by :option:`-X showrefcount <-X>` command line option.
663
Victor Stinner331a6a52019-05-27 16:39:22 +0200664 Need a debug build of Python (``Py_REF_DEBUG`` macro must be defined).
665
666 .. c:member:: int site_import
667
668 Import the :mod:`site` module at startup?
669
670 .. c:member:: int skip_source_first_line
671
672 Skip the first line of the source?
673
674 .. c:member:: wchar_t* stdio_encoding
675 .. c:member:: wchar_t* stdio_errors
676
677 Encoding and encoding errors of :data:`sys.stdin`, :data:`sys.stdout` and
678 :data:`sys.stderr`.
679
680 .. c:member:: int tracemalloc
681
Victor Stinner88feaec2019-09-26 03:15:07 +0200682 If non-zero, call :func:`tracemalloc.start` at startup.
Victor Stinner331a6a52019-05-27 16:39:22 +0200683
684 .. c:member:: int use_environment
685
686 If greater than 0, use :ref:`environment variables <using-on-envvars>`.
687
688 .. c:member:: int user_site_directory
689
690 If non-zero, add user site directory to :data:`sys.path`.
691
692 .. c:member:: int verbose
693
694 If non-zero, enable verbose mode.
695
696 .. c:member:: PyWideStringList warnoptions
697
Victor Stinnerfb4ae152019-09-30 01:40:17 +0200698 :data:`sys.warnoptions`: options of the :mod:`warnings` module to build
699 warnings filters: lowest to highest priority.
700
701 The :mod:`warnings` module adds :data:`sys.warnoptions` in the reverse
702 order: the last :c:member:`PyConfig.warnoptions` item becomes the first
703 item of :data:`warnings.filters` which is checked first (highest
704 priority).
Victor Stinner331a6a52019-05-27 16:39:22 +0200705
706 .. c:member:: int write_bytecode
707
708 If non-zero, write ``.pyc`` files.
709
Victor Stinner88feaec2019-09-26 03:15:07 +0200710 :data:`sys.dont_write_bytecode` is initialized to the inverted value of
711 :c:member:`~PyConfig.write_bytecode`.
712
Victor Stinner331a6a52019-05-27 16:39:22 +0200713 .. c:member:: PyWideStringList xoptions
714
715 :data:`sys._xoptions`.
716
717If ``parse_argv`` is non-zero, ``argv`` arguments are parsed the same
718way the regular Python parses command line arguments, and Python
719arguments are stripped from ``argv``: see :ref:`Command Line Arguments
720<using-on-cmdline>`.
721
722The ``xoptions`` options are parsed to set other options: see :option:`-X`
723option.
724
Victor Stinnerc6e5c112020-02-03 15:17:15 +0100725.. versionchanged:: 3.9
726
727 The ``show_alloc_count`` field has been removed.
728
Victor Stinner331a6a52019-05-27 16:39:22 +0200729
730Initialization with PyConfig
731----------------------------
732
733Function to initialize Python:
734
735.. c:function:: PyStatus Py_InitializeFromConfig(const PyConfig *config)
736
737 Initialize Python from *config* configuration.
738
739The caller is responsible to handle exceptions (error or exit) using
740:c:func:`PyStatus_Exception` and :c:func:`Py_ExitStatusException`.
741
Victor Stinner88feaec2019-09-26 03:15:07 +0200742If ``PyImport_FrozenModules``, ``PyImport_AppendInittab()`` or
743``PyImport_ExtendInittab()`` are used, they must be set or called after Python
Victor Stinner331a6a52019-05-27 16:39:22 +0200744preinitialization and before the Python initialization.
745
746Example setting the program name::
747
748 void init_python(void)
749 {
750 PyStatus status;
Victor Stinner331a6a52019-05-27 16:39:22 +0200751
Victor Stinner8462a492019-10-01 12:06:16 +0200752 PyConfig config;
753 PyConfig_InitPythonConfig(&config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200754
755 /* Set the program name. Implicitly preinitialize Python. */
756 status = PyConfig_SetString(&config, &config.program_name,
757 L"/path/to/my_program");
758 if (PyStatus_Exception(status)) {
759 goto fail;
760 }
761
762 status = Py_InitializeFromConfig(&config);
763 if (PyStatus_Exception(status)) {
764 goto fail;
765 }
766 PyConfig_Clear(&config);
767 return;
768
769 fail:
770 PyConfig_Clear(&config);
771 Py_ExitStatusException(status);
772 }
773
774More complete example modifying the default configuration, read the
775configuration, and then override some parameters::
776
777 PyStatus init_python(const char *program_name)
778 {
779 PyStatus status;
Victor Stinner331a6a52019-05-27 16:39:22 +0200780
Victor Stinner8462a492019-10-01 12:06:16 +0200781 PyConfig config;
782 PyConfig_InitPythonConfig(&config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200783
Gurupad Hegde6c7bb382019-12-28 17:16:02 -0500784 /* Set the program name before reading the configuration
Victor Stinner331a6a52019-05-27 16:39:22 +0200785 (decode byte string from the locale encoding).
786
787 Implicitly preinitialize Python. */
788 status = PyConfig_SetBytesString(&config, &config.program_name,
789 program_name);
790 if (PyStatus_Exception(status)) {
791 goto done;
792 }
793
794 /* Read all configuration at once */
795 status = PyConfig_Read(&config);
796 if (PyStatus_Exception(status)) {
797 goto done;
798 }
799
800 /* Append our custom search path to sys.path */
801 status = PyWideStringList_Append(&config.module_search_paths,
Victor Stinner88feaec2019-09-26 03:15:07 +0200802 L"/path/to/more/modules");
Victor Stinner331a6a52019-05-27 16:39:22 +0200803 if (PyStatus_Exception(status)) {
804 goto done;
805 }
806
807 /* Override executable computed by PyConfig_Read() */
808 status = PyConfig_SetString(&config, &config.executable,
809 L"/path/to/my_executable");
810 if (PyStatus_Exception(status)) {
811 goto done;
812 }
813
814 status = Py_InitializeFromConfig(&config);
815
816 done:
817 PyConfig_Clear(&config);
818 return status;
819 }
820
821
822.. _init-isolated-conf:
823
824Isolated Configuration
825----------------------
826
827:c:func:`PyPreConfig_InitIsolatedConfig` and
828:c:func:`PyConfig_InitIsolatedConfig` functions create a configuration to
829isolate Python from the system. For example, to embed Python into an
830application.
831
832This configuration ignores global configuration variables, environments
Victor Stinner88feaec2019-09-26 03:15:07 +0200833variables, command line arguments (:c:member:`PyConfig.argv` is not parsed)
834and user site directory. The C standard streams (ex: ``stdout``) and the
835LC_CTYPE locale are left unchanged. Signal handlers are not installed.
Victor Stinner331a6a52019-05-27 16:39:22 +0200836
837Configuration files are still used with this configuration. Set the
838:ref:`Path Configuration <init-path-config>` ("output fields") to ignore these
839configuration files and avoid the function computing the default path
840configuration.
841
842
843.. _init-python-config:
844
845Python Configuration
846--------------------
847
848:c:func:`PyPreConfig_InitPythonConfig` and :c:func:`PyConfig_InitPythonConfig`
849functions create a configuration to build a customized Python which behaves as
850the regular Python.
851
852Environments variables and command line arguments are used to configure
853Python, whereas global configuration variables are ignored.
854
855This function enables C locale coercion (:pep:`538`) and UTF-8 Mode
856(:pep:`540`) depending on the LC_CTYPE locale, :envvar:`PYTHONUTF8` and
857:envvar:`PYTHONCOERCECLOCALE` environment variables.
858
859Example of customized Python always running in isolated mode::
860
861 int main(int argc, char **argv)
862 {
Victor Stinner331a6a52019-05-27 16:39:22 +0200863 PyStatus status;
Victor Stinner8462a492019-10-01 12:06:16 +0200864
Victor Stinner441b10c2019-09-28 04:28:35 +0200865 PyConfig config;
Victor Stinner8462a492019-10-01 12:06:16 +0200866 PyConfig_InitPythonConfig(&config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200867 config.isolated = 1;
868
869 /* Decode command line arguments.
870 Implicitly preinitialize Python (in isolated mode). */
871 status = PyConfig_SetBytesArgv(&config, argc, argv);
872 if (PyStatus_Exception(status)) {
873 goto fail;
874 }
875
876 status = Py_InitializeFromConfig(&config);
877 if (PyStatus_Exception(status)) {
878 goto fail;
879 }
880 PyConfig_Clear(&config);
881
882 return Py_RunMain();
883
884 fail:
885 PyConfig_Clear(&config);
886 if (PyStatus_IsExit(status)) {
887 return status.exitcode;
888 }
889 /* Display the error message and exit the process with
890 non-zero exit code */
891 Py_ExitStatusException(status);
892 }
893
894
895.. _init-path-config:
896
897Path Configuration
898------------------
899
900:c:type:`PyConfig` contains multiple fields for the path configuration:
901
Victor Stinner8bf39b62019-09-26 02:22:35 +0200902* Path configuration inputs:
Victor Stinner331a6a52019-05-27 16:39:22 +0200903
904 * :c:member:`PyConfig.home`
Sandro Mani8f023a22020-06-08 17:28:11 +0200905 * :c:member:`PyConfig.platlibdir`
Victor Stinner331a6a52019-05-27 16:39:22 +0200906 * :c:member:`PyConfig.pathconfig_warnings`
Victor Stinnerfcdb0272019-09-23 14:45:47 +0200907 * :c:member:`PyConfig.program_name`
908 * :c:member:`PyConfig.pythonpath_env`
Victor Stinner8bf39b62019-09-26 02:22:35 +0200909 * current working directory: to get absolute paths
910 * ``PATH`` environment variable to get the program full path
911 (from :c:member:`PyConfig.program_name`)
912 * ``__PYVENV_LAUNCHER__`` environment variable
913 * (Windows only) Application paths in the registry under
914 "Software\Python\PythonCore\X.Y\PythonPath" of HKEY_CURRENT_USER and
915 HKEY_LOCAL_MACHINE (where X.Y is the Python version).
Victor Stinner331a6a52019-05-27 16:39:22 +0200916
917* Path configuration output fields:
918
Victor Stinner8bf39b62019-09-26 02:22:35 +0200919 * :c:member:`PyConfig.base_exec_prefix`
Victor Stinnerfcdb0272019-09-23 14:45:47 +0200920 * :c:member:`PyConfig.base_executable`
Victor Stinner8bf39b62019-09-26 02:22:35 +0200921 * :c:member:`PyConfig.base_prefix`
Victor Stinner331a6a52019-05-27 16:39:22 +0200922 * :c:member:`PyConfig.exec_prefix`
923 * :c:member:`PyConfig.executable`
Victor Stinner331a6a52019-05-27 16:39:22 +0200924 * :c:member:`PyConfig.module_search_paths_set`,
925 :c:member:`PyConfig.module_search_paths`
Victor Stinner8bf39b62019-09-26 02:22:35 +0200926 * :c:member:`PyConfig.prefix`
Victor Stinner331a6a52019-05-27 16:39:22 +0200927
Victor Stinner8bf39b62019-09-26 02:22:35 +0200928If at least one "output field" is not set, Python calculates the path
Victor Stinner331a6a52019-05-27 16:39:22 +0200929configuration to fill unset fields. If
930:c:member:`~PyConfig.module_search_paths_set` is equal to 0,
Min ho Kim39d87b52019-08-31 06:21:19 +1000931:c:member:`~PyConfig.module_search_paths` is overridden and
Victor Stinner331a6a52019-05-27 16:39:22 +0200932:c:member:`~PyConfig.module_search_paths_set` is set to 1.
933
Victor Stinner8bf39b62019-09-26 02:22:35 +0200934It is possible to completely ignore the function calculating the default
Victor Stinner331a6a52019-05-27 16:39:22 +0200935path configuration by setting explicitly all path configuration output
936fields listed above. A string is considered as set even if it is non-empty.
937``module_search_paths`` is considered as set if
938``module_search_paths_set`` is set to 1. In this case, path
939configuration input fields are ignored as well.
940
941Set :c:member:`~PyConfig.pathconfig_warnings` to 0 to suppress warnings when
Victor Stinner8bf39b62019-09-26 02:22:35 +0200942calculating the path configuration (Unix only, Windows does not log any warning).
Victor Stinner331a6a52019-05-27 16:39:22 +0200943
944If :c:member:`~PyConfig.base_prefix` or :c:member:`~PyConfig.base_exec_prefix`
945fields are not set, they inherit their value from :c:member:`~PyConfig.prefix`
946and :c:member:`~PyConfig.exec_prefix` respectively.
947
948:c:func:`Py_RunMain` and :c:func:`Py_Main` modify :data:`sys.path`:
949
950* If :c:member:`~PyConfig.run_filename` is set and is a directory which contains a
951 ``__main__.py`` script, prepend :c:member:`~PyConfig.run_filename` to
952 :data:`sys.path`.
953* If :c:member:`~PyConfig.isolated` is zero:
954
955 * If :c:member:`~PyConfig.run_module` is set, prepend the current directory
956 to :data:`sys.path`. Do nothing if the current directory cannot be read.
957 * If :c:member:`~PyConfig.run_filename` is set, prepend the directory of the
958 filename to :data:`sys.path`.
959 * Otherwise, prepend an empty string to :data:`sys.path`.
960
961If :c:member:`~PyConfig.site_import` is non-zero, :data:`sys.path` can be
962modified by the :mod:`site` module. If
963:c:member:`~PyConfig.user_site_directory` is non-zero and the user's
964site-package directory exists, the :mod:`site` module appends the user's
965site-package directory to :data:`sys.path`.
966
967The following configuration files are used by the path configuration:
968
969* ``pyvenv.cfg``
970* ``python._pth`` (Windows only)
971* ``pybuilddir.txt`` (Unix only)
972
Victor Stinnerfcdb0272019-09-23 14:45:47 +0200973The ``__PYVENV_LAUNCHER__`` environment variable is used to set
974:c:member:`PyConfig.base_executable`
975
Victor Stinner331a6a52019-05-27 16:39:22 +0200976
977Py_RunMain()
978------------
979
980.. c:function:: int Py_RunMain(void)
981
982 Execute the command (:c:member:`PyConfig.run_command`), the script
983 (:c:member:`PyConfig.run_filename`) or the module
984 (:c:member:`PyConfig.run_module`) specified on the command line or in the
985 configuration.
986
987 By default and when if :option:`-i` option is used, run the REPL.
988
989 Finally, finalizes Python and returns an exit status that can be passed to
990 the ``exit()`` function.
991
992See :ref:`Python Configuration <init-python-config>` for an example of
993customized Python always running in isolated mode using
994:c:func:`Py_RunMain`.
995
996
Victor Stinnere81f6e62020-06-08 18:12:59 +0200997Py_GetArgcArgv()
998----------------
999
1000.. c:function:: void Py_GetArgcArgv(int *argc, wchar_t ***argv)
1001
1002 Get the original command line arguments, before Python modified them.
1003
Victor Stinnerdd8a93e2020-06-30 00:49:03 +02001004 See also :c:member:`PyConfig.orig_argv` member.
1005
Victor Stinnere81f6e62020-06-08 18:12:59 +02001006
Victor Stinner331a6a52019-05-27 16:39:22 +02001007Multi-Phase Initialization Private Provisional API
1008--------------------------------------------------
1009
1010This section is a private provisional API introducing multi-phase
1011initialization, the core feature of the :pep:`432`:
1012
1013* "Core" initialization phase, "bare minimum Python":
1014
1015 * Builtin types;
1016 * Builtin exceptions;
1017 * Builtin and frozen modules;
1018 * The :mod:`sys` module is only partially initialized
Victor Stinner88feaec2019-09-26 03:15:07 +02001019 (ex: :data:`sys.path` doesn't exist yet).
Victor Stinner331a6a52019-05-27 16:39:22 +02001020
1021* "Main" initialization phase, Python is fully initialized:
1022
1023 * Install and configure :mod:`importlib`;
1024 * Apply the :ref:`Path Configuration <init-path-config>`;
1025 * Install signal handlers;
1026 * Finish :mod:`sys` module initialization (ex: create :data:`sys.stdout`
1027 and :data:`sys.path`);
1028 * Enable optional features like :mod:`faulthandler` and :mod:`tracemalloc`;
1029 * Import the :mod:`site` module;
1030 * etc.
1031
1032Private provisional API:
1033
1034* :c:member:`PyConfig._init_main`: if set to 0,
1035 :c:func:`Py_InitializeFromConfig` stops at the "Core" initialization phase.
Victor Stinner252346a2020-05-01 11:33:44 +02001036* :c:member:`PyConfig._isolated_interpreter`: if non-zero,
1037 disallow threads, subprocesses and fork.
Victor Stinner331a6a52019-05-27 16:39:22 +02001038
1039.. c:function:: PyStatus _Py_InitializeMain(void)
1040
1041 Move to the "Main" initialization phase, finish the Python initialization.
1042
1043No module is imported during the "Core" phase and the ``importlib`` module is
1044not configured: the :ref:`Path Configuration <init-path-config>` is only
1045applied during the "Main" phase. It may allow to customize Python in Python to
1046override or tune the :ref:`Path Configuration <init-path-config>`, maybe
Victor Stinner88feaec2019-09-26 03:15:07 +02001047install a custom :data:`sys.meta_path` importer or an import hook, etc.
Victor Stinner331a6a52019-05-27 16:39:22 +02001048
Victor Stinner88feaec2019-09-26 03:15:07 +02001049It may become possible to calculatin the :ref:`Path Configuration
Victor Stinner331a6a52019-05-27 16:39:22 +02001050<init-path-config>` in Python, after the Core phase and before the Main phase,
1051which is one of the :pep:`432` motivation.
1052
1053The "Core" phase is not properly defined: what should be and what should
1054not be available at this phase is not specified yet. The API is marked
1055as private and provisional: the API can be modified or even be removed
1056anytime until a proper public API is designed.
1057
1058Example running Python code between "Core" and "Main" initialization
1059phases::
1060
1061 void init_python(void)
1062 {
1063 PyStatus status;
Victor Stinner8462a492019-10-01 12:06:16 +02001064
Victor Stinner331a6a52019-05-27 16:39:22 +02001065 PyConfig config;
Victor Stinner8462a492019-10-01 12:06:16 +02001066 PyConfig_InitPythonConfig(&config);
Victor Stinner331a6a52019-05-27 16:39:22 +02001067 config._init_main = 0;
1068
1069 /* ... customize 'config' configuration ... */
1070
1071 status = Py_InitializeFromConfig(&config);
1072 PyConfig_Clear(&config);
1073 if (PyStatus_Exception(status)) {
1074 Py_ExitStatusException(status);
1075 }
1076
1077 /* Use sys.stderr because sys.stdout is only created
1078 by _Py_InitializeMain() */
1079 int res = PyRun_SimpleString(
1080 "import sys; "
1081 "print('Run Python code before _Py_InitializeMain', "
1082 "file=sys.stderr)");
1083 if (res < 0) {
1084 exit(1);
1085 }
1086
1087 /* ... put more configuration code here ... */
1088
1089 status = _Py_InitializeMain();
1090 if (PyStatus_Exception(status)) {
1091 Py_ExitStatusException(status);
1092 }
1093 }