blob: 7b8e894fe22dd30987b472cc67ff1e21828930dc [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
Serhiy Storchakae835b312019-10-30 21:37:16 +020064 If *length* is non-zero, *items* must be non-``NULL`` and all strings must be
65 non-``NULL``.
Victor Stinner331a6a52019-05-27 16:39:22 +020066
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
Victor Stinner3c30a762019-10-01 10:56:37 +0200199 .. c:function:: void PyPreConfig_InitIsolatedConfig(PyPreConfig *preconfig)
Victor Stinner331a6a52019-05-27 16:39:22 +0200200
201 Initialize the preconfiguration with :ref:`Python Configuration
202 <init-python-config>`.
203
Victor Stinner3c30a762019-10-01 10:56:37 +0200204 .. c:function:: void PyPreConfig_InitPythonConfig(PyPreConfig *preconfig)
Victor Stinner331a6a52019-05-27 16:39:22 +0200205
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
Victor Stinner88feaec2019-09-26 03:15:07 +0200244
Victor Stinner331a6a52019-05-27 16:39:22 +0200245 If non-zero, emit a warning if the C locale is coerced.
246
247 .. c:member:: int dev_mode
248
249 See :c:member:`PyConfig.dev_mode`.
250
251 .. c:member:: int isolated
252
253 See :c:member:`PyConfig.isolated`.
254
255 .. c:member:: int legacy_windows_fs_encoding (Windows only)
256
257 If non-zero, disable UTF-8 Mode, set the Python filesystem encoding to
258 ``mbcs``, set the filesystem error handler to ``replace``.
259
260 Only available on Windows. ``#ifdef MS_WINDOWS`` macro can be used for
261 Windows specific code.
262
263 .. c:member:: int parse_argv
264
265 If non-zero, :c:func:`Py_PreInitializeFromArgs` and
266 :c:func:`Py_PreInitializeFromBytesArgs` parse their ``argv`` argument the
267 same way the regular Python parses command line arguments: see
268 :ref:`Command Line Arguments <using-on-cmdline>`.
269
270 .. c:member:: int use_environment
271
272 See :c:member:`PyConfig.use_environment`.
273
274 .. c:member:: int utf8_mode
275
276 If non-zero, enable the UTF-8 mode.
277
278Preinitialization with PyPreConfig
279----------------------------------
280
281Functions to preinitialize Python:
282
283.. c:function:: PyStatus Py_PreInitialize(const PyPreConfig *preconfig)
284
285 Preinitialize Python from *preconfig* preconfiguration.
286
287.. c:function:: PyStatus Py_PreInitializeFromBytesArgs(const PyPreConfig *preconfig, int argc, char * const *argv)
288
289 Preinitialize Python from *preconfig* preconfiguration and command line
290 arguments (bytes strings).
291
292.. c:function:: PyStatus Py_PreInitializeFromArgs(const PyPreConfig *preconfig, int argc, wchar_t * const * argv)
293
294 Preinitialize Python from *preconfig* preconfiguration and command line
295 arguments (wide strings).
296
297The caller is responsible to handle exceptions (error or exit) using
298:c:func:`PyStatus_Exception` and :c:func:`Py_ExitStatusException`.
299
300For :ref:`Python Configuration <init-python-config>`
301(:c:func:`PyPreConfig_InitPythonConfig`), if Python is initialized with
302command line arguments, the command line arguments must also be passed to
303preinitialize Python, since they have an effect on the pre-configuration
Victor Stinner88feaec2019-09-26 03:15:07 +0200304like encodings. For example, the :option:`-X utf8 <-X>` command line option
Victor Stinner331a6a52019-05-27 16:39:22 +0200305enables the UTF-8 Mode.
306
307``PyMem_SetAllocator()`` can be called after :c:func:`Py_PreInitialize` and
308before :c:func:`Py_InitializeFromConfig` to install a custom memory allocator.
309It can be called before :c:func:`Py_PreInitialize` if
310:c:member:`PyPreConfig.allocator` is set to ``PYMEM_ALLOCATOR_NOT_SET``.
311
312Python memory allocation functions like :c:func:`PyMem_RawMalloc` must not be
313used before Python preinitialization, whereas calling directly ``malloc()`` and
314``free()`` is always safe. :c:func:`Py_DecodeLocale` must not be called before
315the preinitialization.
316
317Example using the preinitialization to enable the UTF-8 Mode::
318
Victor Stinner441b10c2019-09-28 04:28:35 +0200319 PyStatus status;
Victor Stinner331a6a52019-05-27 16:39:22 +0200320 PyPreConfig preconfig;
Victor Stinner3c30a762019-10-01 10:56:37 +0200321 PyPreConfig_InitPythonConfig(&preconfig);
Victor Stinner331a6a52019-05-27 16:39:22 +0200322
323 preconfig.utf8_mode = 1;
324
Victor Stinner441b10c2019-09-28 04:28:35 +0200325 status = Py_PreInitialize(&preconfig);
Victor Stinner331a6a52019-05-27 16:39:22 +0200326 if (PyStatus_Exception(status)) {
327 Py_ExitStatusException(status);
328 }
329
330 /* at this point, Python will speak UTF-8 */
331
332 Py_Initialize();
333 /* ... use Python API here ... */
334 Py_Finalize();
335
336
337PyConfig
338--------
339
340.. c:type:: PyConfig
341
342 Structure containing most parameters to configure Python.
343
344 Structure methods:
345
Victor Stinner8462a492019-10-01 12:06:16 +0200346 .. c:function:: void PyConfig_InitPythonConfig(PyConfig *config)
Victor Stinner331a6a52019-05-27 16:39:22 +0200347
348 Initialize configuration with :ref:`Python Configuration
349 <init-python-config>`.
350
Victor Stinner8462a492019-10-01 12:06:16 +0200351 .. c:function:: void PyConfig_InitIsolatedConfig(PyConfig *config)
Victor Stinner331a6a52019-05-27 16:39:22 +0200352
353 Initialize configuration with :ref:`Isolated Configuration
354 <init-isolated-conf>`.
355
356 .. c:function:: PyStatus PyConfig_SetString(PyConfig *config, wchar_t * const *config_str, const wchar_t *str)
357
358 Copy the wide character string *str* into ``*config_str``.
359
360 Preinitialize Python if needed.
361
362 .. c:function:: PyStatus PyConfig_SetBytesString(PyConfig *config, wchar_t * const *config_str, const char *str)
363
364 Decode *str* using ``Py_DecodeLocale()`` and set the result into ``*config_str``.
365
366 Preinitialize Python if needed.
367
368 .. c:function:: PyStatus PyConfig_SetArgv(PyConfig *config, int argc, wchar_t * const *argv)
369
370 Set command line arguments from wide character strings.
371
372 Preinitialize Python if needed.
373
374 .. c:function:: PyStatus PyConfig_SetBytesArgv(PyConfig *config, int argc, char * const *argv)
375
376 Set command line arguments: decode bytes using :c:func:`Py_DecodeLocale`.
377
378 Preinitialize Python if needed.
379
Victor Stinner36242fd2019-07-01 19:13:50 +0200380 .. c:function:: PyStatus PyConfig_SetWideStringList(PyConfig *config, PyWideStringList *list, Py_ssize_t length, wchar_t **items)
381
382 Set the list of wide strings *list* to *length* and *items*.
383
384 Preinitialize Python if needed.
385
Victor Stinner331a6a52019-05-27 16:39:22 +0200386 .. c:function:: PyStatus PyConfig_Read(PyConfig *config)
387
388 Read all Python configuration.
389
390 Fields which are already initialized are left unchanged.
391
392 Preinitialize Python if needed.
393
394 .. c:function:: void PyConfig_Clear(PyConfig *config)
395
396 Release configuration memory.
397
398 Most ``PyConfig`` methods preinitialize Python if needed. In that case, the
399 Python preinitialization configuration in based on the :c:type:`PyConfig`.
400 If configuration fields which are in common with :c:type:`PyPreConfig` are
401 tuned, they must be set before calling a :c:type:`PyConfig` method:
402
403 * :c:member:`~PyConfig.dev_mode`
404 * :c:member:`~PyConfig.isolated`
405 * :c:member:`~PyConfig.parse_argv`
406 * :c:member:`~PyConfig.use_environment`
407
408 Moreover, if :c:func:`PyConfig_SetArgv` or :c:func:`PyConfig_SetBytesArgv`
409 is used, this method must be called first, before other methods, since the
410 preinitialization configuration depends on command line arguments (if
411 :c:member:`parse_argv` is non-zero).
412
413 The caller of these methods is responsible to handle exceptions (error or
414 exit) using ``PyStatus_Exception()`` and ``Py_ExitStatusException()``.
415
416 Structure fields:
417
418 .. c:member:: PyWideStringList argv
419
420 Command line arguments, :data:`sys.argv`. See
421 :c:member:`~PyConfig.parse_argv` to parse :c:member:`~PyConfig.argv` the
422 same way the regular Python parses Python command line arguments. If
423 :c:member:`~PyConfig.argv` is empty, an empty string is added to ensure
424 that :data:`sys.argv` always exists and is never empty.
425
426 .. c:member:: wchar_t* base_exec_prefix
427
428 :data:`sys.base_exec_prefix`.
429
Victor Stinnerfcdb0272019-09-23 14:45:47 +0200430 .. c:member:: wchar_t* base_executable
431
432 :data:`sys._base_executable`: ``__PYVENV_LAUNCHER__`` environment
433 variable value, or copy of :c:member:`PyConfig.executable`.
434
Victor Stinner331a6a52019-05-27 16:39:22 +0200435 .. c:member:: wchar_t* base_prefix
436
437 :data:`sys.base_prefix`.
438
Sandro Mani8f023a22020-06-08 17:28:11 +0200439 .. c:member:: wchar_t* platlibdir
440
441 :data:`sys.platlibdir`: platform library directory name, set at configure time
442 by ``--with-platlibdir``, overrideable by the ``PYTHONPLATLIBDIR``
443 environment variable.
444
445 .. versionadded:: 3.10
446
Victor Stinner331a6a52019-05-27 16:39:22 +0200447 .. c:member:: int buffered_stdio
448
449 If equals to 0, enable unbuffered mode, making the stdout and stderr
450 streams unbuffered.
451
452 stdin is always opened in buffered mode.
453
454 .. c:member:: int bytes_warning
455
456 If equals to 1, issue a warning when comparing :class:`bytes` or
457 :class:`bytearray` with :class:`str`, or comparing :class:`bytes` with
458 :class:`int`. If equal or greater to 2, raise a :exc:`BytesWarning`
459 exception.
460
461 .. c:member:: wchar_t* check_hash_pycs_mode
462
463 Control the validation behavior of hash-based ``.pyc`` files (see
464 :pep:`552`): :option:`--check-hash-based-pycs` command line option value.
465
466 Valid values: ``always``, ``never`` and ``default``.
467
468 The default value is: ``default``.
469
470 .. c:member:: int configure_c_stdio
471
472 If non-zero, configure C standard streams (``stdio``, ``stdout``,
473 ``stdout``). For example, set their mode to ``O_BINARY`` on Windows.
474
475 .. c:member:: int dev_mode
476
Victor Stinnerb9783d22020-01-24 10:22:18 +0100477 If non-zero, enable the :ref:`Python Development Mode <devmode>`.
Victor Stinner331a6a52019-05-27 16:39:22 +0200478
479 .. c:member:: int dump_refs
480
481 If non-zero, dump all objects which are still alive at exit.
482
Hai Shia7847592020-02-17 17:18:19 +0800483 ``Py_TRACE_REFS`` macro must be defined in build.
Victor Stinner331a6a52019-05-27 16:39:22 +0200484
485 .. c:member:: wchar_t* exec_prefix
486
487 :data:`sys.exec_prefix`.
488
489 .. c:member:: wchar_t* executable
490
491 :data:`sys.executable`.
492
493 .. c:member:: int faulthandler
494
Victor Stinner88feaec2019-09-26 03:15:07 +0200495 If non-zero, call :func:`faulthandler.enable` at startup.
Victor Stinner331a6a52019-05-27 16:39:22 +0200496
497 .. c:member:: wchar_t* filesystem_encoding
498
499 Filesystem encoding, :func:`sys.getfilesystemencoding`.
500
501 .. c:member:: wchar_t* filesystem_errors
502
503 Filesystem encoding errors, :func:`sys.getfilesystemencodeerrors`.
504
505 .. c:member:: unsigned long hash_seed
506 .. c:member:: int use_hash_seed
507
508 Randomized hash function seed.
509
510 If :c:member:`~PyConfig.use_hash_seed` is zero, a seed is chosen randomly
511 at Pythonstartup, and :c:member:`~PyConfig.hash_seed` is ignored.
512
513 .. c:member:: wchar_t* home
514
515 Python home directory.
516
Victor Stinner88feaec2019-09-26 03:15:07 +0200517 Initialized from :envvar:`PYTHONHOME` environment variable value by
518 default.
519
Victor Stinner331a6a52019-05-27 16:39:22 +0200520 .. c:member:: int import_time
521
522 If non-zero, profile import time.
523
524 .. c:member:: int inspect
525
526 Enter interactive mode after executing a script or a command.
527
528 .. c:member:: int install_signal_handlers
529
530 Install signal handlers?
531
532 .. c:member:: int interactive
533
534 Interactive mode.
535
536 .. c:member:: int isolated
537
538 If greater than 0, enable isolated mode:
539
540 * :data:`sys.path` contains neither the script's directory (computed from
541 ``argv[0]`` or the current directory) nor the user's site-packages
542 directory.
543 * Python REPL doesn't import :mod:`readline` nor enable default readline
544 configuration on interactive prompts.
545 * Set :c:member:`~PyConfig.use_environment` and
546 :c:member:`~PyConfig.user_site_directory` to 0.
547
548 .. c:member:: int legacy_windows_stdio
549
550 If non-zero, use :class:`io.FileIO` instead of
551 :class:`io.WindowsConsoleIO` for :data:`sys.stdin`, :data:`sys.stdout`
552 and :data:`sys.stderr`.
553
554 Only available on Windows. ``#ifdef MS_WINDOWS`` macro can be used for
555 Windows specific code.
556
557 .. c:member:: int malloc_stats
558
559 If non-zero, dump statistics on :ref:`Python pymalloc memory allocator
560 <pymalloc>` at exit.
561
562 The option is ignored if Python is built using ``--without-pymalloc``.
563
564 .. c:member:: wchar_t* pythonpath_env
565
566 Module search paths as a string separated by ``DELIM``
567 (:data:`os.path.pathsep`).
568
569 Initialized from :envvar:`PYTHONPATH` environment variable value by
570 default.
571
572 .. c:member:: PyWideStringList module_search_paths
573 .. c:member:: int module_search_paths_set
574
575 :data:`sys.path`. If :c:member:`~PyConfig.module_search_paths_set` is
576 equal to 0, the :c:member:`~PyConfig.module_search_paths` is overridden
Victor Stinner88feaec2019-09-26 03:15:07 +0200577 by the function calculating the :ref:`Path Configuration
Victor Stinner331a6a52019-05-27 16:39:22 +0200578 <init-path-config>`.
579
580 .. c:member:: int optimization_level
581
582 Compilation optimization level:
583
584 * 0: Peephole optimizer (and ``__debug__`` is set to ``True``)
585 * 1: Remove assertions, set ``__debug__`` to ``False``
586 * 2: Strip docstrings
587
588 .. c:member:: int parse_argv
589
590 If non-zero, parse :c:member:`~PyConfig.argv` the same way the regular
591 Python command line arguments, and strip Python arguments from
592 :c:member:`~PyConfig.argv`: see :ref:`Command Line Arguments
593 <using-on-cmdline>`.
594
595 .. c:member:: int parser_debug
596
597 If non-zero, turn on parser debugging output (for expert only, depending
598 on compilation options).
599
600 .. c:member:: int pathconfig_warnings
601
Victor Stinner88feaec2019-09-26 03:15:07 +0200602 If equal to 0, suppress warnings when calculating the :ref:`Path
603 Configuration <init-path-config>` (Unix only, Windows does not log any
604 warning). Otherwise, warnings are written into ``stderr``.
Victor Stinner331a6a52019-05-27 16:39:22 +0200605
606 .. c:member:: wchar_t* prefix
607
608 :data:`sys.prefix`.
609
610 .. c:member:: wchar_t* program_name
611
Victor Stinner88feaec2019-09-26 03:15:07 +0200612 Program name. Used to initialize :c:member:`~PyConfig.executable`, and in
613 early error messages.
Victor Stinner331a6a52019-05-27 16:39:22 +0200614
615 .. c:member:: wchar_t* pycache_prefix
616
Victor Stinner88feaec2019-09-26 03:15:07 +0200617 :data:`sys.pycache_prefix`: ``.pyc`` cache prefix.
618
Serhiy Storchakae835b312019-10-30 21:37:16 +0200619 If ``NULL``, :data:`sys.pycache_prefix` is set to ``None``.
Victor Stinner331a6a52019-05-27 16:39:22 +0200620
621 .. c:member:: int quiet
622
623 Quiet mode. For example, don't display the copyright and version messages
Victor Stinner88feaec2019-09-26 03:15:07 +0200624 in interactive mode.
Victor Stinner331a6a52019-05-27 16:39:22 +0200625
626 .. c:member:: wchar_t* run_command
627
Victor Stinner88feaec2019-09-26 03:15:07 +0200628 ``python3 -c COMMAND`` argument. Used by :c:func:`Py_RunMain`.
Victor Stinner331a6a52019-05-27 16:39:22 +0200629
630 .. c:member:: wchar_t* run_filename
631
Victor Stinner88feaec2019-09-26 03:15:07 +0200632 ``python3 FILENAME`` argument. Used by :c:func:`Py_RunMain`.
Victor Stinner331a6a52019-05-27 16:39:22 +0200633
634 .. c:member:: wchar_t* run_module
635
Victor Stinner88feaec2019-09-26 03:15:07 +0200636 ``python3 -m MODULE`` argument. Used by :c:func:`Py_RunMain`.
Victor Stinner331a6a52019-05-27 16:39:22 +0200637
Victor Stinner331a6a52019-05-27 16:39:22 +0200638 .. c:member:: int show_ref_count
639
640 Show total reference count at exit?
641
Victor Stinner88feaec2019-09-26 03:15:07 +0200642 Set to 1 by :option:`-X showrefcount <-X>` command line option.
643
Victor Stinner331a6a52019-05-27 16:39:22 +0200644 Need a debug build of Python (``Py_REF_DEBUG`` macro must be defined).
645
646 .. c:member:: int site_import
647
648 Import the :mod:`site` module at startup?
649
650 .. c:member:: int skip_source_first_line
651
652 Skip the first line of the source?
653
654 .. c:member:: wchar_t* stdio_encoding
655 .. c:member:: wchar_t* stdio_errors
656
657 Encoding and encoding errors of :data:`sys.stdin`, :data:`sys.stdout` and
658 :data:`sys.stderr`.
659
660 .. c:member:: int tracemalloc
661
Victor Stinner88feaec2019-09-26 03:15:07 +0200662 If non-zero, call :func:`tracemalloc.start` at startup.
Victor Stinner331a6a52019-05-27 16:39:22 +0200663
664 .. c:member:: int use_environment
665
666 If greater than 0, use :ref:`environment variables <using-on-envvars>`.
667
668 .. c:member:: int user_site_directory
669
670 If non-zero, add user site directory to :data:`sys.path`.
671
672 .. c:member:: int verbose
673
674 If non-zero, enable verbose mode.
675
676 .. c:member:: PyWideStringList warnoptions
677
Victor Stinnerfb4ae152019-09-30 01:40:17 +0200678 :data:`sys.warnoptions`: options of the :mod:`warnings` module to build
679 warnings filters: lowest to highest priority.
680
681 The :mod:`warnings` module adds :data:`sys.warnoptions` in the reverse
682 order: the last :c:member:`PyConfig.warnoptions` item becomes the first
683 item of :data:`warnings.filters` which is checked first (highest
684 priority).
Victor Stinner331a6a52019-05-27 16:39:22 +0200685
686 .. c:member:: int write_bytecode
687
688 If non-zero, write ``.pyc`` files.
689
Victor Stinner88feaec2019-09-26 03:15:07 +0200690 :data:`sys.dont_write_bytecode` is initialized to the inverted value of
691 :c:member:`~PyConfig.write_bytecode`.
692
Victor Stinner331a6a52019-05-27 16:39:22 +0200693 .. c:member:: PyWideStringList xoptions
694
695 :data:`sys._xoptions`.
696
Victor Stinner1def7752020-04-23 03:03:24 +0200697 .. c:member:: int _use_peg_parser
698
699 Enable PEG parser? Default: 1.
700
701 Set to 0 by :option:`-X oldparser <-X>` and :envvar:`PYTHONOLDPARSER`.
702
703 See also :pep:`617`.
704
705 .. deprecated-removed:: 3.9 3.10
706
Victor Stinner331a6a52019-05-27 16:39:22 +0200707If ``parse_argv`` is non-zero, ``argv`` arguments are parsed the same
708way the regular Python parses command line arguments, and Python
709arguments are stripped from ``argv``: see :ref:`Command Line Arguments
710<using-on-cmdline>`.
711
712The ``xoptions`` options are parsed to set other options: see :option:`-X`
713option.
714
Victor Stinnerc6e5c112020-02-03 15:17:15 +0100715.. versionchanged:: 3.9
716
717 The ``show_alloc_count`` field has been removed.
718
Victor Stinner331a6a52019-05-27 16:39:22 +0200719
720Initialization with PyConfig
721----------------------------
722
723Function to initialize Python:
724
725.. c:function:: PyStatus Py_InitializeFromConfig(const PyConfig *config)
726
727 Initialize Python from *config* configuration.
728
729The caller is responsible to handle exceptions (error or exit) using
730:c:func:`PyStatus_Exception` and :c:func:`Py_ExitStatusException`.
731
Victor Stinner88feaec2019-09-26 03:15:07 +0200732If ``PyImport_FrozenModules``, ``PyImport_AppendInittab()`` or
733``PyImport_ExtendInittab()`` are used, they must be set or called after Python
Victor Stinner331a6a52019-05-27 16:39:22 +0200734preinitialization and before the Python initialization.
735
736Example setting the program name::
737
738 void init_python(void)
739 {
740 PyStatus status;
Victor Stinner331a6a52019-05-27 16:39:22 +0200741
Victor Stinner8462a492019-10-01 12:06:16 +0200742 PyConfig config;
743 PyConfig_InitPythonConfig(&config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200744
745 /* Set the program name. Implicitly preinitialize Python. */
746 status = PyConfig_SetString(&config, &config.program_name,
747 L"/path/to/my_program");
748 if (PyStatus_Exception(status)) {
749 goto fail;
750 }
751
752 status = Py_InitializeFromConfig(&config);
753 if (PyStatus_Exception(status)) {
754 goto fail;
755 }
756 PyConfig_Clear(&config);
757 return;
758
759 fail:
760 PyConfig_Clear(&config);
761 Py_ExitStatusException(status);
762 }
763
764More complete example modifying the default configuration, read the
765configuration, and then override some parameters::
766
767 PyStatus init_python(const char *program_name)
768 {
769 PyStatus status;
Victor Stinner331a6a52019-05-27 16:39:22 +0200770
Victor Stinner8462a492019-10-01 12:06:16 +0200771 PyConfig config;
772 PyConfig_InitPythonConfig(&config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200773
Gurupad Hegde6c7bb382019-12-28 17:16:02 -0500774 /* Set the program name before reading the configuration
Victor Stinner331a6a52019-05-27 16:39:22 +0200775 (decode byte string from the locale encoding).
776
777 Implicitly preinitialize Python. */
778 status = PyConfig_SetBytesString(&config, &config.program_name,
779 program_name);
780 if (PyStatus_Exception(status)) {
781 goto done;
782 }
783
784 /* Read all configuration at once */
785 status = PyConfig_Read(&config);
786 if (PyStatus_Exception(status)) {
787 goto done;
788 }
789
790 /* Append our custom search path to sys.path */
791 status = PyWideStringList_Append(&config.module_search_paths,
Victor Stinner88feaec2019-09-26 03:15:07 +0200792 L"/path/to/more/modules");
Victor Stinner331a6a52019-05-27 16:39:22 +0200793 if (PyStatus_Exception(status)) {
794 goto done;
795 }
796
797 /* Override executable computed by PyConfig_Read() */
798 status = PyConfig_SetString(&config, &config.executable,
799 L"/path/to/my_executable");
800 if (PyStatus_Exception(status)) {
801 goto done;
802 }
803
804 status = Py_InitializeFromConfig(&config);
805
806 done:
807 PyConfig_Clear(&config);
808 return status;
809 }
810
811
812.. _init-isolated-conf:
813
814Isolated Configuration
815----------------------
816
817:c:func:`PyPreConfig_InitIsolatedConfig` and
818:c:func:`PyConfig_InitIsolatedConfig` functions create a configuration to
819isolate Python from the system. For example, to embed Python into an
820application.
821
822This configuration ignores global configuration variables, environments
Victor Stinner88feaec2019-09-26 03:15:07 +0200823variables, command line arguments (:c:member:`PyConfig.argv` is not parsed)
824and user site directory. The C standard streams (ex: ``stdout``) and the
825LC_CTYPE locale are left unchanged. Signal handlers are not installed.
Victor Stinner331a6a52019-05-27 16:39:22 +0200826
827Configuration files are still used with this configuration. Set the
828:ref:`Path Configuration <init-path-config>` ("output fields") to ignore these
829configuration files and avoid the function computing the default path
830configuration.
831
832
833.. _init-python-config:
834
835Python Configuration
836--------------------
837
838:c:func:`PyPreConfig_InitPythonConfig` and :c:func:`PyConfig_InitPythonConfig`
839functions create a configuration to build a customized Python which behaves as
840the regular Python.
841
842Environments variables and command line arguments are used to configure
843Python, whereas global configuration variables are ignored.
844
845This function enables C locale coercion (:pep:`538`) and UTF-8 Mode
846(:pep:`540`) depending on the LC_CTYPE locale, :envvar:`PYTHONUTF8` and
847:envvar:`PYTHONCOERCECLOCALE` environment variables.
848
849Example of customized Python always running in isolated mode::
850
851 int main(int argc, char **argv)
852 {
Victor Stinner331a6a52019-05-27 16:39:22 +0200853 PyStatus status;
Victor Stinner8462a492019-10-01 12:06:16 +0200854
Victor Stinner441b10c2019-09-28 04:28:35 +0200855 PyConfig config;
Victor Stinner8462a492019-10-01 12:06:16 +0200856 PyConfig_InitPythonConfig(&config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200857 config.isolated = 1;
858
859 /* Decode command line arguments.
860 Implicitly preinitialize Python (in isolated mode). */
861 status = PyConfig_SetBytesArgv(&config, argc, argv);
862 if (PyStatus_Exception(status)) {
863 goto fail;
864 }
865
866 status = Py_InitializeFromConfig(&config);
867 if (PyStatus_Exception(status)) {
868 goto fail;
869 }
870 PyConfig_Clear(&config);
871
872 return Py_RunMain();
873
874 fail:
875 PyConfig_Clear(&config);
876 if (PyStatus_IsExit(status)) {
877 return status.exitcode;
878 }
879 /* Display the error message and exit the process with
880 non-zero exit code */
881 Py_ExitStatusException(status);
882 }
883
884
885.. _init-path-config:
886
887Path Configuration
888------------------
889
890:c:type:`PyConfig` contains multiple fields for the path configuration:
891
Victor Stinner8bf39b62019-09-26 02:22:35 +0200892* Path configuration inputs:
Victor Stinner331a6a52019-05-27 16:39:22 +0200893
894 * :c:member:`PyConfig.home`
Sandro Mani8f023a22020-06-08 17:28:11 +0200895 * :c:member:`PyConfig.platlibdir`
Victor Stinner331a6a52019-05-27 16:39:22 +0200896 * :c:member:`PyConfig.pathconfig_warnings`
Victor Stinnerfcdb0272019-09-23 14:45:47 +0200897 * :c:member:`PyConfig.program_name`
898 * :c:member:`PyConfig.pythonpath_env`
Victor Stinner8bf39b62019-09-26 02:22:35 +0200899 * current working directory: to get absolute paths
900 * ``PATH`` environment variable to get the program full path
901 (from :c:member:`PyConfig.program_name`)
902 * ``__PYVENV_LAUNCHER__`` environment variable
903 * (Windows only) Application paths in the registry under
904 "Software\Python\PythonCore\X.Y\PythonPath" of HKEY_CURRENT_USER and
905 HKEY_LOCAL_MACHINE (where X.Y is the Python version).
Victor Stinner331a6a52019-05-27 16:39:22 +0200906
907* Path configuration output fields:
908
Victor Stinner8bf39b62019-09-26 02:22:35 +0200909 * :c:member:`PyConfig.base_exec_prefix`
Victor Stinnerfcdb0272019-09-23 14:45:47 +0200910 * :c:member:`PyConfig.base_executable`
Victor Stinner8bf39b62019-09-26 02:22:35 +0200911 * :c:member:`PyConfig.base_prefix`
Victor Stinner331a6a52019-05-27 16:39:22 +0200912 * :c:member:`PyConfig.exec_prefix`
913 * :c:member:`PyConfig.executable`
Victor Stinner331a6a52019-05-27 16:39:22 +0200914 * :c:member:`PyConfig.module_search_paths_set`,
915 :c:member:`PyConfig.module_search_paths`
Victor Stinner8bf39b62019-09-26 02:22:35 +0200916 * :c:member:`PyConfig.prefix`
Victor Stinner331a6a52019-05-27 16:39:22 +0200917
Victor Stinner8bf39b62019-09-26 02:22:35 +0200918If at least one "output field" is not set, Python calculates the path
Victor Stinner331a6a52019-05-27 16:39:22 +0200919configuration to fill unset fields. If
920:c:member:`~PyConfig.module_search_paths_set` is equal to 0,
Min ho Kim39d87b52019-08-31 06:21:19 +1000921:c:member:`~PyConfig.module_search_paths` is overridden and
Victor Stinner331a6a52019-05-27 16:39:22 +0200922:c:member:`~PyConfig.module_search_paths_set` is set to 1.
923
Victor Stinner8bf39b62019-09-26 02:22:35 +0200924It is possible to completely ignore the function calculating the default
Victor Stinner331a6a52019-05-27 16:39:22 +0200925path configuration by setting explicitly all path configuration output
926fields listed above. A string is considered as set even if it is non-empty.
927``module_search_paths`` is considered as set if
928``module_search_paths_set`` is set to 1. In this case, path
929configuration input fields are ignored as well.
930
931Set :c:member:`~PyConfig.pathconfig_warnings` to 0 to suppress warnings when
Victor Stinner8bf39b62019-09-26 02:22:35 +0200932calculating the path configuration (Unix only, Windows does not log any warning).
Victor Stinner331a6a52019-05-27 16:39:22 +0200933
934If :c:member:`~PyConfig.base_prefix` or :c:member:`~PyConfig.base_exec_prefix`
935fields are not set, they inherit their value from :c:member:`~PyConfig.prefix`
936and :c:member:`~PyConfig.exec_prefix` respectively.
937
938:c:func:`Py_RunMain` and :c:func:`Py_Main` modify :data:`sys.path`:
939
940* If :c:member:`~PyConfig.run_filename` is set and is a directory which contains a
941 ``__main__.py`` script, prepend :c:member:`~PyConfig.run_filename` to
942 :data:`sys.path`.
943* If :c:member:`~PyConfig.isolated` is zero:
944
945 * If :c:member:`~PyConfig.run_module` is set, prepend the current directory
946 to :data:`sys.path`. Do nothing if the current directory cannot be read.
947 * If :c:member:`~PyConfig.run_filename` is set, prepend the directory of the
948 filename to :data:`sys.path`.
949 * Otherwise, prepend an empty string to :data:`sys.path`.
950
951If :c:member:`~PyConfig.site_import` is non-zero, :data:`sys.path` can be
952modified by the :mod:`site` module. If
953:c:member:`~PyConfig.user_site_directory` is non-zero and the user's
954site-package directory exists, the :mod:`site` module appends the user's
955site-package directory to :data:`sys.path`.
956
957The following configuration files are used by the path configuration:
958
959* ``pyvenv.cfg``
960* ``python._pth`` (Windows only)
961* ``pybuilddir.txt`` (Unix only)
962
Victor Stinnerfcdb0272019-09-23 14:45:47 +0200963The ``__PYVENV_LAUNCHER__`` environment variable is used to set
964:c:member:`PyConfig.base_executable`
965
Victor Stinner331a6a52019-05-27 16:39:22 +0200966
967Py_RunMain()
968------------
969
970.. c:function:: int Py_RunMain(void)
971
972 Execute the command (:c:member:`PyConfig.run_command`), the script
973 (:c:member:`PyConfig.run_filename`) or the module
974 (:c:member:`PyConfig.run_module`) specified on the command line or in the
975 configuration.
976
977 By default and when if :option:`-i` option is used, run the REPL.
978
979 Finally, finalizes Python and returns an exit status that can be passed to
980 the ``exit()`` function.
981
982See :ref:`Python Configuration <init-python-config>` for an example of
983customized Python always running in isolated mode using
984:c:func:`Py_RunMain`.
985
986
987Multi-Phase Initialization Private Provisional API
988--------------------------------------------------
989
990This section is a private provisional API introducing multi-phase
991initialization, the core feature of the :pep:`432`:
992
993* "Core" initialization phase, "bare minimum Python":
994
995 * Builtin types;
996 * Builtin exceptions;
997 * Builtin and frozen modules;
998 * The :mod:`sys` module is only partially initialized
Victor Stinner88feaec2019-09-26 03:15:07 +0200999 (ex: :data:`sys.path` doesn't exist yet).
Victor Stinner331a6a52019-05-27 16:39:22 +02001000
1001* "Main" initialization phase, Python is fully initialized:
1002
1003 * Install and configure :mod:`importlib`;
1004 * Apply the :ref:`Path Configuration <init-path-config>`;
1005 * Install signal handlers;
1006 * Finish :mod:`sys` module initialization (ex: create :data:`sys.stdout`
1007 and :data:`sys.path`);
1008 * Enable optional features like :mod:`faulthandler` and :mod:`tracemalloc`;
1009 * Import the :mod:`site` module;
1010 * etc.
1011
1012Private provisional API:
1013
1014* :c:member:`PyConfig._init_main`: if set to 0,
1015 :c:func:`Py_InitializeFromConfig` stops at the "Core" initialization phase.
Victor Stinner252346a2020-05-01 11:33:44 +02001016* :c:member:`PyConfig._isolated_interpreter`: if non-zero,
1017 disallow threads, subprocesses and fork.
Victor Stinner331a6a52019-05-27 16:39:22 +02001018
1019.. c:function:: PyStatus _Py_InitializeMain(void)
1020
1021 Move to the "Main" initialization phase, finish the Python initialization.
1022
1023No module is imported during the "Core" phase and the ``importlib`` module is
1024not configured: the :ref:`Path Configuration <init-path-config>` is only
1025applied during the "Main" phase. It may allow to customize Python in Python to
1026override or tune the :ref:`Path Configuration <init-path-config>`, maybe
Victor Stinner88feaec2019-09-26 03:15:07 +02001027install a custom :data:`sys.meta_path` importer or an import hook, etc.
Victor Stinner331a6a52019-05-27 16:39:22 +02001028
Victor Stinner88feaec2019-09-26 03:15:07 +02001029It may become possible to calculatin the :ref:`Path Configuration
Victor Stinner331a6a52019-05-27 16:39:22 +02001030<init-path-config>` in Python, after the Core phase and before the Main phase,
1031which is one of the :pep:`432` motivation.
1032
1033The "Core" phase is not properly defined: what should be and what should
1034not be available at this phase is not specified yet. The API is marked
1035as private and provisional: the API can be modified or even be removed
1036anytime until a proper public API is designed.
1037
1038Example running Python code between "Core" and "Main" initialization
1039phases::
1040
1041 void init_python(void)
1042 {
1043 PyStatus status;
Victor Stinner8462a492019-10-01 12:06:16 +02001044
Victor Stinner331a6a52019-05-27 16:39:22 +02001045 PyConfig config;
Victor Stinner8462a492019-10-01 12:06:16 +02001046 PyConfig_InitPythonConfig(&config);
Victor Stinner331a6a52019-05-27 16:39:22 +02001047 config._init_main = 0;
1048
1049 /* ... customize 'config' configuration ... */
1050
1051 status = Py_InitializeFromConfig(&config);
1052 PyConfig_Clear(&config);
1053 if (PyStatus_Exception(status)) {
1054 Py_ExitStatusException(status);
1055 }
1056
1057 /* Use sys.stderr because sys.stdout is only created
1058 by _Py_InitializeMain() */
1059 int res = PyRun_SimpleString(
1060 "import sys; "
1061 "print('Run Python code before _Py_InitializeMain', "
1062 "file=sys.stderr)");
1063 if (res < 0) {
1064 exit(1);
1065 }
1066
1067 /* ... put more configuration code here ... */
1068
1069 status = _Py_InitializeMain();
1070 if (PyStatus_Exception(status)) {
1071 Py_ExitStatusException(status);
1072 }
1073 }