blob: abf8b3dd222ef8c786d349d306ae77232aae0fc7 [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 Stinnerdedaac02020-06-08 18:44:50 +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
427 .. c:member:: wchar_t* base_exec_prefix
428
429 :data:`sys.base_exec_prefix`.
430
Victor Stinnerfcdb0272019-09-23 14:45:47 +0200431 .. c:member:: wchar_t* base_executable
432
433 :data:`sys._base_executable`: ``__PYVENV_LAUNCHER__`` environment
434 variable value, or copy of :c:member:`PyConfig.executable`.
435
Victor Stinner331a6a52019-05-27 16:39:22 +0200436 .. c:member:: wchar_t* base_prefix
437
438 :data:`sys.base_prefix`.
439
440 .. c:member:: int buffered_stdio
441
442 If equals to 0, enable unbuffered mode, making the stdout and stderr
443 streams unbuffered.
444
445 stdin is always opened in buffered mode.
446
447 .. c:member:: int bytes_warning
448
449 If equals to 1, issue a warning when comparing :class:`bytes` or
450 :class:`bytearray` with :class:`str`, or comparing :class:`bytes` with
451 :class:`int`. If equal or greater to 2, raise a :exc:`BytesWarning`
452 exception.
453
454 .. c:member:: wchar_t* check_hash_pycs_mode
455
456 Control the validation behavior of hash-based ``.pyc`` files (see
457 :pep:`552`): :option:`--check-hash-based-pycs` command line option value.
458
459 Valid values: ``always``, ``never`` and ``default``.
460
461 The default value is: ``default``.
462
463 .. c:member:: int configure_c_stdio
464
465 If non-zero, configure C standard streams (``stdio``, ``stdout``,
466 ``stdout``). For example, set their mode to ``O_BINARY`` on Windows.
467
468 .. c:member:: int dev_mode
469
Victor Stinnerb9783d22020-01-24 10:22:18 +0100470 If non-zero, enable the :ref:`Python Development Mode <devmode>`.
Victor Stinner331a6a52019-05-27 16:39:22 +0200471
472 .. c:member:: int dump_refs
473
474 If non-zero, dump all objects which are still alive at exit.
475
Hai Shia7847592020-02-17 17:18:19 +0800476 ``Py_TRACE_REFS`` macro must be defined in build.
Victor Stinner331a6a52019-05-27 16:39:22 +0200477
478 .. c:member:: wchar_t* exec_prefix
479
480 :data:`sys.exec_prefix`.
481
482 .. c:member:: wchar_t* executable
483
484 :data:`sys.executable`.
485
486 .. c:member:: int faulthandler
487
Victor Stinner88feaec2019-09-26 03:15:07 +0200488 If non-zero, call :func:`faulthandler.enable` at startup.
Victor Stinner331a6a52019-05-27 16:39:22 +0200489
490 .. c:member:: wchar_t* filesystem_encoding
491
492 Filesystem encoding, :func:`sys.getfilesystemencoding`.
493
494 .. c:member:: wchar_t* filesystem_errors
495
496 Filesystem encoding errors, :func:`sys.getfilesystemencodeerrors`.
497
498 .. c:member:: unsigned long hash_seed
499 .. c:member:: int use_hash_seed
500
501 Randomized hash function seed.
502
503 If :c:member:`~PyConfig.use_hash_seed` is zero, a seed is chosen randomly
504 at Pythonstartup, and :c:member:`~PyConfig.hash_seed` is ignored.
505
506 .. c:member:: wchar_t* home
507
508 Python home directory.
509
Victor Stinner88feaec2019-09-26 03:15:07 +0200510 Initialized from :envvar:`PYTHONHOME` environment variable value by
511 default.
512
Victor Stinner331a6a52019-05-27 16:39:22 +0200513 .. c:member:: int import_time
514
515 If non-zero, profile import time.
516
517 .. c:member:: int inspect
518
519 Enter interactive mode after executing a script or a command.
520
521 .. c:member:: int install_signal_handlers
522
523 Install signal handlers?
524
525 .. c:member:: int interactive
526
527 Interactive mode.
528
529 .. c:member:: int isolated
530
531 If greater than 0, enable isolated mode:
532
533 * :data:`sys.path` contains neither the script's directory (computed from
534 ``argv[0]`` or the current directory) nor the user's site-packages
535 directory.
536 * Python REPL doesn't import :mod:`readline` nor enable default readline
537 configuration on interactive prompts.
538 * Set :c:member:`~PyConfig.use_environment` and
539 :c:member:`~PyConfig.user_site_directory` to 0.
540
541 .. c:member:: int legacy_windows_stdio
542
543 If non-zero, use :class:`io.FileIO` instead of
544 :class:`io.WindowsConsoleIO` for :data:`sys.stdin`, :data:`sys.stdout`
545 and :data:`sys.stderr`.
546
547 Only available on Windows. ``#ifdef MS_WINDOWS`` macro can be used for
548 Windows specific code.
549
550 .. c:member:: int malloc_stats
551
552 If non-zero, dump statistics on :ref:`Python pymalloc memory allocator
553 <pymalloc>` at exit.
554
555 The option is ignored if Python is built using ``--without-pymalloc``.
556
557 .. c:member:: wchar_t* pythonpath_env
558
559 Module search paths as a string separated by ``DELIM``
560 (:data:`os.path.pathsep`).
561
562 Initialized from :envvar:`PYTHONPATH` environment variable value by
563 default.
564
565 .. c:member:: PyWideStringList module_search_paths
566 .. c:member:: int module_search_paths_set
567
568 :data:`sys.path`. If :c:member:`~PyConfig.module_search_paths_set` is
569 equal to 0, the :c:member:`~PyConfig.module_search_paths` is overridden
Victor Stinner88feaec2019-09-26 03:15:07 +0200570 by the function calculating the :ref:`Path Configuration
Victor Stinner331a6a52019-05-27 16:39:22 +0200571 <init-path-config>`.
572
573 .. c:member:: int optimization_level
574
575 Compilation optimization level:
576
577 * 0: Peephole optimizer (and ``__debug__`` is set to ``True``)
578 * 1: Remove assertions, set ``__debug__`` to ``False``
579 * 2: Strip docstrings
580
581 .. c:member:: int parse_argv
582
583 If non-zero, parse :c:member:`~PyConfig.argv` the same way the regular
584 Python command line arguments, and strip Python arguments from
585 :c:member:`~PyConfig.argv`: see :ref:`Command Line Arguments
586 <using-on-cmdline>`.
587
588 .. c:member:: int parser_debug
589
590 If non-zero, turn on parser debugging output (for expert only, depending
591 on compilation options).
592
593 .. c:member:: int pathconfig_warnings
594
Victor Stinner88feaec2019-09-26 03:15:07 +0200595 If equal to 0, suppress warnings when calculating the :ref:`Path
596 Configuration <init-path-config>` (Unix only, Windows does not log any
597 warning). Otherwise, warnings are written into ``stderr``.
Victor Stinner331a6a52019-05-27 16:39:22 +0200598
599 .. c:member:: wchar_t* prefix
600
601 :data:`sys.prefix`.
602
603 .. c:member:: wchar_t* program_name
604
Victor Stinner88feaec2019-09-26 03:15:07 +0200605 Program name. Used to initialize :c:member:`~PyConfig.executable`, and in
606 early error messages.
Victor Stinner331a6a52019-05-27 16:39:22 +0200607
608 .. c:member:: wchar_t* pycache_prefix
609
Victor Stinner88feaec2019-09-26 03:15:07 +0200610 :data:`sys.pycache_prefix`: ``.pyc`` cache prefix.
611
Serhiy Storchakae835b312019-10-30 21:37:16 +0200612 If ``NULL``, :data:`sys.pycache_prefix` is set to ``None``.
Victor Stinner331a6a52019-05-27 16:39:22 +0200613
614 .. c:member:: int quiet
615
616 Quiet mode. For example, don't display the copyright and version messages
Victor Stinner88feaec2019-09-26 03:15:07 +0200617 in interactive mode.
Victor Stinner331a6a52019-05-27 16:39:22 +0200618
619 .. c:member:: wchar_t* run_command
620
Victor Stinner88feaec2019-09-26 03:15:07 +0200621 ``python3 -c COMMAND`` argument. Used by :c:func:`Py_RunMain`.
Victor Stinner331a6a52019-05-27 16:39:22 +0200622
623 .. c:member:: wchar_t* run_filename
624
Victor Stinner88feaec2019-09-26 03:15:07 +0200625 ``python3 FILENAME`` argument. Used by :c:func:`Py_RunMain`.
Victor Stinner331a6a52019-05-27 16:39:22 +0200626
627 .. c:member:: wchar_t* run_module
628
Victor Stinner88feaec2019-09-26 03:15:07 +0200629 ``python3 -m MODULE`` argument. Used by :c:func:`Py_RunMain`.
Victor Stinner331a6a52019-05-27 16:39:22 +0200630
Victor Stinner331a6a52019-05-27 16:39:22 +0200631 .. c:member:: int show_ref_count
632
633 Show total reference count at exit?
634
Victor Stinner88feaec2019-09-26 03:15:07 +0200635 Set to 1 by :option:`-X showrefcount <-X>` command line option.
636
Victor Stinner331a6a52019-05-27 16:39:22 +0200637 Need a debug build of Python (``Py_REF_DEBUG`` macro must be defined).
638
639 .. c:member:: int site_import
640
641 Import the :mod:`site` module at startup?
642
643 .. c:member:: int skip_source_first_line
644
645 Skip the first line of the source?
646
647 .. c:member:: wchar_t* stdio_encoding
648 .. c:member:: wchar_t* stdio_errors
649
650 Encoding and encoding errors of :data:`sys.stdin`, :data:`sys.stdout` and
651 :data:`sys.stderr`.
652
653 .. c:member:: int tracemalloc
654
Victor Stinner88feaec2019-09-26 03:15:07 +0200655 If non-zero, call :func:`tracemalloc.start` at startup.
Victor Stinner331a6a52019-05-27 16:39:22 +0200656
657 .. c:member:: int use_environment
658
659 If greater than 0, use :ref:`environment variables <using-on-envvars>`.
660
661 .. c:member:: int user_site_directory
662
663 If non-zero, add user site directory to :data:`sys.path`.
664
665 .. c:member:: int verbose
666
667 If non-zero, enable verbose mode.
668
669 .. c:member:: PyWideStringList warnoptions
670
Victor Stinnerfb4ae152019-09-30 01:40:17 +0200671 :data:`sys.warnoptions`: options of the :mod:`warnings` module to build
672 warnings filters: lowest to highest priority.
673
674 The :mod:`warnings` module adds :data:`sys.warnoptions` in the reverse
675 order: the last :c:member:`PyConfig.warnoptions` item becomes the first
676 item of :data:`warnings.filters` which is checked first (highest
677 priority).
Victor Stinner331a6a52019-05-27 16:39:22 +0200678
679 .. c:member:: int write_bytecode
680
681 If non-zero, write ``.pyc`` files.
682
Victor Stinner88feaec2019-09-26 03:15:07 +0200683 :data:`sys.dont_write_bytecode` is initialized to the inverted value of
684 :c:member:`~PyConfig.write_bytecode`.
685
Victor Stinner331a6a52019-05-27 16:39:22 +0200686 .. c:member:: PyWideStringList xoptions
687
688 :data:`sys._xoptions`.
689
Victor Stinner1def7752020-04-23 03:03:24 +0200690 .. c:member:: int _use_peg_parser
691
692 Enable PEG parser? Default: 1.
693
694 Set to 0 by :option:`-X oldparser <-X>` and :envvar:`PYTHONOLDPARSER`.
695
696 See also :pep:`617`.
697
698 .. deprecated-removed:: 3.9 3.10
699
Victor Stinner331a6a52019-05-27 16:39:22 +0200700If ``parse_argv`` is non-zero, ``argv`` arguments are parsed the same
701way the regular Python parses command line arguments, and Python
702arguments are stripped from ``argv``: see :ref:`Command Line Arguments
703<using-on-cmdline>`.
704
705The ``xoptions`` options are parsed to set other options: see :option:`-X`
706option.
707
Victor Stinnerc6e5c112020-02-03 15:17:15 +0100708.. versionchanged:: 3.9
709
710 The ``show_alloc_count`` field has been removed.
711
Victor Stinner331a6a52019-05-27 16:39:22 +0200712
713Initialization with PyConfig
714----------------------------
715
716Function to initialize Python:
717
718.. c:function:: PyStatus Py_InitializeFromConfig(const PyConfig *config)
719
720 Initialize Python from *config* configuration.
721
722The caller is responsible to handle exceptions (error or exit) using
723:c:func:`PyStatus_Exception` and :c:func:`Py_ExitStatusException`.
724
Victor Stinner88feaec2019-09-26 03:15:07 +0200725If ``PyImport_FrozenModules``, ``PyImport_AppendInittab()`` or
726``PyImport_ExtendInittab()`` are used, they must be set or called after Python
Victor Stinner331a6a52019-05-27 16:39:22 +0200727preinitialization and before the Python initialization.
728
729Example setting the program name::
730
731 void init_python(void)
732 {
733 PyStatus status;
Victor Stinner331a6a52019-05-27 16:39:22 +0200734
Victor Stinner8462a492019-10-01 12:06:16 +0200735 PyConfig config;
736 PyConfig_InitPythonConfig(&config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200737
738 /* Set the program name. Implicitly preinitialize Python. */
739 status = PyConfig_SetString(&config, &config.program_name,
740 L"/path/to/my_program");
741 if (PyStatus_Exception(status)) {
742 goto fail;
743 }
744
745 status = Py_InitializeFromConfig(&config);
746 if (PyStatus_Exception(status)) {
747 goto fail;
748 }
749 PyConfig_Clear(&config);
750 return;
751
752 fail:
753 PyConfig_Clear(&config);
754 Py_ExitStatusException(status);
755 }
756
757More complete example modifying the default configuration, read the
758configuration, and then override some parameters::
759
760 PyStatus init_python(const char *program_name)
761 {
762 PyStatus status;
Victor Stinner331a6a52019-05-27 16:39:22 +0200763
Victor Stinner8462a492019-10-01 12:06:16 +0200764 PyConfig config;
765 PyConfig_InitPythonConfig(&config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200766
Gurupad Hegde6c7bb382019-12-28 17:16:02 -0500767 /* Set the program name before reading the configuration
Victor Stinner331a6a52019-05-27 16:39:22 +0200768 (decode byte string from the locale encoding).
769
770 Implicitly preinitialize Python. */
771 status = PyConfig_SetBytesString(&config, &config.program_name,
772 program_name);
773 if (PyStatus_Exception(status)) {
774 goto done;
775 }
776
777 /* Read all configuration at once */
778 status = PyConfig_Read(&config);
779 if (PyStatus_Exception(status)) {
780 goto done;
781 }
782
783 /* Append our custom search path to sys.path */
784 status = PyWideStringList_Append(&config.module_search_paths,
Victor Stinner88feaec2019-09-26 03:15:07 +0200785 L"/path/to/more/modules");
Victor Stinner331a6a52019-05-27 16:39:22 +0200786 if (PyStatus_Exception(status)) {
787 goto done;
788 }
789
790 /* Override executable computed by PyConfig_Read() */
791 status = PyConfig_SetString(&config, &config.executable,
792 L"/path/to/my_executable");
793 if (PyStatus_Exception(status)) {
794 goto done;
795 }
796
797 status = Py_InitializeFromConfig(&config);
798
799 done:
800 PyConfig_Clear(&config);
801 return status;
802 }
803
804
805.. _init-isolated-conf:
806
807Isolated Configuration
808----------------------
809
810:c:func:`PyPreConfig_InitIsolatedConfig` and
811:c:func:`PyConfig_InitIsolatedConfig` functions create a configuration to
812isolate Python from the system. For example, to embed Python into an
813application.
814
815This configuration ignores global configuration variables, environments
Victor Stinner88feaec2019-09-26 03:15:07 +0200816variables, command line arguments (:c:member:`PyConfig.argv` is not parsed)
817and user site directory. The C standard streams (ex: ``stdout``) and the
818LC_CTYPE locale are left unchanged. Signal handlers are not installed.
Victor Stinner331a6a52019-05-27 16:39:22 +0200819
820Configuration files are still used with this configuration. Set the
821:ref:`Path Configuration <init-path-config>` ("output fields") to ignore these
822configuration files and avoid the function computing the default path
823configuration.
824
825
826.. _init-python-config:
827
828Python Configuration
829--------------------
830
831:c:func:`PyPreConfig_InitPythonConfig` and :c:func:`PyConfig_InitPythonConfig`
832functions create a configuration to build a customized Python which behaves as
833the regular Python.
834
835Environments variables and command line arguments are used to configure
836Python, whereas global configuration variables are ignored.
837
838This function enables C locale coercion (:pep:`538`) and UTF-8 Mode
839(:pep:`540`) depending on the LC_CTYPE locale, :envvar:`PYTHONUTF8` and
840:envvar:`PYTHONCOERCECLOCALE` environment variables.
841
842Example of customized Python always running in isolated mode::
843
844 int main(int argc, char **argv)
845 {
Victor Stinner331a6a52019-05-27 16:39:22 +0200846 PyStatus status;
Victor Stinner8462a492019-10-01 12:06:16 +0200847
Victor Stinner441b10c2019-09-28 04:28:35 +0200848 PyConfig config;
Victor Stinner8462a492019-10-01 12:06:16 +0200849 PyConfig_InitPythonConfig(&config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200850 config.isolated = 1;
851
852 /* Decode command line arguments.
853 Implicitly preinitialize Python (in isolated mode). */
854 status = PyConfig_SetBytesArgv(&config, argc, argv);
855 if (PyStatus_Exception(status)) {
856 goto fail;
857 }
858
859 status = Py_InitializeFromConfig(&config);
860 if (PyStatus_Exception(status)) {
861 goto fail;
862 }
863 PyConfig_Clear(&config);
864
865 return Py_RunMain();
866
867 fail:
868 PyConfig_Clear(&config);
869 if (PyStatus_IsExit(status)) {
870 return status.exitcode;
871 }
872 /* Display the error message and exit the process with
873 non-zero exit code */
874 Py_ExitStatusException(status);
875 }
876
877
878.. _init-path-config:
879
880Path Configuration
881------------------
882
883:c:type:`PyConfig` contains multiple fields for the path configuration:
884
Victor Stinner8bf39b62019-09-26 02:22:35 +0200885* Path configuration inputs:
Victor Stinner331a6a52019-05-27 16:39:22 +0200886
887 * :c:member:`PyConfig.home`
Victor Stinner331a6a52019-05-27 16:39:22 +0200888 * :c:member:`PyConfig.pathconfig_warnings`
Victor Stinnerfcdb0272019-09-23 14:45:47 +0200889 * :c:member:`PyConfig.program_name`
890 * :c:member:`PyConfig.pythonpath_env`
Victor Stinner8bf39b62019-09-26 02:22:35 +0200891 * current working directory: to get absolute paths
892 * ``PATH`` environment variable to get the program full path
893 (from :c:member:`PyConfig.program_name`)
894 * ``__PYVENV_LAUNCHER__`` environment variable
895 * (Windows only) Application paths in the registry under
896 "Software\Python\PythonCore\X.Y\PythonPath" of HKEY_CURRENT_USER and
897 HKEY_LOCAL_MACHINE (where X.Y is the Python version).
Victor Stinner331a6a52019-05-27 16:39:22 +0200898
899* Path configuration output fields:
900
Victor Stinner8bf39b62019-09-26 02:22:35 +0200901 * :c:member:`PyConfig.base_exec_prefix`
Victor Stinnerfcdb0272019-09-23 14:45:47 +0200902 * :c:member:`PyConfig.base_executable`
Victor Stinner8bf39b62019-09-26 02:22:35 +0200903 * :c:member:`PyConfig.base_prefix`
Victor Stinner331a6a52019-05-27 16:39:22 +0200904 * :c:member:`PyConfig.exec_prefix`
905 * :c:member:`PyConfig.executable`
Victor Stinner331a6a52019-05-27 16:39:22 +0200906 * :c:member:`PyConfig.module_search_paths_set`,
907 :c:member:`PyConfig.module_search_paths`
Victor Stinner8bf39b62019-09-26 02:22:35 +0200908 * :c:member:`PyConfig.prefix`
Victor Stinner331a6a52019-05-27 16:39:22 +0200909
Victor Stinner8bf39b62019-09-26 02:22:35 +0200910If at least one "output field" is not set, Python calculates the path
Victor Stinner331a6a52019-05-27 16:39:22 +0200911configuration to fill unset fields. If
912:c:member:`~PyConfig.module_search_paths_set` is equal to 0,
Min ho Kim39d87b52019-08-31 06:21:19 +1000913:c:member:`~PyConfig.module_search_paths` is overridden and
Victor Stinner331a6a52019-05-27 16:39:22 +0200914:c:member:`~PyConfig.module_search_paths_set` is set to 1.
915
Victor Stinner8bf39b62019-09-26 02:22:35 +0200916It is possible to completely ignore the function calculating the default
Victor Stinner331a6a52019-05-27 16:39:22 +0200917path configuration by setting explicitly all path configuration output
918fields listed above. A string is considered as set even if it is non-empty.
919``module_search_paths`` is considered as set if
920``module_search_paths_set`` is set to 1. In this case, path
921configuration input fields are ignored as well.
922
923Set :c:member:`~PyConfig.pathconfig_warnings` to 0 to suppress warnings when
Victor Stinner8bf39b62019-09-26 02:22:35 +0200924calculating the path configuration (Unix only, Windows does not log any warning).
Victor Stinner331a6a52019-05-27 16:39:22 +0200925
926If :c:member:`~PyConfig.base_prefix` or :c:member:`~PyConfig.base_exec_prefix`
927fields are not set, they inherit their value from :c:member:`~PyConfig.prefix`
928and :c:member:`~PyConfig.exec_prefix` respectively.
929
930:c:func:`Py_RunMain` and :c:func:`Py_Main` modify :data:`sys.path`:
931
932* If :c:member:`~PyConfig.run_filename` is set and is a directory which contains a
933 ``__main__.py`` script, prepend :c:member:`~PyConfig.run_filename` to
934 :data:`sys.path`.
935* If :c:member:`~PyConfig.isolated` is zero:
936
937 * If :c:member:`~PyConfig.run_module` is set, prepend the current directory
938 to :data:`sys.path`. Do nothing if the current directory cannot be read.
939 * If :c:member:`~PyConfig.run_filename` is set, prepend the directory of the
940 filename to :data:`sys.path`.
941 * Otherwise, prepend an empty string to :data:`sys.path`.
942
943If :c:member:`~PyConfig.site_import` is non-zero, :data:`sys.path` can be
944modified by the :mod:`site` module. If
945:c:member:`~PyConfig.user_site_directory` is non-zero and the user's
946site-package directory exists, the :mod:`site` module appends the user's
947site-package directory to :data:`sys.path`.
948
949The following configuration files are used by the path configuration:
950
951* ``pyvenv.cfg``
952* ``python._pth`` (Windows only)
953* ``pybuilddir.txt`` (Unix only)
954
Victor Stinnerfcdb0272019-09-23 14:45:47 +0200955The ``__PYVENV_LAUNCHER__`` environment variable is used to set
956:c:member:`PyConfig.base_executable`
957
Victor Stinner331a6a52019-05-27 16:39:22 +0200958
959Py_RunMain()
960------------
961
962.. c:function:: int Py_RunMain(void)
963
964 Execute the command (:c:member:`PyConfig.run_command`), the script
965 (:c:member:`PyConfig.run_filename`) or the module
966 (:c:member:`PyConfig.run_module`) specified on the command line or in the
967 configuration.
968
969 By default and when if :option:`-i` option is used, run the REPL.
970
971 Finally, finalizes Python and returns an exit status that can be passed to
972 the ``exit()`` function.
973
974See :ref:`Python Configuration <init-python-config>` for an example of
975customized Python always running in isolated mode using
976:c:func:`Py_RunMain`.
977
978
Victor Stinnerdedaac02020-06-08 18:44:50 +0200979Py_GetArgcArgv()
980----------------
981
982.. c:function:: void Py_GetArgcArgv(int *argc, wchar_t ***argv)
983
984 Get the original command line arguments, before Python modified them.
985
986
Victor Stinner331a6a52019-05-27 16:39:22 +0200987Multi-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 }