Debian Codegraph @

Doc/c-api/interp-lifecycle.rst

raw
1 .. highlight:: c
2
3 .. _initialization:
4
5 Interpreter initialization and finalization
6 ===========================================
7
8 See :ref:`Python Initialization Configuration <init-config>` for details
9 on how to configure the interpreter prior to initialization.
10
11 .. _pre-init-safe:
12
13 Before Python initialization
14 ----------------------------
15
16 In an application embedding Python, the :c:func:`Py_Initialize` function must
17 be called before using any other Python/C API functions; with the exception of
18 a few functions and the :ref:`global configuration variables
19 <global-conf-vars>`.
20
21 The following functions can be safely called before Python is initialized:
22
23 * Functions that initialize the interpreter:
24
25 * :c:func:`Py_Initialize`
26 * :c:func:`Py_InitializeEx`
27 * :c:func:`Py_InitializeFromConfig`
28 * :c:func:`Py_BytesMain`
29 * :c:func:`Py_Main`
30 * the runtime pre-initialization functions covered in :ref:`init-config`
31
32 * Configuration functions:
33
34 * :c:func:`PyImport_AppendInittab`
35 * :c:func:`PyImport_ExtendInittab`
36 * :c:func:`!PyInitFrozenExtensions`
37 * :c:func:`PyMem_SetAllocator`
38 * :c:func:`PyMem_SetupDebugHooks`
39 * :c:func:`PyObject_SetArenaAllocator`
40 * :c:func:`Py_SetProgramName`
41 * :c:func:`Py_SetPythonHome`
42 * the configuration functions covered in :ref:`init-config`
43
44 * Informative functions:
45
46 * :c:func:`Py_IsInitialized`
47 * :c:func:`PyMem_GetAllocator`
48 * :c:func:`PyObject_GetArenaAllocator`
49 * :c:func:`Py_GetBuildInfo`
50 * :c:func:`Py_GetCompiler`
51 * :c:func:`Py_GetCopyright`
52 * :c:func:`Py_GetPlatform`
53 * :c:func:`Py_GetVersion`
54 * :c:func:`Py_IsInitialized`
55
56 * Utilities:
57
58 * :c:func:`Py_DecodeLocale`
59 * the status reporting and utility functions covered in :ref:`init-config`
60
61 * Memory allocators:
62
63 * :c:func:`PyMem_RawMalloc`
64 * :c:func:`PyMem_RawRealloc`
65 * :c:func:`PyMem_RawCalloc`
66 * :c:func:`PyMem_RawFree`
67
68 * Synchronization:
69
70 * :c:func:`PyMutex_Lock`
71 * :c:func:`PyMutex_Unlock`
72
73 .. note::
74
75 Despite their apparent similarity to some of the functions listed above,
76 the following functions **should not be called** before the interpreter has
77 been initialized: :c:func:`Py_EncodeLocale`, :c:func:`PyEval_InitThreads`, and
78 :c:func:`Py_RunMain`.
79
80
81 .. _global-conf-vars:
82
83 Global configuration variables
84 ------------------------------
85
86 Python has variables for the global configuration to control different features
87 and options. By default, these flags are controlled by :ref:`command line
88 options <using-on-interface-options>`.
89
90 When a flag is set by an option, the value of the flag is the number of times
91 that the option was set. For example, ``-b`` sets :c:data:`Py_BytesWarningFlag`
92 to 1 and ``-bb`` sets :c:data:`Py_BytesWarningFlag` to 2.
93
94
95 .. c:var:: int Py_BytesWarningFlag
96
97 This API is kept for backward compatibility: setting
98 :c:member:`PyConfig.bytes_warning` should be used instead, see :ref:`Python
99 Initialization Configuration <init-config>`.
100
101 Issue a warning when comparing :class:`bytes` or :class:`bytearray` with
102 :class:`str` or :class:`bytes` with :class:`int`. Issue an error if greater
103 or equal to ``2``.
104
105 Set by the :option:`-b` option.
106
107 .. deprecated-removed:: 3.12 3.15
108
109
110 .. c:var:: int Py_DebugFlag
111
112 This API is kept for backward compatibility: setting
113 :c:member:`PyConfig.parser_debug` should be used instead, see :ref:`Python
114 Initialization Configuration <init-config>`.
115
116 Turn on parser debugging output (for expert only, depending on compilation
117 options).
118
119 Set by the :option:`-d` option and the :envvar:`PYTHONDEBUG` environment
120 variable.
121
122 .. deprecated-removed:: 3.12 3.15
123
124
125 .. c:var:: int Py_DontWriteBytecodeFlag
126
127 This API is kept for backward compatibility: setting
128 :c:member:`PyConfig.write_bytecode` should be used instead, see :ref:`Python
129 Initialization Configuration <init-config>`.
130
131 If set to non-zero, Python won't try to write ``.pyc`` files on the
132 import of source modules.
133
134 Set by the :option:`-B` option and the :envvar:`PYTHONDONTWRITEBYTECODE`
135 environment variable.
136
137 .. deprecated-removed:: 3.12 3.15
138
139
140 .. c:var:: int Py_FrozenFlag
141
142 This API is kept for backward compatibility: setting
143 :c:member:`PyConfig.pathconfig_warnings` should be used instead, see
144 :ref:`Python Initialization Configuration <init-config>`.
145
146 Private flag used by ``_freeze_module`` and ``frozenmain`` programs.
147
148 .. deprecated-removed:: 3.12 3.15
149
150
151 .. c:var:: int Py_HashRandomizationFlag
152
153 This API is kept for backward compatibility: setting
154 :c:member:`PyConfig.hash_seed` and :c:member:`PyConfig.use_hash_seed` should
155 be used instead, see :ref:`Python Initialization Configuration
156 <init-config>`.
157
158 Set to ``1`` if the :envvar:`PYTHONHASHSEED` environment variable is set to
159 a non-empty string.
160
161 If the flag is non-zero, read the :envvar:`PYTHONHASHSEED` environment
162 variable to initialize the secret hash seed.
163
164 .. deprecated-removed:: 3.12 3.15
165
166
167 .. c:var:: int Py_IgnoreEnvironmentFlag
168
169 This API is kept for backward compatibility: setting
170 :c:member:`PyConfig.use_environment` should be used instead, see
171 :ref:`Python Initialization Configuration <init-config>`.
172
173 Ignore all :envvar:`!PYTHON*` environment variables, e.g.
174 :envvar:`PYTHONPATH` and :envvar:`PYTHONHOME`, that might be set.
175
176 Set by the :option:`-E` and :option:`-I` options.
177
178 .. deprecated-removed:: 3.12 3.15
179
180
181 .. c:var:: int Py_InspectFlag
182
183 This API is kept for backward compatibility: setting
184 :c:member:`PyConfig.inspect` should be used instead, see
185 :ref:`Python Initialization Configuration <init-config>`.
186
187 When a script is passed as first argument or the :option:`-c` option is used,
188 enter interactive mode after executing the script or the command, even when
189 :data:`sys.stdin` does not appear to be a terminal.
190
191 Set by the :option:`-i` option and the :envvar:`PYTHONINSPECT` environment
192 variable.
193
194 .. deprecated-removed:: 3.12 3.15
195
196
197 .. c:var:: int Py_InteractiveFlag
198
199 This API is kept for backward compatibility: setting
200 :c:member:`PyConfig.interactive` should be used instead, see
201 :ref:`Python Initialization Configuration <init-config>`.
202
203 Set by the :option:`-i` option.
204
205 .. deprecated-removed:: 3.12 3.15
206
207
208 .. c:var:: int Py_IsolatedFlag
209
210 This API is kept for backward compatibility: setting
211 :c:member:`PyConfig.isolated` should be used instead, see
212 :ref:`Python Initialization Configuration <init-config>`.
213
214 Run Python in isolated mode. In isolated mode :data:`sys.path` contains
215 neither the script's directory nor the user's site-packages directory.
216
217 Set by the :option:`-I` option.
218
219 .. versionadded:: 3.4
220
221 .. deprecated-removed:: 3.12 3.15
222
223
224 .. c:var:: int Py_LegacyWindowsFSEncodingFlag
225
226 This API is kept for backward compatibility: setting
227 :c:member:`PyPreConfig.legacy_windows_fs_encoding` should be used instead, see
228 :ref:`Python Initialization Configuration <init-config>`.
229
230 If the flag is non-zero, use the ``mbcs`` encoding with ``replace`` error
231 handler, instead of the UTF-8 encoding with ``surrogatepass`` error handler,
232 for the :term:`filesystem encoding and error handler`.
233
234 Set to ``1`` if the :envvar:`PYTHONLEGACYWINDOWSFSENCODING` environment
235 variable is set to a non-empty string.
236
237 See :pep:`529` for more details.
238
239 .. availability:: Windows.
240
241 .. deprecated-removed:: 3.12 3.15
242
243
244 .. c:var:: int Py_LegacyWindowsStdioFlag
245
246 This API is kept for backward compatibility: setting
247 :c:member:`PyConfig.legacy_windows_stdio` should be used instead, see
248 :ref:`Python Initialization Configuration <init-config>`.
249
250 If the flag is non-zero, use :class:`io.FileIO` instead of
251 :class:`!io._WindowsConsoleIO` for :mod:`sys` standard streams.
252
253 Set to ``1`` if the :envvar:`PYTHONLEGACYWINDOWSSTDIO` environment
254 variable is set to a non-empty string.
255
256 See :pep:`528` for more details.
257
258 .. availability:: Windows.
259
260 .. deprecated-removed:: 3.12 3.15
261
262
263 .. c:var:: int Py_NoSiteFlag
264
265 This API is kept for backward compatibility: setting
266 :c:member:`PyConfig.site_import` should be used instead, see
267 :ref:`Python Initialization Configuration <init-config>`.
268
269 Disable the import of the module :mod:`site` and the site-dependent
270 manipulations of :data:`sys.path` that it entails. Also disable these
271 manipulations if :mod:`site` is explicitly imported later (call
272 :func:`site.main` if you want them to be triggered).
273
274 Set by the :option:`-S` option.
275
276 .. deprecated-removed:: 3.12 3.15
277
278
279 .. c:var:: int Py_NoUserSiteDirectory
280
281 This API is kept for backward compatibility: setting
282 :c:member:`PyConfig.user_site_directory` should be used instead, see
283 :ref:`Python Initialization Configuration <init-config>`.
284
285 Don't add the :data:`user site-packages directory <site.USER_SITE>` to
286 :data:`sys.path`.
287
288 Set by the :option:`-s` and :option:`-I` options, and the
289 :envvar:`PYTHONNOUSERSITE` environment variable.
290
291 .. deprecated-removed:: 3.12 3.15
292
293
294 .. c:var:: int Py_OptimizeFlag
295
296 This API is kept for backward compatibility: setting
297 :c:member:`PyConfig.optimization_level` should be used instead, see
298 :ref:`Python Initialization Configuration <init-config>`.
299
300 Set by the :option:`-O` option and the :envvar:`PYTHONOPTIMIZE` environment
301 variable.
302
303 .. deprecated-removed:: 3.12 3.15
304
305
306 .. c:var:: int Py_QuietFlag
307
308 This API is kept for backward compatibility: setting
309 :c:member:`PyConfig.quiet` should be used instead, see :ref:`Python
310 Initialization Configuration <init-config>`.
311
312 Don't display the copyright and version messages even in interactive mode.
313
314 Set by the :option:`-q` option.
315
316 .. versionadded:: 3.2
317
318 .. deprecated-removed:: 3.12 3.15
319
320
321 .. c:var:: int Py_UnbufferedStdioFlag
322
323 This API is kept for backward compatibility: setting
324 :c:member:`PyConfig.buffered_stdio` should be used instead, see :ref:`Python
325 Initialization Configuration <init-config>`.
326
327 Force the stdout and stderr streams to be unbuffered.
328
329 Set by the :option:`-u` option and the :envvar:`PYTHONUNBUFFERED`
330 environment variable.
331
332 .. deprecated-removed:: 3.12 3.15
333
334
335 .. c:var:: int Py_VerboseFlag
336
337 This API is kept for backward compatibility: setting
338 :c:member:`PyConfig.verbose` should be used instead, see :ref:`Python
339 Initialization Configuration <init-config>`.
340
341 Print a message each time a module is initialized, showing the place
342 (filename or built-in module) from which it is loaded. If greater or equal
343 to ``2``, print a message for each file that is checked for when
344 searching for a module. Also provides information on module cleanup at exit.
345
346 Set by the :option:`-v` option and the :envvar:`PYTHONVERBOSE` environment
347 variable.
348
349 .. deprecated-removed:: 3.12 3.15
350
351
352 Initializing and finalizing the interpreter
353 -------------------------------------------
354
355 .. c:function:: void Py_Initialize()
356
357 .. index::
358 single: PyEval_InitThreads()
359 single: modules (in module sys)
360 single: path (in module sys)
361 pair: module; builtins
362 pair: module; __main__
363 pair: module; sys
364 triple: module; search; path
365 single: Py_FinalizeEx (C function)
366
367 Initialize the Python interpreter. In an application embedding Python,
368 this should be called before using any other Python/C API functions; see
369 :ref:`Before Python Initialization <pre-init-safe>` for the few exceptions.
370
371 This initializes the table of loaded modules (``sys.modules``), and creates
372 the fundamental modules :mod:`builtins`, :mod:`__main__` and :mod:`sys`.
373 It also initializes the module search path (``sys.path``). It does not set
374 ``sys.argv``; use the :ref:`Python Initialization Configuration <init-config>`
375 API for that. This is a no-op when called for a second time (without calling
376 :c:func:`Py_FinalizeEx` first). There is no return value; it is a fatal
377 error if the initialization fails.
378
379 Use :c:func:`Py_InitializeFromConfig` to customize the
380 :ref:`Python Initialization Configuration <init-config>`.
381
382 .. note::
383 On Windows, changes the console mode from ``O_TEXT`` to ``O_BINARY``,
384 which will also affect non-Python uses of the console using the C Runtime.
385
386
387 .. c:function:: void Py_InitializeEx(int initsigs)
388
389 This function works like :c:func:`Py_Initialize` if *initsigs* is ``1``. If
390 *initsigs* is ``0``, it skips initialization registration of signal handlers,
391 which may be useful when CPython is embedded as part of a larger application.
392
393 Use :c:func:`Py_InitializeFromConfig` to customize the
394 :ref:`Python Initialization Configuration <init-config>`.
395
396
397 .. c:function:: PyStatus Py_InitializeFromConfig(const PyConfig *config)
398
399 Initialize Python from *config* configuration, as described in
400 :ref:`init-from-config`.
401
402 See the :ref:`init-config` section for details on pre-initializing the
403 interpreter, populating the runtime configuration structure, and querying
404 the returned status structure.
405
406
407 .. c:function:: int Py_IsInitialized()
408
409 Return true (nonzero) when the Python interpreter has been initialized, false
410 (zero) if not. After :c:func:`Py_FinalizeEx` is called, this returns false until
411 :c:func:`Py_Initialize` is called again.
412
413
414 .. c:function:: int Py_IsFinalizing()
415
416 Return true (non-zero) if the main Python interpreter is
417 :term:`shutting down <interpreter shutdown>`. Return false (zero) otherwise.
418
419 .. versionadded:: 3.13
420
421
422 .. c:function:: int Py_FinalizeEx()
423
424 Undo all initializations made by :c:func:`Py_Initialize` and subsequent use of
425 Python/C API functions, and destroy all sub-interpreters (see
426 :c:func:`Py_NewInterpreter` below) that were created and not yet destroyed since
427 the last call to :c:func:`Py_Initialize`. This is a no-op when called for a second
428 time (without calling :c:func:`Py_Initialize` again first).
429
430 Since this is the reverse of :c:func:`Py_Initialize`, it should be called
431 in the same thread with the same interpreter active. That means
432 the main thread and the main interpreter.
433 This should never be called while :c:func:`Py_RunMain` is running.
434
435 Normally the return value is ``0``.
436 If there were errors during finalization (flushing buffered data),
437 ``-1`` is returned.
438
439 Note that Python will do a best effort at freeing all memory allocated by the Python
440 interpreter. Therefore, any C-Extension should make sure to correctly clean up all
441 of the previously allocated PyObjects before using them in subsequent calls to
442 :c:func:`Py_Initialize`. Otherwise it could introduce vulnerabilities and incorrect
443 behavior.
444
445 This function is provided for a number of reasons. An embedding application
446 might want to restart Python without having to restart the application itself.
447 An application that has loaded the Python interpreter from a dynamically
448 loadable library (or DLL) might want to free all memory allocated by Python
449 before unloading the DLL. During a hunt for memory leaks in an application a
450 developer might want to free all memory allocated by Python before exiting from
451 the application.
452
453 **Bugs and caveats:** The destruction of modules and objects in modules is done
454 in random order; this may cause destructors (:meth:`~object.__del__` methods) to fail
455 when they depend on other objects (even functions) or modules. Dynamically
456 loaded extension modules loaded by Python are not unloaded. Small amounts of
457 memory allocated by the Python interpreter may not be freed (if you find a leak,
458 please report it). Memory tied up in circular references between objects is not
459 freed. Interned strings will all be deallocated regardless of their reference count.
460 Some memory allocated by extension modules may not be freed. Some extensions may not
461 work properly if their initialization routine is called more than once; this can
462 happen if an application calls :c:func:`Py_Initialize` and :c:func:`Py_FinalizeEx`
463 more than once. :c:func:`Py_FinalizeEx` must not be called recursively from
464 within itself. Therefore, it must not be called by any code that may be run
465 as part of the interpreter shutdown process, such as :py:mod:`atexit`
466 handlers, object finalizers, or any code that may be run while flushing the
467 stdout and stderr files.
468
469 .. audit-event:: cpython._PySys_ClearAuditHooks "" c.Py_FinalizeEx
470
471 .. versionadded:: 3.6
472
473
474 .. c:function:: void Py_Finalize()
475
476 This is a backwards-compatible version of :c:func:`Py_FinalizeEx` that
477 disregards the return value.
478
479
480 .. c:function:: int Py_BytesMain(int argc, char **argv)
481
482 Similar to :c:func:`Py_Main` but *argv* is an array of bytes strings,
483 allowing the calling application to delegate the text decoding step to
484 the CPython runtime.
485
486 .. versionadded:: 3.8
487
488
489 .. c:function:: int Py_Main(int argc, wchar_t **argv)
490
491 The main program for the standard interpreter, encapsulating a full
492 initialization/finalization cycle, as well as additional
493 behaviour to implement reading configurations settings from the environment
494 and command line, and then executing ``__main__`` in accordance with
495 :ref:`using-on-cmdline`.
496
497 This is made available for programs which wish to support the full CPython
498 command line interface, rather than just embedding a Python runtime in a
499 larger application.
500
501 The *argc* and *argv* parameters are similar to those which are passed to a
502 C program's :c:func:`main` function, except that the *argv* entries are first
503 converted to ``wchar_t`` using :c:func:`Py_DecodeLocale`. It is also
504 important to note that the argument list entries may be modified to point to
505 strings other than those passed in (however, the contents of the strings
506 pointed to by the argument list are not modified).
507
508 The return value is ``2`` if the argument list does not represent a valid
509 Python command line, and otherwise the same as :c:func:`Py_RunMain`.
510
511 In terms of the CPython runtime configuration APIs documented in the
512 :ref:`runtime configuration <init-config>` section (and without accounting
513 for error handling), ``Py_Main`` is approximately equivalent to::
514
515 PyConfig config;
516 PyConfig_InitPythonConfig(&config);
517 PyConfig_SetArgv(&config, argc, argv);
518 Py_InitializeFromConfig(&config);
519 PyConfig_Clear(&config);
520
521 Py_RunMain();
522
523 In normal usage, an embedding application will call this function
524 *instead* of calling :c:func:`Py_Initialize`, :c:func:`Py_InitializeEx` or
525 :c:func:`Py_InitializeFromConfig` directly, and all settings will be applied
526 as described elsewhere in this documentation. If this function is instead
527 called *after* a preceding runtime initialization API call, then exactly
528 which environmental and command line configuration settings will be updated
529 is version dependent (as it depends on which settings correctly support
530 being modified after they have already been set once when the runtime was
531 first initialized).
532
533
534 .. c:function:: int Py_RunMain(void)
535
536 Executes the main module in a fully configured CPython runtime.
537
538 Executes the command (:c:member:`PyConfig.run_command`), the script
539 (:c:member:`PyConfig.run_filename`) or the module
540 (:c:member:`PyConfig.run_module`) specified on the command line or in the
541 configuration. If none of these values are set, runs the interactive Python
542 prompt (REPL) using the ``__main__`` module's global namespace.
543
544 If :c:member:`PyConfig.inspect` is not set (the default), the return value
545 will be ``0`` if the interpreter exits normally (that is, without raising
546 an exception), the exit status of an unhandled :exc:`SystemExit`, or ``1``
547 for any other unhandled exception.
548
549 If :c:member:`PyConfig.inspect` is set (such as when the :option:`-i` option
550 is used), rather than returning when the interpreter exits, execution will
551 instead resume in an interactive Python prompt (REPL) using the ``__main__``
552 module's global namespace. If the interpreter exited with an exception, it
553 is immediately raised in the REPL session. The function return value is
554 then determined by the way the *REPL session* terminates: ``0``, ``1``, or
555 the status of a :exc:`SystemExit`, as specified above.
556
557 This function always finalizes the Python interpreter before it returns.
558
559 See :ref:`Python Configuration <init-python-config>` for an example of a
560 customized Python that always runs in isolated mode using
561 :c:func:`Py_RunMain`.
562
563 .. c:function:: int PyUnstable_AtExit(PyInterpreterState *interp, void (*func)(void *), void *data)
564
565 Register an :mod:`atexit` callback for the target interpreter *interp*.
566 This is similar to :c:func:`Py_AtExit`, but takes an explicit interpreter and
567 data pointer for the callback.
568
569 There must be an :term:`attached thread state` for *interp*.
570
571 .. versionadded:: 3.13
572
573
574 .. _cautions-regarding-runtime-finalization:
575
576 Cautions regarding runtime finalization
577 ---------------------------------------
578
579 In the late stage of :term:`interpreter shutdown`, after attempting to wait for
580 non-daemon threads to exit (though this can be interrupted by
581 :class:`KeyboardInterrupt`) and running the :mod:`atexit` functions, the runtime
582 is marked as *finalizing*: :c:func:`Py_IsFinalizing` and
583 :func:`sys.is_finalizing` return true. At this point, only the *finalization
584 thread* that initiated finalization (typically the main thread) is allowed to
585 acquire the :term:`GIL`.
586
587 If any thread, other than the finalization thread, attempts to attach a :term:`thread state`
588 during finalization, either explicitly or
589 implicitly, the thread enters **a permanently blocked state**
590 where it remains until the program exits. In most cases this is harmless, but this can result
591 in deadlock if a later stage of finalization attempts to acquire a lock owned by the
592 blocked thread, or otherwise waits on the blocked thread.
593
594 Gross? Yes. This prevents random crashes and/or unexpectedly skipped C++
595 finalizations further up the call stack when such threads were forcibly exited
596 here in CPython 3.13 and earlier. The CPython runtime :term:`thread state` C APIs
597 have never had any error reporting or handling expectations at :term:`thread state`
598 attachment time that would've allowed for graceful exit from this situation. Changing that
599 would require new stable C APIs and rewriting the majority of C code in the
600 CPython ecosystem to use those with error handling.
601
602
603 Process-wide parameters
604 -----------------------
605
606 .. c:function:: void Py_SetProgramName(const wchar_t *name)
607
608 .. index::
609 single: Py_Initialize()
610 single: main()
611 single: Py_GetPath()
612
613 This API is kept for backward compatibility: setting
614 :c:member:`PyConfig.program_name` should be used instead, see :ref:`Python
615 Initialization Configuration <init-config>`.
616
617 This function should be called before :c:func:`Py_Initialize` is called for
618 the first time, if it is called at all. It tells the interpreter the value
619 of the ``argv[0]`` argument to the :c:func:`main` function of the program
620 (converted to wide characters).
621 This is used by :c:func:`Py_GetPath` and some other functions below to find
622 the Python run-time libraries relative to the interpreter executable. The
623 default value is ``'python'``. The argument should point to a
624 zero-terminated wide character string in static storage whose contents will not
625 change for the duration of the program's execution. No code in the Python
626 interpreter will change the contents of this storage.
627
628 Use :c:func:`Py_DecodeLocale` to decode a bytes string to get a
629 :c:expr:`wchar_t*` string.
630
631 .. deprecated-removed:: 3.11 3.15
632
633
634 .. c:function:: wchar_t* Py_GetProgramName()
635
636 Return the program name set with :c:member:`PyConfig.program_name`, or the default.
637 The returned string points into static storage; the caller should not modify its
638 value.
639
640 This function should not be called before :c:func:`Py_Initialize`, otherwise
641 it returns ``NULL``.
642
643 .. versionchanged:: 3.10
644 It now returns ``NULL`` if called before :c:func:`Py_Initialize`.
645
646 .. deprecated-removed:: 3.13 3.15
647 Use :c:func:`PyConfig_Get("executable") <PyConfig_Get>`
648 (:data:`sys.executable`) instead.
649
650
651 .. c:function:: wchar_t* Py_GetPrefix()
652
653 Return the *prefix* for installed platform-independent files. This is derived
654 through a number of complicated rules from the program name set with
655 :c:member:`PyConfig.program_name` and some environment variables; for example, if the
656 program name is ``'/usr/local/bin/python'``, the prefix is ``'/usr/local'``. The
657 returned string points into static storage; the caller should not modify its
658 value. This corresponds to the :makevar:`prefix` variable in the top-level
659 :file:`Makefile` and the :option:`--prefix` argument to the :program:`configure`
660 script at build time. The value is available to Python code as ``sys.base_prefix``.
661 It is only useful on Unix. See also the next function.
662
663 This function should not be called before :c:func:`Py_Initialize`, otherwise
664 it returns ``NULL``.
665
666 .. versionchanged:: 3.10
667 It now returns ``NULL`` if called before :c:func:`Py_Initialize`.
668
669 .. deprecated-removed:: 3.13 3.15
670 Use :c:func:`PyConfig_Get("base_prefix") <PyConfig_Get>`
671 (:data:`sys.base_prefix`) instead. Use :c:func:`PyConfig_Get("prefix")
672 <PyConfig_Get>` (:data:`sys.prefix`) if :ref:`virtual environments
673 <venv-def>` need to be handled.
674
675
676 .. c:function:: wchar_t* Py_GetExecPrefix()
677
678 Return the *exec-prefix* for installed platform-*dependent* files. This is
679 derived through a number of complicated rules from the program name set with
680 :c:member:`PyConfig.program_name` and some environment variables; for example, if the
681 program name is ``'/usr/local/bin/python'``, the exec-prefix is
682 ``'/usr/local'``. The returned string points into static storage; the caller
683 should not modify its value. This corresponds to the :makevar:`exec_prefix`
684 variable in the top-level :file:`Makefile` and the ``--exec-prefix``
685 argument to the :program:`configure` script at build time. The value is
686 available to Python code as ``sys.base_exec_prefix``. It is only useful on
687 Unix.
688
689 Background: The exec-prefix differs from the prefix when platform dependent
690 files (such as executables and shared libraries) are installed in a different
691 directory tree. In a typical installation, platform dependent files may be
692 installed in the :file:`/usr/local/plat` subtree while platform independent may
693 be installed in :file:`/usr/local`.
694
695 Generally speaking, a platform is a combination of hardware and software
696 families, e.g. Sparc machines running the Solaris 2.x operating system are
697 considered the same platform, but Intel machines running Solaris 2.x are another
698 platform, and Intel machines running Linux are yet another platform. Different
699 major revisions of the same operating system generally also form different
700 platforms. Non-Unix operating systems are a different story; the installation
701 strategies on those systems are so different that the prefix and exec-prefix are
702 meaningless, and set to the empty string. Note that compiled Python bytecode
703 files are platform independent (but not independent from the Python version by
704 which they were compiled!).
705
706 System administrators will know how to configure the :program:`mount` or
707 :program:`automount` programs to share :file:`/usr/local` between platforms
708 while having :file:`/usr/local/plat` be a different filesystem for each
709 platform.
710
711 This function should not be called before :c:func:`Py_Initialize`, otherwise
712 it returns ``NULL``.
713
714 .. versionchanged:: 3.10
715 It now returns ``NULL`` if called before :c:func:`Py_Initialize`.
716
717 .. deprecated-removed:: 3.13 3.15
718 Use :c:func:`PyConfig_Get("base_exec_prefix") <PyConfig_Get>`
719 (:data:`sys.base_exec_prefix`) instead. Use
720 :c:func:`PyConfig_Get("exec_prefix") <PyConfig_Get>`
721 (:data:`sys.exec_prefix`) if :ref:`virtual environments <venv-def>` need
722 to be handled.
723
724
725 .. c:function:: wchar_t* Py_GetProgramFullPath()
726
727 .. index::
728 single: executable (in module sys)
729
730 Return the full program name of the Python executable; this is computed as a
731 side-effect of deriving the default module search path from the program name
732 (set by :c:member:`PyConfig.program_name`). The returned string points into
733 static storage; the caller should not modify its value. The value is available
734 to Python code as ``sys.executable``.
735
736 This function should not be called before :c:func:`Py_Initialize`, otherwise
737 it returns ``NULL``.
738
739 .. versionchanged:: 3.10
740 It now returns ``NULL`` if called before :c:func:`Py_Initialize`.
741
742 .. deprecated-removed:: 3.13 3.15
743 Use :c:func:`PyConfig_Get("executable") <PyConfig_Get>`
744 (:data:`sys.executable`) instead.
745
746
747 .. c:function:: wchar_t* Py_GetPath()
748
749 .. index::
750 triple: module; search; path
751 single: path (in module sys)
752
753 Return the default module search path; this is computed from the program name
754 (set by :c:member:`PyConfig.program_name`) and some environment variables.
755 The returned string consists of a series of directory names separated by a
756 platform dependent delimiter character. The delimiter character is ``':'``
757 on Unix and macOS, ``';'`` on Windows. The returned string points into
758 static storage; the caller should not modify its value. The list
759 :data:`sys.path` is initialized with this value on interpreter startup; it
760 can be (and usually is) modified later to change the search path for loading
761 modules.
762
763 This function should not be called before :c:func:`Py_Initialize`, otherwise
764 it returns ``NULL``.
765
766 .. XXX should give the exact rules
767
768 .. versionchanged:: 3.10
769 It now returns ``NULL`` if called before :c:func:`Py_Initialize`.
770
771 .. deprecated-removed:: 3.13 3.15
772 Use :c:func:`PyConfig_Get("module_search_paths") <PyConfig_Get>`
773 (:data:`sys.path`) instead.
774
775 .. c:function:: const char* Py_GetVersion()
776
777 Return the version of this Python interpreter. This is a string that looks
778 something like ::
779
780 "3.0a5+ (py3k:63103M, May 12 2008, 00:53:55) \n[GCC 4.2.3]"
781
782 .. index:: single: version (in module sys)
783
784 The first word (up to the first space character) is the current Python version;
785 the first characters are the major and minor version separated by a
786 period. The returned string points into static storage; the caller should not
787 modify its value. The value is available to Python code as :data:`sys.version`.
788
789 See also the :c:var:`Py_Version` constant.
790
791
792 .. c:function:: const char* Py_GetPlatform()
793
794 .. index:: single: platform (in module sys)
795
796 Return the platform identifier for the current platform. On Unix, this is
797 formed from the "official" name of the operating system, converted to lower
798 case, followed by the major revision number; e.g., for Solaris 2.x, which is
799 also known as SunOS 5.x, the value is ``'sunos5'``. On macOS, it is
800 ``'darwin'``. On Windows, it is ``'win'``. The returned string points into
801 static storage; the caller should not modify its value. The value is available
802 to Python code as ``sys.platform``.
803
804
805 .. c:function:: const char* Py_GetCopyright()
806
807 Return the official copyright string for the current Python version, for example
808
809 ``'Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam'``
810
811 .. index:: single: copyright (in module sys)
812
813 The returned string points into static storage; the caller should not modify its
814 value. The value is available to Python code as ``sys.copyright``.
815
816
817 .. c:function:: const char* Py_GetCompiler()
818
819 Return an indication of the compiler used to build the current Python version,
820 in square brackets, for example::
821
822 "[GCC 2.7.2.2]"
823
824 .. index:: single: version (in module sys)
825
826 The returned string points into static storage; the caller should not modify its
827 value. The value is available to Python code as part of the variable
828 ``sys.version``.
829
830
831 .. c:function:: const char* Py_GetBuildInfo()
832
833 Return information about the sequence number and build date and time of the
834 current Python interpreter instance, for example ::
835
836 "#67, Aug 1 1997, 22:34:28"
837
838 .. index:: single: version (in module sys)
839
840 The returned string points into static storage; the caller should not modify its
841 value. The value is available to Python code as part of the variable
842 ``sys.version``.
843
844
845 .. c:function:: void PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
846
847 .. index::
848 single: main()
849 single: Py_FatalError()
850 single: argv (in module sys)
851
852 This API is kept for backward compatibility: setting
853 :c:member:`PyConfig.argv`, :c:member:`PyConfig.parse_argv` and
854 :c:member:`PyConfig.safe_path` should be used instead, see :ref:`Python
855 Initialization Configuration <init-config>`.
856
857 Set :data:`sys.argv` based on *argc* and *argv*. These parameters are
858 similar to those passed to the program's :c:func:`main` function with the
859 difference that the first entry should refer to the script file to be
860 executed rather than the executable hosting the Python interpreter. If there
861 isn't a script that will be run, the first entry in *argv* can be an empty
862 string. If this function fails to initialize :data:`sys.argv`, a fatal
863 condition is signalled using :c:func:`Py_FatalError`.
864
865 If *updatepath* is zero, this is all the function does. If *updatepath*
866 is non-zero, the function also modifies :data:`sys.path` according to the
867 following algorithm:
868
869 - If the name of an existing script is passed in ``argv[0]``, the absolute
870 path of the directory where the script is located is prepended to
871 :data:`sys.path`.
872 - Otherwise (that is, if *argc* is ``0`` or ``argv[0]`` doesn't point
873 to an existing file name), an empty string is prepended to
874 :data:`sys.path`, which is the same as prepending the current working
875 directory (``"."``).
876
877 Use :c:func:`Py_DecodeLocale` to decode a bytes string to get a
878 :c:expr:`wchar_t*` string.
879
880 See also :c:member:`PyConfig.orig_argv` and :c:member:`PyConfig.argv`
881 members of the :ref:`Python Initialization Configuration <init-config>`.
882
883 .. note::
884 It is recommended that applications embedding the Python interpreter
885 for purposes other than executing a single script pass ``0`` as *updatepath*,
886 and update :data:`sys.path` themselves if desired.
887 See :cve:`2008-5983`.
888
889 On versions before 3.1.3, you can achieve the same effect by manually
890 popping the first :data:`sys.path` element after having called
891 :c:func:`PySys_SetArgv`, for example using::
892
893 PyRun_SimpleString("import sys; sys.path.pop(0)\n");
894
895 .. versionadded:: 3.1.3
896
897 .. deprecated-removed:: 3.11 3.15
898
899
900 .. c:function:: void PySys_SetArgv(int argc, wchar_t **argv)
901
902 This API is kept for backward compatibility: setting
903 :c:member:`PyConfig.argv` and :c:member:`PyConfig.parse_argv` should be used
904 instead, see :ref:`Python Initialization Configuration <init-config>`.
905
906 This function works like :c:func:`PySys_SetArgvEx` with *updatepath* set
907 to ``1`` unless the :program:`python` interpreter was started with the
908 :option:`-I`.
909
910 Use :c:func:`Py_DecodeLocale` to decode a bytes string to get a
911 :c:expr:`wchar_t*` string.
912
913 See also :c:member:`PyConfig.orig_argv` and :c:member:`PyConfig.argv`
914 members of the :ref:`Python Initialization Configuration <init-config>`.
915
916 .. versionchanged:: 3.4 The *updatepath* value depends on :option:`-I`.
917
918 .. deprecated-removed:: 3.11 3.15
919
920
921 .. c:function:: void Py_SetPythonHome(const wchar_t *home)
922
923 This API is kept for backward compatibility: setting
924 :c:member:`PyConfig.home` should be used instead, see :ref:`Python
925 Initialization Configuration <init-config>`.
926
927 Set the default "home" directory, that is, the location of the standard
928 Python libraries. See :envvar:`PYTHONHOME` for the meaning of the
929 argument string.
930
931 The argument should point to a zero-terminated character string in static
932 storage whose contents will not change for the duration of the program's
933 execution. No code in the Python interpreter will change the contents of
934 this storage.
935
936 Use :c:func:`Py_DecodeLocale` to decode a bytes string to get a
937 :c:expr:`wchar_t*` string.
938
939 .. deprecated-removed:: 3.11 3.15
940
941
942 .. c:function:: wchar_t* Py_GetPythonHome()
943
944 Return the default "home", that is, the value set by
945 :c:member:`PyConfig.home`, or the value of the :envvar:`PYTHONHOME`
946 environment variable if it is set.
947
948 This function should not be called before :c:func:`Py_Initialize`, otherwise
949 it returns ``NULL``.
950
951 .. versionchanged:: 3.10
952 It now returns ``NULL`` if called before :c:func:`Py_Initialize`.
953
954 .. deprecated-removed:: 3.13 3.15
955 Use :c:func:`PyConfig_Get("home") <PyConfig_Get>` or the
956 :envvar:`PYTHONHOME` environment variable instead.