blob: 6b5290a7ebbb004e23ee17963a13409112e413cc [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001.. highlightlang:: c
2
3
4.. _initialization:
5
6*****************************************
7Initialization, Finalization, and Threads
8*****************************************
9
Victor Stinner84c4b192017-11-24 22:30:27 +010010.. _pre-init-safe:
11
12Before Python Initialization
13============================
14
15In an application embedding Python, the :c:func:`Py_Initialize` function must
16be called before using any other Python/C API functions; with the exception of
17a few functions and the :ref:`global configuration variables
18<global-conf-vars>`.
19
20The following functions can be safely called before Python is initialized:
21
22* Configuration functions:
23
24 * :c:func:`PyImport_AppendInittab`
25 * :c:func:`PyImport_ExtendInittab`
26 * :c:func:`PyInitFrozenExtensions`
27 * :c:func:`PyMem_SetAllocator`
28 * :c:func:`PyMem_SetupDebugHooks`
29 * :c:func:`PyObject_SetArenaAllocator`
30 * :c:func:`Py_SetPath`
31 * :c:func:`Py_SetProgramName`
32 * :c:func:`Py_SetPythonHome`
33 * :c:func:`Py_SetStandardStreamEncoding`
Nick Coghlanbc77eff2018-03-25 20:44:30 +100034 * :c:func:`PySys_AddWarnOption`
35 * :c:func:`PySys_AddXOption`
36 * :c:func:`PySys_ResetWarnOptions`
Victor Stinner84c4b192017-11-24 22:30:27 +010037
38* Informative functions:
39
40 * :c:func:`PyMem_GetAllocator`
41 * :c:func:`PyObject_GetArenaAllocator`
42 * :c:func:`Py_GetBuildInfo`
43 * :c:func:`Py_GetCompiler`
44 * :c:func:`Py_GetCopyright`
45 * :c:func:`Py_GetPlatform`
Victor Stinner84c4b192017-11-24 22:30:27 +010046 * :c:func:`Py_GetVersion`
47
48* Utilities:
49
50 * :c:func:`Py_DecodeLocale`
51
52* Memory allocators:
53
54 * :c:func:`PyMem_RawMalloc`
55 * :c:func:`PyMem_RawRealloc`
56 * :c:func:`PyMem_RawCalloc`
57 * :c:func:`PyMem_RawFree`
58
59.. note::
60
61 The following functions **should not be called** before
62 :c:func:`Py_Initialize`: :c:func:`Py_EncodeLocale`, :c:func:`Py_GetPath`,
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +010063 :c:func:`Py_GetPrefix`, :c:func:`Py_GetExecPrefix`,
Victor Stinner31a83932017-12-04 13:39:15 +010064 :c:func:`Py_GetProgramFullPath`, :c:func:`Py_GetPythonHome`,
65 :c:func:`Py_GetProgramName` and :c:func:`PyEval_InitThreads`.
Victor Stinner84c4b192017-11-24 22:30:27 +010066
67
68.. _global-conf-vars:
69
70Global configuration variables
71==============================
72
73Python has variables for the global configuration to control different features
74and options. By default, these flags are controlled by :ref:`command line
75options <using-on-interface-options>`.
76
77When a flag is set by an option, the value of the flag is the number of times
78that the option was set. For example, ``-b`` sets :c:data:`Py_BytesWarningFlag`
79to 1 and ``-bb`` sets :c:data:`Py_BytesWarningFlag` to 2.
80
81.. c:var:: Py_BytesWarningFlag
82
83 Issue a warning when comparing :class:`bytes` or :class:`bytearray` with
84 :class:`str` or :class:`bytes` with :class:`int`. Issue an error if greater
85 or equal to ``2``.
86
87 Set by the :option:`-b` option.
88
89.. c:var:: Py_DebugFlag
90
91 Turn on parser debugging output (for expert only, depending on compilation
92 options).
93
94 Set by the :option:`-d` option and the :envvar:`PYTHONDEBUG` environment
95 variable.
96
97.. c:var:: Py_DontWriteBytecodeFlag
98
99 If set to non-zero, Python won't try to write ``.pyc`` files on the
100 import of source modules.
101
102 Set by the :option:`-B` option and the :envvar:`PYTHONDONTWRITEBYTECODE`
103 environment variable.
104
105.. c:var:: Py_FrozenFlag
106
107 Suppress error messages when calculating the module search path in
108 :c:func:`Py_GetPath`.
109
110 Private flag used by ``_freeze_importlib`` and ``frozenmain`` programs.
111
112.. c:var:: Py_HashRandomizationFlag
113
114 Set to ``1`` if the :envvar:`PYTHONHASHSEED` environment variable is set to
115 a non-empty string.
116
117 If the flag is non-zero, read the :envvar:`PYTHONHASHSEED` environment
118 variable to initialize the secret hash seed.
119
120.. c:var:: Py_IgnoreEnvironmentFlag
121
122 Ignore all :envvar:`PYTHON*` environment variables, e.g.
123 :envvar:`PYTHONPATH` and :envvar:`PYTHONHOME`, that might be set.
124
125 Set by the :option:`-E` and :option:`-I` options.
126
127.. c:var:: Py_InspectFlag
128
129 When a script is passed as first argument or the :option:`-c` option is used,
130 enter interactive mode after executing the script or the command, even when
131 :data:`sys.stdin` does not appear to be a terminal.
132
133 Set by the :option:`-i` option and the :envvar:`PYTHONINSPECT` environment
134 variable.
135
136.. c:var:: Py_InteractiveFlag
137
138 Set by the :option:`-i` option.
139
140.. c:var:: Py_IsolatedFlag
141
142 Run Python in isolated mode. In isolated mode :data:`sys.path` contains
143 neither the script's directory nor the user's site-packages directory.
144
145 Set by the :option:`-I` option.
146
147 .. versionadded:: 3.4
148
149.. c:var:: Py_LegacyWindowsFSEncodingFlag
150
151 If the flag is non-zero, use the ``mbcs`` encoding instead of the UTF-8
152 encoding for the filesystem encoding.
153
154 Set to ``1`` if the :envvar:`PYTHONLEGACYWINDOWSFSENCODING` environment
155 variable is set to a non-empty string.
156
157 See :pep:`529` for more details.
158
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400159 .. availability:: Windows.
Victor Stinner84c4b192017-11-24 22:30:27 +0100160
161.. c:var:: Py_LegacyWindowsStdioFlag
162
163 If the flag is non-zero, use :class:`io.FileIO` instead of
164 :class:`WindowsConsoleIO` for :mod:`sys` standard streams.
165
166 Set to ``1`` if the :envvar:`PYTHONLEGACYWINDOWSSTDIO` environment
167 variable is set to a non-empty string.
168
169 See :pep:`528` for more details.
170
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400171 .. availability:: Windows.
Victor Stinner84c4b192017-11-24 22:30:27 +0100172
173.. c:var:: Py_NoSiteFlag
174
175 Disable the import of the module :mod:`site` and the site-dependent
176 manipulations of :data:`sys.path` that it entails. Also disable these
177 manipulations if :mod:`site` is explicitly imported later (call
178 :func:`site.main` if you want them to be triggered).
179
180 Set by the :option:`-S` option.
181
182.. c:var:: Py_NoUserSiteDirectory
183
184 Don't add the :data:`user site-packages directory <site.USER_SITE>` to
185 :data:`sys.path`.
186
187 Set by the :option:`-s` and :option:`-I` options, and the
188 :envvar:`PYTHONNOUSERSITE` environment variable.
189
190.. c:var:: Py_OptimizeFlag
191
192 Set by the :option:`-O` option and the :envvar:`PYTHONOPTIMIZE` environment
193 variable.
194
195.. c:var:: Py_QuietFlag
196
197 Don't display the copyright and version messages even in interactive mode.
198
199 Set by the :option:`-q` option.
200
201 .. versionadded:: 3.2
202
203.. c:var:: Py_UnbufferedStdioFlag
204
205 Force the stdout and stderr streams to be unbuffered.
206
207 Set by the :option:`-u` option and the :envvar:`PYTHONUNBUFFERED`
208 environment variable.
209
210.. c:var:: Py_VerboseFlag
211
212 Print a message each time a module is initialized, showing the place
213 (filename or built-in module) from which it is loaded. If greater or equal
214 to ``2``, print a message for each file that is checked for when
215 searching for a module. Also provides information on module cleanup at exit.
216
217 Set by the :option:`-v` option and the :envvar:`PYTHONVERBOSE` environment
218 variable.
219
Georg Brandl116aa622007-08-15 14:28:22 +0000220
Antoine Pitrou8b50b832011-01-15 11:57:42 +0000221Initializing and finalizing the interpreter
222===========================================
223
224
Georg Brandl60203b42010-10-06 10:11:56 +0000225.. c:function:: void Py_Initialize()
Georg Brandl116aa622007-08-15 14:28:22 +0000226
227 .. index::
228 single: Py_SetProgramName()
229 single: PyEval_InitThreads()
Georg Brandl116aa622007-08-15 14:28:22 +0000230 single: modules (in module sys)
231 single: path (in module sys)
Georg Brandl1a3284e2007-12-02 09:40:06 +0000232 module: builtins
Georg Brandl116aa622007-08-15 14:28:22 +0000233 module: __main__
234 module: sys
235 triple: module; search; path
236 single: PySys_SetArgv()
Antoine Pitrouf978fac2010-05-21 17:25:34 +0000237 single: PySys_SetArgvEx()
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000238 single: Py_FinalizeEx()
Georg Brandl116aa622007-08-15 14:28:22 +0000239
Victor Stinner84c4b192017-11-24 22:30:27 +0100240 Initialize the Python interpreter. In an application embedding Python,
241 this should be called before using any other Python/C API functions; see
242 :ref:`Before Python Initialization <pre-init-safe>` for the few exceptions.
243
244 This initializes
Georg Brandl116aa622007-08-15 14:28:22 +0000245 the table of loaded modules (``sys.modules``), and creates the fundamental
Georg Brandl1a3284e2007-12-02 09:40:06 +0000246 modules :mod:`builtins`, :mod:`__main__` and :mod:`sys`. It also initializes
Georg Brandl116aa622007-08-15 14:28:22 +0000247 the module search path (``sys.path``). It does not set ``sys.argv``; use
Georg Brandl60203b42010-10-06 10:11:56 +0000248 :c:func:`PySys_SetArgvEx` for that. This is a no-op when called for a second time
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000249 (without calling :c:func:`Py_FinalizeEx` first). There is no return value; it is a
Georg Brandl116aa622007-08-15 14:28:22 +0000250 fatal error if the initialization fails.
251
Steve Dowerde02b082016-09-09 11:46:37 -0700252 .. note::
253 On Windows, changes the console mode from ``O_TEXT`` to ``O_BINARY``, which will
254 also affect non-Python uses of the console using the C Runtime.
255
Georg Brandl116aa622007-08-15 14:28:22 +0000256
Georg Brandl60203b42010-10-06 10:11:56 +0000257.. c:function:: void Py_InitializeEx(int initsigs)
Georg Brandl116aa622007-08-15 14:28:22 +0000258
Serhiy Storchaka1ecf7d22016-10-27 21:41:19 +0300259 This function works like :c:func:`Py_Initialize` if *initsigs* is ``1``. If
260 *initsigs* is ``0``, it skips initialization registration of signal handlers, which
Georg Brandl116aa622007-08-15 14:28:22 +0000261 might be useful when Python is embedded.
262
Georg Brandl116aa622007-08-15 14:28:22 +0000263
Georg Brandl60203b42010-10-06 10:11:56 +0000264.. c:function:: int Py_IsInitialized()
Georg Brandl116aa622007-08-15 14:28:22 +0000265
266 Return true (nonzero) when the Python interpreter has been initialized, false
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000267 (zero) if not. After :c:func:`Py_FinalizeEx` is called, this returns false until
Georg Brandl60203b42010-10-06 10:11:56 +0000268 :c:func:`Py_Initialize` is called again.
Georg Brandl116aa622007-08-15 14:28:22 +0000269
270
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000271.. c:function:: int Py_FinalizeEx()
Georg Brandl116aa622007-08-15 14:28:22 +0000272
Georg Brandl60203b42010-10-06 10:11:56 +0000273 Undo all initializations made by :c:func:`Py_Initialize` and subsequent use of
Georg Brandl116aa622007-08-15 14:28:22 +0000274 Python/C API functions, and destroy all sub-interpreters (see
Georg Brandl60203b42010-10-06 10:11:56 +0000275 :c:func:`Py_NewInterpreter` below) that were created and not yet destroyed since
276 the last call to :c:func:`Py_Initialize`. Ideally, this frees all memory
Georg Brandl116aa622007-08-15 14:28:22 +0000277 allocated by the Python interpreter. This is a no-op when called for a second
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000278 time (without calling :c:func:`Py_Initialize` again first). Normally the
Serhiy Storchaka5bb00052018-02-09 13:31:19 +0200279 return value is ``0``. If there were errors during finalization
280 (flushing buffered data), ``-1`` is returned.
Georg Brandl116aa622007-08-15 14:28:22 +0000281
282 This function is provided for a number of reasons. An embedding application
283 might want to restart Python without having to restart the application itself.
284 An application that has loaded the Python interpreter from a dynamically
285 loadable library (or DLL) might want to free all memory allocated by Python
286 before unloading the DLL. During a hunt for memory leaks in an application a
287 developer might want to free all memory allocated by Python before exiting from
288 the application.
289
290 **Bugs and caveats:** The destruction of modules and objects in modules is done
291 in random order; this may cause destructors (:meth:`__del__` methods) to fail
292 when they depend on other objects (even functions) or modules. Dynamically
293 loaded extension modules loaded by Python are not unloaded. Small amounts of
294 memory allocated by the Python interpreter may not be freed (if you find a leak,
295 please report it). Memory tied up in circular references between objects is not
296 freed. Some memory allocated by extension modules may not be freed. Some
297 extensions may not work properly if their initialization routine is called more
Georg Brandl60203b42010-10-06 10:11:56 +0000298 than once; this can happen if an application calls :c:func:`Py_Initialize` and
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000299 :c:func:`Py_FinalizeEx` more than once.
300
301 .. versionadded:: 3.6
302
303
304.. c:function:: void Py_Finalize()
305
306 This is a backwards-compatible version of :c:func:`Py_FinalizeEx` that
307 disregards the return value.
Georg Brandl116aa622007-08-15 14:28:22 +0000308
309
Antoine Pitrou8b50b832011-01-15 11:57:42 +0000310Process-wide parameters
311=======================
Georg Brandl116aa622007-08-15 14:28:22 +0000312
313
Serhiy Storchaka03863d22015-06-21 17:11:21 +0300314.. c:function:: int Py_SetStandardStreamEncoding(const char *encoding, const char *errors)
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000315
316 .. index::
317 single: Py_Initialize()
318 single: main()
319 triple: stdin; stdout; sdterr
320
Nick Coghlan1805a622013-10-18 23:11:47 +1000321 This function should be called before :c:func:`Py_Initialize`, if it is
322 called at all. It specifies which encoding and error handling to use
323 with standard IO, with the same meanings as in :func:`str.encode`.
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000324
325 It overrides :envvar:`PYTHONIOENCODING` values, and allows embedding code
Nick Coghlan1805a622013-10-18 23:11:47 +1000326 to control IO encoding when the environment variable does not work.
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000327
328 ``encoding`` and/or ``errors`` may be NULL to use
329 :envvar:`PYTHONIOENCODING` and/or default values (depending on other
330 settings).
331
332 Note that :data:`sys.stderr` always uses the "backslashreplace" error
333 handler, regardless of this (or any other) setting.
334
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000335 If :c:func:`Py_FinalizeEx` is called, this function will need to be called
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000336 again in order to affect subsequent calls to :c:func:`Py_Initialize`.
337
Serhiy Storchaka1ecf7d22016-10-27 21:41:19 +0300338 Returns ``0`` if successful, a nonzero value on error (e.g. calling after the
Nick Coghlan1805a622013-10-18 23:11:47 +1000339 interpreter has already been initialized).
340
341 .. versionadded:: 3.4
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000342
343
Serhiy Storchaka4ae06c52017-12-12 13:55:04 +0200344.. c:function:: void Py_SetProgramName(const wchar_t *name)
Georg Brandl116aa622007-08-15 14:28:22 +0000345
346 .. index::
347 single: Py_Initialize()
348 single: main()
349 single: Py_GetPath()
350
Georg Brandl60203b42010-10-06 10:11:56 +0000351 This function should be called before :c:func:`Py_Initialize` is called for
Georg Brandl116aa622007-08-15 14:28:22 +0000352 the first time, if it is called at all. It tells the interpreter the value
Georg Brandl60203b42010-10-06 10:11:56 +0000353 of the ``argv[0]`` argument to the :c:func:`main` function of the program
Martin v. Löwis790465f2008-04-05 20:41:37 +0000354 (converted to wide characters).
Georg Brandl60203b42010-10-06 10:11:56 +0000355 This is used by :c:func:`Py_GetPath` and some other functions below to find
Georg Brandl116aa622007-08-15 14:28:22 +0000356 the Python run-time libraries relative to the interpreter executable. The
357 default value is ``'python'``. The argument should point to a
Martin v. Löwis790465f2008-04-05 20:41:37 +0000358 zero-terminated wide character string in static storage whose contents will not
Georg Brandl116aa622007-08-15 14:28:22 +0000359 change for the duration of the program's execution. No code in the Python
360 interpreter will change the contents of this storage.
361
Victor Stinner25e014b2014-08-01 12:28:49 +0200362 Use :c:func:`Py_DecodeLocale` to decode a bytes string to get a
363 :c:type:`wchar_*` string.
364
Georg Brandl116aa622007-08-15 14:28:22 +0000365
Georg Brandl60203b42010-10-06 10:11:56 +0000366.. c:function:: wchar* Py_GetProgramName()
Georg Brandl116aa622007-08-15 14:28:22 +0000367
368 .. index:: single: Py_SetProgramName()
369
Georg Brandl60203b42010-10-06 10:11:56 +0000370 Return the program name set with :c:func:`Py_SetProgramName`, or the default.
Georg Brandl116aa622007-08-15 14:28:22 +0000371 The returned string points into static storage; the caller should not modify its
372 value.
373
374
Georg Brandl60203b42010-10-06 10:11:56 +0000375.. c:function:: wchar_t* Py_GetPrefix()
Georg Brandl116aa622007-08-15 14:28:22 +0000376
377 Return the *prefix* for installed platform-independent files. This is derived
378 through a number of complicated rules from the program name set with
Georg Brandl60203b42010-10-06 10:11:56 +0000379 :c:func:`Py_SetProgramName` and some environment variables; for example, if the
Georg Brandl116aa622007-08-15 14:28:22 +0000380 program name is ``'/usr/local/bin/python'``, the prefix is ``'/usr/local'``. The
381 returned string points into static storage; the caller should not modify its
382 value. This corresponds to the :makevar:`prefix` variable in the top-level
Éric Araujo37b5f9e2011-09-01 03:19:30 +0200383 :file:`Makefile` and the ``--prefix`` argument to the :program:`configure`
Georg Brandl116aa622007-08-15 14:28:22 +0000384 script at build time. The value is available to Python code as ``sys.prefix``.
385 It is only useful on Unix. See also the next function.
386
387
Georg Brandl60203b42010-10-06 10:11:56 +0000388.. c:function:: wchar_t* Py_GetExecPrefix()
Georg Brandl116aa622007-08-15 14:28:22 +0000389
390 Return the *exec-prefix* for installed platform-*dependent* files. This is
391 derived through a number of complicated rules from the program name set with
Georg Brandl60203b42010-10-06 10:11:56 +0000392 :c:func:`Py_SetProgramName` and some environment variables; for example, if the
Georg Brandl116aa622007-08-15 14:28:22 +0000393 program name is ``'/usr/local/bin/python'``, the exec-prefix is
394 ``'/usr/local'``. The returned string points into static storage; the caller
395 should not modify its value. This corresponds to the :makevar:`exec_prefix`
Éric Araujo37b5f9e2011-09-01 03:19:30 +0200396 variable in the top-level :file:`Makefile` and the ``--exec-prefix``
Georg Brandl116aa622007-08-15 14:28:22 +0000397 argument to the :program:`configure` script at build time. The value is
398 available to Python code as ``sys.exec_prefix``. It is only useful on Unix.
399
400 Background: The exec-prefix differs from the prefix when platform dependent
401 files (such as executables and shared libraries) are installed in a different
402 directory tree. In a typical installation, platform dependent files may be
403 installed in the :file:`/usr/local/plat` subtree while platform independent may
404 be installed in :file:`/usr/local`.
405
406 Generally speaking, a platform is a combination of hardware and software
407 families, e.g. Sparc machines running the Solaris 2.x operating system are
408 considered the same platform, but Intel machines running Solaris 2.x are another
409 platform, and Intel machines running Linux are yet another platform. Different
410 major revisions of the same operating system generally also form different
411 platforms. Non-Unix operating systems are a different story; the installation
412 strategies on those systems are so different that the prefix and exec-prefix are
413 meaningless, and set to the empty string. Note that compiled Python bytecode
414 files are platform independent (but not independent from the Python version by
415 which they were compiled!).
416
417 System administrators will know how to configure the :program:`mount` or
418 :program:`automount` programs to share :file:`/usr/local` between platforms
419 while having :file:`/usr/local/plat` be a different filesystem for each
420 platform.
421
422
Georg Brandl60203b42010-10-06 10:11:56 +0000423.. c:function:: wchar_t* Py_GetProgramFullPath()
Georg Brandl116aa622007-08-15 14:28:22 +0000424
425 .. index::
426 single: Py_SetProgramName()
427 single: executable (in module sys)
428
429 Return the full program name of the Python executable; this is computed as a
430 side-effect of deriving the default module search path from the program name
Georg Brandl60203b42010-10-06 10:11:56 +0000431 (set by :c:func:`Py_SetProgramName` above). The returned string points into
Georg Brandl116aa622007-08-15 14:28:22 +0000432 static storage; the caller should not modify its value. The value is available
433 to Python code as ``sys.executable``.
434
435
Georg Brandl60203b42010-10-06 10:11:56 +0000436.. c:function:: wchar_t* Py_GetPath()
Georg Brandl116aa622007-08-15 14:28:22 +0000437
438 .. index::
439 triple: module; search; path
440 single: path (in module sys)
Kristján Valur Jónsson3b69db22010-09-27 05:32:54 +0000441 single: Py_SetPath()
Georg Brandl116aa622007-08-15 14:28:22 +0000442
Benjamin Peterson46a99002010-01-09 18:45:30 +0000443 Return the default module search path; this is computed from the program name
Georg Brandl60203b42010-10-06 10:11:56 +0000444 (set by :c:func:`Py_SetProgramName` above) and some environment variables.
Benjamin Peterson46a99002010-01-09 18:45:30 +0000445 The returned string consists of a series of directory names separated by a
446 platform dependent delimiter character. The delimiter character is ``':'``
447 on Unix and Mac OS X, ``';'`` on Windows. The returned string points into
448 static storage; the caller should not modify its value. The list
449 :data:`sys.path` is initialized with this value on interpreter startup; it
450 can be (and usually is) modified later to change the search path for loading
451 modules.
Georg Brandl116aa622007-08-15 14:28:22 +0000452
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000453 .. XXX should give the exact rules
Georg Brandl116aa622007-08-15 14:28:22 +0000454
455
Georg Brandl60203b42010-10-06 10:11:56 +0000456.. c:function:: void Py_SetPath(const wchar_t *)
Kristján Valur Jónsson3b69db22010-09-27 05:32:54 +0000457
458 .. index::
459 triple: module; search; path
460 single: path (in module sys)
461 single: Py_GetPath()
462
463 Set the default module search path. If this function is called before
Georg Brandlfa4f7f92010-10-06 10:14:08 +0000464 :c:func:`Py_Initialize`, then :c:func:`Py_GetPath` won't attempt to compute a
465 default search path but uses the one provided instead. This is useful if
466 Python is embedded by an application that has full knowledge of the location
Georg Brandle8ea3552014-10-11 14:36:02 +0200467 of all modules. The path components should be separated by the platform
468 dependent delimiter character, which is ``':'`` on Unix and Mac OS X, ``';'``
469 on Windows.
Kristján Valur Jónsson3b69db22010-09-27 05:32:54 +0000470
Georg Brandlfa4f7f92010-10-06 10:14:08 +0000471 This also causes :data:`sys.executable` to be set only to the raw program
472 name (see :c:func:`Py_SetProgramName`) and for :data:`sys.prefix` and
473 :data:`sys.exec_prefix` to be empty. It is up to the caller to modify these
474 if required after calling :c:func:`Py_Initialize`.
475
Victor Stinner25e014b2014-08-01 12:28:49 +0200476 Use :c:func:`Py_DecodeLocale` to decode a bytes string to get a
477 :c:type:`wchar_*` string.
478
Benjamin Petersonb33bb892014-12-24 10:49:11 -0600479 The path argument is copied internally, so the caller may free it after the
480 call completes.
481
Kristján Valur Jónsson3b69db22010-09-27 05:32:54 +0000482
Georg Brandl60203b42010-10-06 10:11:56 +0000483.. c:function:: const char* Py_GetVersion()
Georg Brandl116aa622007-08-15 14:28:22 +0000484
485 Return the version of this Python interpreter. This is a string that looks
486 something like ::
487
Georg Brandle6bcc912008-05-12 18:05:20 +0000488 "3.0a5+ (py3k:63103M, May 12 2008, 00:53:55) \n[GCC 4.2.3]"
Georg Brandl116aa622007-08-15 14:28:22 +0000489
490 .. index:: single: version (in module sys)
491
492 The first word (up to the first space character) is the current Python version;
493 the first three characters are the major and minor version separated by a
494 period. The returned string points into static storage; the caller should not
Georg Brandle6bcc912008-05-12 18:05:20 +0000495 modify its value. The value is available to Python code as :data:`sys.version`.
Georg Brandl116aa622007-08-15 14:28:22 +0000496
497
Georg Brandl60203b42010-10-06 10:11:56 +0000498.. c:function:: const char* Py_GetPlatform()
Georg Brandl116aa622007-08-15 14:28:22 +0000499
500 .. index:: single: platform (in module sys)
501
502 Return the platform identifier for the current platform. On Unix, this is
503 formed from the "official" name of the operating system, converted to lower
504 case, followed by the major revision number; e.g., for Solaris 2.x, which is
505 also known as SunOS 5.x, the value is ``'sunos5'``. On Mac OS X, it is
506 ``'darwin'``. On Windows, it is ``'win'``. The returned string points into
507 static storage; the caller should not modify its value. The value is available
508 to Python code as ``sys.platform``.
509
510
Georg Brandl60203b42010-10-06 10:11:56 +0000511.. c:function:: const char* Py_GetCopyright()
Georg Brandl116aa622007-08-15 14:28:22 +0000512
513 Return the official copyright string for the current Python version, for example
514
515 ``'Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam'``
516
517 .. index:: single: copyright (in module sys)
518
519 The returned string points into static storage; the caller should not modify its
520 value. The value is available to Python code as ``sys.copyright``.
521
522
Georg Brandl60203b42010-10-06 10:11:56 +0000523.. c:function:: const char* Py_GetCompiler()
Georg Brandl116aa622007-08-15 14:28:22 +0000524
525 Return an indication of the compiler used to build the current Python version,
526 in square brackets, for example::
527
528 "[GCC 2.7.2.2]"
529
530 .. index:: single: version (in module sys)
531
532 The returned string points into static storage; the caller should not modify its
533 value. The value is available to Python code as part of the variable
534 ``sys.version``.
535
536
Georg Brandl60203b42010-10-06 10:11:56 +0000537.. c:function:: const char* Py_GetBuildInfo()
Georg Brandl116aa622007-08-15 14:28:22 +0000538
539 Return information about the sequence number and build date and time of the
540 current Python interpreter instance, for example ::
541
542 "#67, Aug 1 1997, 22:34:28"
543
544 .. index:: single: version (in module sys)
545
546 The returned string points into static storage; the caller should not modify its
547 value. The value is available to Python code as part of the variable
548 ``sys.version``.
549
550
Georg Brandl60203b42010-10-06 10:11:56 +0000551.. c:function:: void PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
Georg Brandl116aa622007-08-15 14:28:22 +0000552
553 .. index::
554 single: main()
555 single: Py_FatalError()
556 single: argv (in module sys)
557
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000558 Set :data:`sys.argv` based on *argc* and *argv*. These parameters are
Georg Brandl60203b42010-10-06 10:11:56 +0000559 similar to those passed to the program's :c:func:`main` function with the
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000560 difference that the first entry should refer to the script file to be
561 executed rather than the executable hosting the Python interpreter. If there
562 isn't a script that will be run, the first entry in *argv* can be an empty
563 string. If this function fails to initialize :data:`sys.argv`, a fatal
Georg Brandl60203b42010-10-06 10:11:56 +0000564 condition is signalled using :c:func:`Py_FatalError`.
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000565
Antoine Pitrouf978fac2010-05-21 17:25:34 +0000566 If *updatepath* is zero, this is all the function does. If *updatepath*
567 is non-zero, the function also modifies :data:`sys.path` according to the
568 following algorithm:
569
570 - If the name of an existing script is passed in ``argv[0]``, the absolute
571 path of the directory where the script is located is prepended to
572 :data:`sys.path`.
Serhiy Storchaka1ecf7d22016-10-27 21:41:19 +0300573 - Otherwise (that is, if *argc* is ``0`` or ``argv[0]`` doesn't point
Antoine Pitrouf978fac2010-05-21 17:25:34 +0000574 to an existing file name), an empty string is prepended to
575 :data:`sys.path`, which is the same as prepending the current working
576 directory (``"."``).
577
Victor Stinner25e014b2014-08-01 12:28:49 +0200578 Use :c:func:`Py_DecodeLocale` to decode a bytes string to get a
579 :c:type:`wchar_*` string.
580
Antoine Pitrouf978fac2010-05-21 17:25:34 +0000581 .. note::
582 It is recommended that applications embedding the Python interpreter
Serhiy Storchaka1ecf7d22016-10-27 21:41:19 +0300583 for purposes other than executing a single script pass ``0`` as *updatepath*,
Antoine Pitrouf978fac2010-05-21 17:25:34 +0000584 and update :data:`sys.path` themselves if desired.
Serhiy Storchaka6dff0202016-05-07 10:49:07 +0300585 See `CVE-2008-5983 <https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-5983>`_.
Antoine Pitrouf978fac2010-05-21 17:25:34 +0000586
587 On versions before 3.1.3, you can achieve the same effect by manually
588 popping the first :data:`sys.path` element after having called
Georg Brandl60203b42010-10-06 10:11:56 +0000589 :c:func:`PySys_SetArgv`, for example using::
Antoine Pitrouf978fac2010-05-21 17:25:34 +0000590
591 PyRun_SimpleString("import sys; sys.path.pop(0)\n");
592
593 .. versionadded:: 3.1.3
Georg Brandl116aa622007-08-15 14:28:22 +0000594
Serhiy Storchaka1ecf7d22016-10-27 21:41:19 +0300595 .. XXX impl. doesn't seem consistent in allowing ``0``/``NULL`` for the params;
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000596 check w/ Guido.
Georg Brandl116aa622007-08-15 14:28:22 +0000597
Georg Brandl116aa622007-08-15 14:28:22 +0000598
Georg Brandl60203b42010-10-06 10:11:56 +0000599.. c:function:: void PySys_SetArgv(int argc, wchar_t **argv)
Antoine Pitrouf978fac2010-05-21 17:25:34 +0000600
Christian Heimesad73a9c2013-08-10 16:36:18 +0200601 This function works like :c:func:`PySys_SetArgvEx` with *updatepath* set
Serhiy Storchaka1ecf7d22016-10-27 21:41:19 +0300602 to ``1`` unless the :program:`python` interpreter was started with the
Christian Heimesad73a9c2013-08-10 16:36:18 +0200603 :option:`-I`.
604
Victor Stinner25e014b2014-08-01 12:28:49 +0200605 Use :c:func:`Py_DecodeLocale` to decode a bytes string to get a
606 :c:type:`wchar_*` string.
607
Christian Heimesad73a9c2013-08-10 16:36:18 +0200608 .. versionchanged:: 3.4 The *updatepath* value depends on :option:`-I`.
Antoine Pitrouf978fac2010-05-21 17:25:34 +0000609
610
Serhiy Storchaka4ae06c52017-12-12 13:55:04 +0200611.. c:function:: void Py_SetPythonHome(const wchar_t *home)
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000612
613 Set the default "home" directory, that is, the location of the standard
Georg Brandlde0ab5e2010-12-02 18:02:01 +0000614 Python libraries. See :envvar:`PYTHONHOME` for the meaning of the
615 argument string.
616
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000617 The argument should point to a zero-terminated character string in static
618 storage whose contents will not change for the duration of the program's
619 execution. No code in the Python interpreter will change the contents of
620 this storage.
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000621
Victor Stinner25e014b2014-08-01 12:28:49 +0200622 Use :c:func:`Py_DecodeLocale` to decode a bytes string to get a
623 :c:type:`wchar_*` string.
624
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000625
Georg Brandl60203b42010-10-06 10:11:56 +0000626.. c:function:: w_char* Py_GetPythonHome()
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000627
628 Return the default "home", that is, the value set by a previous call to
Georg Brandl60203b42010-10-06 10:11:56 +0000629 :c:func:`Py_SetPythonHome`, or the value of the :envvar:`PYTHONHOME`
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000630 environment variable if it is set.
631
632
Georg Brandl116aa622007-08-15 14:28:22 +0000633.. _threads:
634
635Thread State and the Global Interpreter Lock
636============================================
637
638.. index::
639 single: global interpreter lock
640 single: interpreter lock
641 single: lock, interpreter
642
Georg Brandlf285bcc2010-10-19 21:07:16 +0000643The Python interpreter is not fully thread-safe. In order to support
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000644multi-threaded Python programs, there's a global lock, called the :term:`global
645interpreter lock` or :term:`GIL`, that must be held by the current thread before
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000646it can safely access Python objects. Without the lock, even the simplest
647operations could cause problems in a multi-threaded program: for example, when
648two threads simultaneously increment the reference count of the same object, the
649reference count could end up being incremented only once instead of twice.
Georg Brandl116aa622007-08-15 14:28:22 +0000650
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000651.. index:: single: setswitchinterval() (in module sys)
Georg Brandl116aa622007-08-15 14:28:22 +0000652
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000653Therefore, the rule exists that only the thread that has acquired the
654:term:`GIL` may operate on Python objects or call Python/C API functions.
655In order to emulate concurrency of execution, the interpreter regularly
656tries to switch threads (see :func:`sys.setswitchinterval`). The lock is also
657released around potentially blocking I/O operations like reading or writing
658a file, so that other Python threads can run in the meantime.
Georg Brandl116aa622007-08-15 14:28:22 +0000659
660.. index::
661 single: PyThreadState
662 single: PyThreadState
663
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000664The Python interpreter keeps some thread-specific bookkeeping information
665inside a data structure called :c:type:`PyThreadState`. There's also one
666global variable pointing to the current :c:type:`PyThreadState`: it can
667be retrieved using :c:func:`PyThreadState_Get`.
Georg Brandl116aa622007-08-15 14:28:22 +0000668
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000669Releasing the GIL from extension code
670-------------------------------------
671
672Most extension code manipulating the :term:`GIL` has the following simple
673structure::
Georg Brandl116aa622007-08-15 14:28:22 +0000674
675 Save the thread state in a local variable.
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000676 Release the global interpreter lock.
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000677 ... Do some blocking I/O operation ...
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000678 Reacquire the global interpreter lock.
Georg Brandl116aa622007-08-15 14:28:22 +0000679 Restore the thread state from the local variable.
680
681This is so common that a pair of macros exists to simplify it::
682
683 Py_BEGIN_ALLOW_THREADS
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000684 ... Do some blocking I/O operation ...
Georg Brandl116aa622007-08-15 14:28:22 +0000685 Py_END_ALLOW_THREADS
686
687.. index::
688 single: Py_BEGIN_ALLOW_THREADS
689 single: Py_END_ALLOW_THREADS
690
Georg Brandl60203b42010-10-06 10:11:56 +0000691The :c:macro:`Py_BEGIN_ALLOW_THREADS` macro opens a new block and declares a
692hidden local variable; the :c:macro:`Py_END_ALLOW_THREADS` macro closes the
Victor Stinner2914bb32018-01-29 11:57:45 +0100693block.
Georg Brandl116aa622007-08-15 14:28:22 +0000694
Victor Stinner2914bb32018-01-29 11:57:45 +0100695The block above expands to the following code::
Georg Brandl116aa622007-08-15 14:28:22 +0000696
697 PyThreadState *_save;
698
699 _save = PyEval_SaveThread();
Victor Stinner2914bb32018-01-29 11:57:45 +0100700 ... Do some blocking I/O operation ...
Georg Brandl116aa622007-08-15 14:28:22 +0000701 PyEval_RestoreThread(_save);
702
Georg Brandl116aa622007-08-15 14:28:22 +0000703.. index::
704 single: PyEval_RestoreThread()
Georg Brandl116aa622007-08-15 14:28:22 +0000705 single: PyEval_SaveThread()
Georg Brandl116aa622007-08-15 14:28:22 +0000706
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000707Here is how these functions work: the global interpreter lock is used to protect the pointer to the
708current thread state. When releasing the lock and saving the thread state,
709the current thread state pointer must be retrieved before the lock is released
710(since another thread could immediately acquire the lock and store its own thread
711state in the global variable). Conversely, when acquiring the lock and restoring
712the thread state, the lock must be acquired before storing the thread state
713pointer.
Georg Brandl116aa622007-08-15 14:28:22 +0000714
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000715.. note::
716 Calling system I/O functions is the most common use case for releasing
717 the GIL, but it can also be useful before calling long-running computations
718 which don't need access to Python objects, such as compression or
719 cryptographic functions operating over memory buffers. For example, the
720 standard :mod:`zlib` and :mod:`hashlib` modules release the GIL when
721 compressing or hashing data.
Georg Brandl116aa622007-08-15 14:28:22 +0000722
Antoine Pitrou1a67bee2013-09-30 21:35:44 +0200723
724.. _gilstate:
725
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000726Non-Python created threads
727--------------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000728
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000729When threads are created using the dedicated Python APIs (such as the
730:mod:`threading` module), a thread state is automatically associated to them
731and the code showed above is therefore correct. However, when threads are
732created from C (for example by a third-party library with its own thread
733management), they don't hold the GIL, nor is there a thread state structure
734for them.
735
736If you need to call Python code from these threads (often this will be part
737of a callback API provided by the aforementioned third-party library),
738you must first register these threads with the interpreter by
739creating a thread state data structure, then acquiring the GIL, and finally
740storing their thread state pointer, before you can start using the Python/C
741API. When you are done, you should reset the thread state pointer, release
742the GIL, and finally free the thread state data structure.
743
744The :c:func:`PyGILState_Ensure` and :c:func:`PyGILState_Release` functions do
745all of the above automatically. The typical idiom for calling into Python
746from a C thread is::
Georg Brandl116aa622007-08-15 14:28:22 +0000747
748 PyGILState_STATE gstate;
749 gstate = PyGILState_Ensure();
750
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000751 /* Perform Python actions here. */
Georg Brandl116aa622007-08-15 14:28:22 +0000752 result = CallSomeFunction();
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000753 /* evaluate result or handle exception */
Georg Brandl116aa622007-08-15 14:28:22 +0000754
755 /* Release the thread. No Python API allowed beyond this point. */
756 PyGILState_Release(gstate);
757
Georg Brandl60203b42010-10-06 10:11:56 +0000758Note that the :c:func:`PyGILState_\*` functions assume there is only one global
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000759interpreter (created automatically by :c:func:`Py_Initialize`). Python
Georg Brandl116aa622007-08-15 14:28:22 +0000760supports the creation of additional interpreters (using
Georg Brandl60203b42010-10-06 10:11:56 +0000761:c:func:`Py_NewInterpreter`), but mixing multiple interpreters and the
762:c:func:`PyGILState_\*` API is unsupported.
Georg Brandl116aa622007-08-15 14:28:22 +0000763
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000764Another important thing to note about threads is their behaviour in the face
Georg Brandl60203b42010-10-06 10:11:56 +0000765of the C :c:func:`fork` call. On most systems with :c:func:`fork`, after a
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000766process forks only the thread that issued the fork will exist. That also
767means any locks held by other threads will never be released. Python solves
768this for :func:`os.fork` by acquiring the locks it uses internally before
769the fork, and releasing them afterwards. In addition, it resets any
770:ref:`lock-objects` in the child. When extending or embedding Python, there
771is no way to inform Python of additional (non-Python) locks that need to be
772acquired before or reset after a fork. OS facilities such as
Ezio Melotti861d27f2011-04-20 21:32:40 +0300773:c:func:`pthread_atfork` would need to be used to accomplish the same thing.
Georg Brandl60203b42010-10-06 10:11:56 +0000774Additionally, when extending or embedding Python, calling :c:func:`fork`
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000775directly rather than through :func:`os.fork` (and returning to or calling
776into Python) may result in a deadlock by one of Python's internal locks
777being held by a thread that is defunct after the fork.
Antoine Pitrouf7ecfac2017-05-28 11:35:14 +0200778:c:func:`PyOS_AfterFork_Child` tries to reset the necessary locks, but is not
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000779always able to.
Georg Brandl116aa622007-08-15 14:28:22 +0000780
Antoine Pitrou8b50b832011-01-15 11:57:42 +0000781
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000782High-level API
783--------------
784
785These are the most commonly used types and functions when writing C extension
786code, or when embedding the Python interpreter:
787
Georg Brandl60203b42010-10-06 10:11:56 +0000788.. c:type:: PyInterpreterState
Georg Brandl116aa622007-08-15 14:28:22 +0000789
790 This data structure represents the state shared by a number of cooperating
791 threads. Threads belonging to the same interpreter share their module
792 administration and a few other internal items. There are no public members in
793 this structure.
794
795 Threads belonging to different interpreters initially share nothing, except
796 process state like available memory, open file descriptors and such. The global
797 interpreter lock is also shared by all threads, regardless of to which
798 interpreter they belong.
799
800
Georg Brandl60203b42010-10-06 10:11:56 +0000801.. c:type:: PyThreadState
Georg Brandl116aa622007-08-15 14:28:22 +0000802
803 This data structure represents the state of a single thread. The only public
Georg Brandl60203b42010-10-06 10:11:56 +0000804 data member is :c:type:`PyInterpreterState \*`:attr:`interp`, which points to
Georg Brandl116aa622007-08-15 14:28:22 +0000805 this thread's interpreter state.
806
807
Georg Brandl60203b42010-10-06 10:11:56 +0000808.. c:function:: void PyEval_InitThreads()
Georg Brandl116aa622007-08-15 14:28:22 +0000809
810 .. index::
Antoine Pitrouf5cf4352011-01-15 14:31:49 +0000811 single: PyEval_AcquireThread()
Georg Brandl116aa622007-08-15 14:28:22 +0000812 single: PyEval_ReleaseThread()
813 single: PyEval_SaveThread()
814 single: PyEval_RestoreThread()
815
816 Initialize and acquire the global interpreter lock. It should be called in the
817 main thread before creating a second thread or engaging in any other thread
Antoine Pitrouf5cf4352011-01-15 14:31:49 +0000818 operations such as ``PyEval_ReleaseThread(tstate)``. It is not needed before
819 calling :c:func:`PyEval_SaveThread` or :c:func:`PyEval_RestoreThread`.
Georg Brandl116aa622007-08-15 14:28:22 +0000820
Antoine Pitrou9bd3bbc2011-03-13 23:28:28 +0100821 This is a no-op when called for a second time.
Georg Brandl116aa622007-08-15 14:28:22 +0000822
Victor Stinner2914bb32018-01-29 11:57:45 +0100823 .. versionchanged:: 3.7
824 This function is now called by :c:func:`Py_Initialize()`, so you don't
825 have to call it yourself anymore.
826
Antoine Pitrou9bb98772011-03-15 20:22:50 +0100827 .. versionchanged:: 3.2
828 This function cannot be called before :c:func:`Py_Initialize()` anymore.
829
Georg Brandl2067bfd2008-05-25 13:05:15 +0000830 .. index:: module: _thread
Georg Brandl116aa622007-08-15 14:28:22 +0000831
Georg Brandl116aa622007-08-15 14:28:22 +0000832
Georg Brandl60203b42010-10-06 10:11:56 +0000833.. c:function:: int PyEval_ThreadsInitialized()
Georg Brandl116aa622007-08-15 14:28:22 +0000834
Georg Brandl60203b42010-10-06 10:11:56 +0000835 Returns a non-zero value if :c:func:`PyEval_InitThreads` has been called. This
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000836 function can be called without holding the GIL, and therefore can be used to
Victor Stinner2914bb32018-01-29 11:57:45 +0100837 avoid calls to the locking API when running single-threaded.
838
839 .. versionchanged:: 3.7
840 The :term:`GIL` is now initialized by :c:func:`Py_Initialize()`.
Georg Brandl116aa622007-08-15 14:28:22 +0000841
Georg Brandl116aa622007-08-15 14:28:22 +0000842
Georg Brandl60203b42010-10-06 10:11:56 +0000843.. c:function:: PyThreadState* PyEval_SaveThread()
Georg Brandl116aa622007-08-15 14:28:22 +0000844
Zackery Spytzeef05962018-09-29 10:07:11 -0600845 Release the global interpreter lock (if it has been created) and reset the
846 thread state to *NULL*, returning the previous thread state (which is not
847 *NULL*). If the lock has been created, the current thread must have
848 acquired it.
Georg Brandl116aa622007-08-15 14:28:22 +0000849
850
Georg Brandl60203b42010-10-06 10:11:56 +0000851.. c:function:: void PyEval_RestoreThread(PyThreadState *tstate)
Georg Brandl116aa622007-08-15 14:28:22 +0000852
Zackery Spytzeef05962018-09-29 10:07:11 -0600853 Acquire the global interpreter lock (if it has been created) and set the
854 thread state to *tstate*, which must not be *NULL*. If the lock has been
855 created, the current thread must not have acquired it, otherwise deadlock
856 ensues.
Georg Brandl116aa622007-08-15 14:28:22 +0000857
Christian Heimesd8654cf2007-12-02 15:22:16 +0000858
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000859.. c:function:: PyThreadState* PyThreadState_Get()
860
861 Return the current thread state. The global interpreter lock must be held.
862 When the current thread state is *NULL*, this issues a fatal error (so that
863 the caller needn't check for *NULL*).
864
865
866.. c:function:: PyThreadState* PyThreadState_Swap(PyThreadState *tstate)
867
868 Swap the current thread state with the thread state given by the argument
869 *tstate*, which may be *NULL*. The global interpreter lock must be held
870 and is not released.
871
872
Georg Brandl60203b42010-10-06 10:11:56 +0000873.. c:function:: void PyEval_ReInitThreads()
Christian Heimesd8654cf2007-12-02 15:22:16 +0000874
Antoine Pitrouf7ecfac2017-05-28 11:35:14 +0200875 This function is called from :c:func:`PyOS_AfterFork_Child` to ensure
876 that newly created child processes don't hold locks referring to threads
877 which are not running in the child process.
Christian Heimesd8654cf2007-12-02 15:22:16 +0000878
879
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000880The following functions use thread-local storage, and are not compatible
881with sub-interpreters:
882
883.. c:function:: PyGILState_STATE PyGILState_Ensure()
884
885 Ensure that the current thread is ready to call the Python C API regardless
886 of the current state of Python, or of the global interpreter lock. This may
887 be called as many times as desired by a thread as long as each call is
888 matched with a call to :c:func:`PyGILState_Release`. In general, other
889 thread-related APIs may be used between :c:func:`PyGILState_Ensure` and
890 :c:func:`PyGILState_Release` calls as long as the thread state is restored to
891 its previous state before the Release(). For example, normal usage of the
892 :c:macro:`Py_BEGIN_ALLOW_THREADS` and :c:macro:`Py_END_ALLOW_THREADS` macros is
893 acceptable.
894
895 The return value is an opaque "handle" to the thread state when
896 :c:func:`PyGILState_Ensure` was called, and must be passed to
897 :c:func:`PyGILState_Release` to ensure Python is left in the same state. Even
898 though recursive calls are allowed, these handles *cannot* be shared - each
899 unique call to :c:func:`PyGILState_Ensure` must save the handle for its call
900 to :c:func:`PyGILState_Release`.
901
902 When the function returns, the current thread will hold the GIL and be able
903 to call arbitrary Python code. Failure is a fatal error.
904
905
906.. c:function:: void PyGILState_Release(PyGILState_STATE)
907
908 Release any resources previously acquired. After this call, Python's state will
909 be the same as it was prior to the corresponding :c:func:`PyGILState_Ensure` call
910 (but generally this state will be unknown to the caller, hence the use of the
911 GILState API).
912
913 Every call to :c:func:`PyGILState_Ensure` must be matched by a call to
914 :c:func:`PyGILState_Release` on the same thread.
915
916
Eli Bendersky08131682012-06-03 08:07:47 +0300917.. c:function:: PyThreadState* PyGILState_GetThisThreadState()
Sandro Tosi61baee02011-08-08 00:16:54 +0200918
919 Get the current thread state for this thread. May return ``NULL`` if no
920 GILState API has been used on the current thread. Note that the main thread
921 always has such a thread-state, even if no auto-thread-state call has been
922 made on the main thread. This is mainly a helper/diagnostic function.
923
924
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -0700925.. c:function:: int PyGILState_Check()
926
Serhiy Storchaka1ecf7d22016-10-27 21:41:19 +0300927 Return ``1`` if the current thread is holding the GIL and ``0`` otherwise.
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -0700928 This function can be called from any thread at any time.
929 Only if it has had its Python thread state initialized and currently is
Serhiy Storchaka1ecf7d22016-10-27 21:41:19 +0300930 holding the GIL will it return ``1``.
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -0700931 This is mainly a helper/diagnostic function. It can be useful
932 for example in callback contexts or memory allocation functions when
933 knowing that the GIL is locked can allow the caller to perform sensitive
934 actions or otherwise behave differently.
935
Kristján Valur Jónsson34870c42013-03-23 03:56:16 -0700936 .. versionadded:: 3.4
937
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -0700938
Georg Brandl116aa622007-08-15 14:28:22 +0000939The following macros are normally used without a trailing semicolon; look for
940example usage in the Python source distribution.
941
942
Georg Brandl60203b42010-10-06 10:11:56 +0000943.. c:macro:: Py_BEGIN_ALLOW_THREADS
Georg Brandl116aa622007-08-15 14:28:22 +0000944
945 This macro expands to ``{ PyThreadState *_save; _save = PyEval_SaveThread();``.
946 Note that it contains an opening brace; it must be matched with a following
Georg Brandl60203b42010-10-06 10:11:56 +0000947 :c:macro:`Py_END_ALLOW_THREADS` macro. See above for further discussion of this
Victor Stinner2914bb32018-01-29 11:57:45 +0100948 macro.
Georg Brandl116aa622007-08-15 14:28:22 +0000949
950
Georg Brandl60203b42010-10-06 10:11:56 +0000951.. c:macro:: Py_END_ALLOW_THREADS
Georg Brandl116aa622007-08-15 14:28:22 +0000952
953 This macro expands to ``PyEval_RestoreThread(_save); }``. Note that it contains
954 a closing brace; it must be matched with an earlier
Georg Brandl60203b42010-10-06 10:11:56 +0000955 :c:macro:`Py_BEGIN_ALLOW_THREADS` macro. See above for further discussion of
Victor Stinner2914bb32018-01-29 11:57:45 +0100956 this macro.
Georg Brandl116aa622007-08-15 14:28:22 +0000957
958
Georg Brandl60203b42010-10-06 10:11:56 +0000959.. c:macro:: Py_BLOCK_THREADS
Georg Brandl116aa622007-08-15 14:28:22 +0000960
961 This macro expands to ``PyEval_RestoreThread(_save);``: it is equivalent to
Victor Stinner2914bb32018-01-29 11:57:45 +0100962 :c:macro:`Py_END_ALLOW_THREADS` without the closing brace.
Georg Brandl116aa622007-08-15 14:28:22 +0000963
964
Georg Brandl60203b42010-10-06 10:11:56 +0000965.. c:macro:: Py_UNBLOCK_THREADS
Georg Brandl116aa622007-08-15 14:28:22 +0000966
967 This macro expands to ``_save = PyEval_SaveThread();``: it is equivalent to
Georg Brandl60203b42010-10-06 10:11:56 +0000968 :c:macro:`Py_BEGIN_ALLOW_THREADS` without the opening brace and variable
Victor Stinner2914bb32018-01-29 11:57:45 +0100969 declaration.
Georg Brandl116aa622007-08-15 14:28:22 +0000970
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000971
972Low-level API
973-------------
974
Victor Stinner2914bb32018-01-29 11:57:45 +0100975All of the following functions must be called after :c:func:`Py_Initialize`.
976
977.. versionchanged:: 3.7
978 :c:func:`Py_Initialize()` now initializes the :term:`GIL`.
Georg Brandl116aa622007-08-15 14:28:22 +0000979
980
Georg Brandl60203b42010-10-06 10:11:56 +0000981.. c:function:: PyInterpreterState* PyInterpreterState_New()
Georg Brandl116aa622007-08-15 14:28:22 +0000982
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000983 Create a new interpreter state object. The global interpreter lock need not
984 be held, but may be held if it is necessary to serialize calls to this
985 function.
Georg Brandl116aa622007-08-15 14:28:22 +0000986
987
Georg Brandl60203b42010-10-06 10:11:56 +0000988.. c:function:: void PyInterpreterState_Clear(PyInterpreterState *interp)
Georg Brandl116aa622007-08-15 14:28:22 +0000989
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000990 Reset all information in an interpreter state object. The global interpreter
991 lock must be held.
Georg Brandl116aa622007-08-15 14:28:22 +0000992
993
Georg Brandl60203b42010-10-06 10:11:56 +0000994.. c:function:: void PyInterpreterState_Delete(PyInterpreterState *interp)
Georg Brandl116aa622007-08-15 14:28:22 +0000995
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000996 Destroy an interpreter state object. The global interpreter lock need not be
997 held. The interpreter state must have been reset with a previous call to
Georg Brandl60203b42010-10-06 10:11:56 +0000998 :c:func:`PyInterpreterState_Clear`.
Georg Brandl116aa622007-08-15 14:28:22 +0000999
1000
Georg Brandl60203b42010-10-06 10:11:56 +00001001.. c:function:: PyThreadState* PyThreadState_New(PyInterpreterState *interp)
Georg Brandl116aa622007-08-15 14:28:22 +00001002
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001003 Create a new thread state object belonging to the given interpreter object.
1004 The global interpreter lock need not be held, but may be held if it is
1005 necessary to serialize calls to this function.
Georg Brandl116aa622007-08-15 14:28:22 +00001006
1007
Georg Brandl60203b42010-10-06 10:11:56 +00001008.. c:function:: void PyThreadState_Clear(PyThreadState *tstate)
Georg Brandl116aa622007-08-15 14:28:22 +00001009
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001010 Reset all information in a thread state object. The global interpreter lock
1011 must be held.
Georg Brandl116aa622007-08-15 14:28:22 +00001012
1013
Georg Brandl60203b42010-10-06 10:11:56 +00001014.. c:function:: void PyThreadState_Delete(PyThreadState *tstate)
Georg Brandl116aa622007-08-15 14:28:22 +00001015
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001016 Destroy a thread state object. The global interpreter lock need not be held.
1017 The thread state must have been reset with a previous call to
Georg Brandl60203b42010-10-06 10:11:56 +00001018 :c:func:`PyThreadState_Clear`.
Georg Brandl116aa622007-08-15 14:28:22 +00001019
1020
Eric Snowe3774162017-05-22 19:46:40 -07001021.. c:function:: PY_INT64_T PyInterpreterState_GetID(PyInterpreterState *interp)
1022
1023 Return the interpreter's unique ID. If there was any error in doing
Serhiy Storchaka5bb00052018-02-09 13:31:19 +02001024 so then ``-1`` is returned and an error is set.
Eric Snowe3774162017-05-22 19:46:40 -07001025
1026 .. versionadded:: 3.7
1027
1028
Georg Brandl60203b42010-10-06 10:11:56 +00001029.. c:function:: PyObject* PyThreadState_GetDict()
Georg Brandl116aa622007-08-15 14:28:22 +00001030
1031 Return a dictionary in which extensions can store thread-specific state
1032 information. Each extension should use a unique key to use to store state in
1033 the dictionary. It is okay to call this function when no current thread state
1034 is available. If this function returns *NULL*, no exception has been raised and
1035 the caller should assume no current thread state is available.
1036
Georg Brandl116aa622007-08-15 14:28:22 +00001037
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02001038.. c:function:: int PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
Georg Brandl116aa622007-08-15 14:28:22 +00001039
1040 Asynchronously raise an exception in a thread. The *id* argument is the thread
1041 id of the target thread; *exc* is the exception object to be raised. This
1042 function does not steal any references to *exc*. To prevent naive misuse, you
1043 must write your own C extension to call this. Must be called with the GIL held.
1044 Returns the number of thread states modified; this is normally one, but will be
1045 zero if the thread id isn't found. If *exc* is :const:`NULL`, the pending
1046 exception (if any) for the thread is cleared. This raises no exceptions.
1047
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02001048 .. versionchanged:: 3.7
1049 The type of the *id* parameter changed from :c:type:`long` to
1050 :c:type:`unsigned long`.
Georg Brandl116aa622007-08-15 14:28:22 +00001051
Antoine Pitroubedd2c22011-01-15 12:54:19 +00001052.. c:function:: void PyEval_AcquireThread(PyThreadState *tstate)
Georg Brandl116aa622007-08-15 14:28:22 +00001053
Antoine Pitroubedd2c22011-01-15 12:54:19 +00001054 Acquire the global interpreter lock and set the current thread state to
1055 *tstate*, which should not be *NULL*. The lock must have been created earlier.
1056 If this thread already has the lock, deadlock ensues.
Georg Brandl116aa622007-08-15 14:28:22 +00001057
Antoine Pitrou5ace8e92011-01-15 13:11:48 +00001058 :c:func:`PyEval_RestoreThread` is a higher-level function which is always
Victor Stinner2914bb32018-01-29 11:57:45 +01001059 available (even when threads have not been initialized).
Antoine Pitrou5ace8e92011-01-15 13:11:48 +00001060
Georg Brandl116aa622007-08-15 14:28:22 +00001061
Antoine Pitroubedd2c22011-01-15 12:54:19 +00001062.. c:function:: void PyEval_ReleaseThread(PyThreadState *tstate)
Georg Brandl116aa622007-08-15 14:28:22 +00001063
Antoine Pitroubedd2c22011-01-15 12:54:19 +00001064 Reset the current thread state to *NULL* and release the global interpreter
1065 lock. The lock must have been created earlier and must be held by the current
1066 thread. The *tstate* argument, which must not be *NULL*, is only used to check
1067 that it represents the current thread state --- if it isn't, a fatal error is
1068 reported.
Georg Brandl116aa622007-08-15 14:28:22 +00001069
Antoine Pitrou5ace8e92011-01-15 13:11:48 +00001070 :c:func:`PyEval_SaveThread` is a higher-level function which is always
Victor Stinner2914bb32018-01-29 11:57:45 +01001071 available (even when threads have not been initialized).
Antoine Pitrou5ace8e92011-01-15 13:11:48 +00001072
Antoine Pitroubedd2c22011-01-15 12:54:19 +00001073
1074.. c:function:: void PyEval_AcquireLock()
1075
1076 Acquire the global interpreter lock. The lock must have been created earlier.
1077 If this thread already has the lock, a deadlock ensues.
1078
Antoine Pitrou5ace8e92011-01-15 13:11:48 +00001079 .. deprecated:: 3.2
Antoine Pitrouf5cf4352011-01-15 14:31:49 +00001080 This function does not update the current thread state. Please use
Antoine Pitrou5ace8e92011-01-15 13:11:48 +00001081 :c:func:`PyEval_RestoreThread` or :c:func:`PyEval_AcquireThread`
1082 instead.
1083
Antoine Pitroubedd2c22011-01-15 12:54:19 +00001084
1085.. c:function:: void PyEval_ReleaseLock()
1086
1087 Release the global interpreter lock. The lock must have been created earlier.
Georg Brandl116aa622007-08-15 14:28:22 +00001088
Antoine Pitrou5ace8e92011-01-15 13:11:48 +00001089 .. deprecated:: 3.2
Antoine Pitrouf5cf4352011-01-15 14:31:49 +00001090 This function does not update the current thread state. Please use
Antoine Pitrou5ace8e92011-01-15 13:11:48 +00001091 :c:func:`PyEval_SaveThread` or :c:func:`PyEval_ReleaseThread`
1092 instead.
1093
Georg Brandl116aa622007-08-15 14:28:22 +00001094
Nick Coghlan2ab5b092015-07-03 19:49:15 +10001095.. _sub-interpreter-support:
1096
Antoine Pitrou8b50b832011-01-15 11:57:42 +00001097Sub-interpreter support
1098=======================
1099
1100While in most uses, you will only embed a single Python interpreter, there
1101are cases where you need to create several independent interpreters in the
1102same process and perhaps even in the same thread. Sub-interpreters allow
Antoine Pitrou9bf8d1c2011-01-15 12:21:53 +00001103you to do that. You can switch between sub-interpreters using the
1104:c:func:`PyThreadState_Swap` function. You can create and destroy them
1105using the following functions:
Antoine Pitrou8b50b832011-01-15 11:57:42 +00001106
1107
1108.. c:function:: PyThreadState* Py_NewInterpreter()
1109
1110 .. index::
1111 module: builtins
1112 module: __main__
1113 module: sys
1114 single: stdout (in module sys)
1115 single: stderr (in module sys)
1116 single: stdin (in module sys)
1117
1118 Create a new sub-interpreter. This is an (almost) totally separate environment
1119 for the execution of Python code. In particular, the new interpreter has
1120 separate, independent versions of all imported modules, including the
1121 fundamental modules :mod:`builtins`, :mod:`__main__` and :mod:`sys`. The
1122 table of loaded modules (``sys.modules``) and the module search path
1123 (``sys.path``) are also separate. The new environment has no ``sys.argv``
1124 variable. It has new standard I/O stream file objects ``sys.stdin``,
1125 ``sys.stdout`` and ``sys.stderr`` (however these refer to the same underlying
1126 file descriptors).
1127
1128 The return value points to the first thread state created in the new
1129 sub-interpreter. This thread state is made in the current thread state.
1130 Note that no actual thread is created; see the discussion of thread states
1131 below. If creation of the new interpreter is unsuccessful, *NULL* is
1132 returned; no exception is set since the exception state is stored in the
1133 current thread state and there may not be a current thread state. (Like all
1134 other Python/C API functions, the global interpreter lock must be held before
1135 calling this function and is still held when it returns; however, unlike most
1136 other Python/C API functions, there needn't be a current thread state on
1137 entry.)
1138
1139 .. index::
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001140 single: Py_FinalizeEx()
Antoine Pitrou8b50b832011-01-15 11:57:42 +00001141 single: Py_Initialize()
1142
1143 Extension modules are shared between (sub-)interpreters as follows: the first
1144 time a particular extension is imported, it is initialized normally, and a
1145 (shallow) copy of its module's dictionary is squirreled away. When the same
1146 extension is imported by another (sub-)interpreter, a new module is initialized
1147 and filled with the contents of this copy; the extension's ``init`` function is
1148 not called. Note that this is different from what happens when an extension is
1149 imported after the interpreter has been completely re-initialized by calling
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001150 :c:func:`Py_FinalizeEx` and :c:func:`Py_Initialize`; in that case, the extension's
Antoine Pitrou8b50b832011-01-15 11:57:42 +00001151 ``initmodule`` function *is* called again.
1152
1153 .. index:: single: close() (in module os)
1154
1155
1156.. c:function:: void Py_EndInterpreter(PyThreadState *tstate)
1157
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001158 .. index:: single: Py_FinalizeEx()
Antoine Pitrou8b50b832011-01-15 11:57:42 +00001159
1160 Destroy the (sub-)interpreter represented by the given thread state. The given
1161 thread state must be the current thread state. See the discussion of thread
1162 states below. When the call returns, the current thread state is *NULL*. All
1163 thread states associated with this interpreter are destroyed. (The global
1164 interpreter lock must be held before calling this function and is still held
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001165 when it returns.) :c:func:`Py_FinalizeEx` will destroy all sub-interpreters that
Antoine Pitrou8b50b832011-01-15 11:57:42 +00001166 haven't been explicitly destroyed at that point.
1167
1168
1169Bugs and caveats
1170----------------
1171
1172Because sub-interpreters (and the main interpreter) are part of the same
1173process, the insulation between them isn't perfect --- for example, using
1174low-level file operations like :func:`os.close` they can
1175(accidentally or maliciously) affect each other's open files. Because of the
1176way extensions are shared between (sub-)interpreters, some extensions may not
1177work properly; this is especially likely when the extension makes use of
1178(static) global variables, or when the extension manipulates its module's
1179dictionary after its initialization. It is possible to insert objects created
1180in one sub-interpreter into a namespace of another sub-interpreter; this should
1181be done with great care to avoid sharing user-defined functions, methods,
1182instances or classes between sub-interpreters, since import operations executed
1183by such objects may affect the wrong (sub-)interpreter's dictionary of loaded
Antoine Pitrouf1dfe732011-01-15 12:10:48 +00001184modules.
Antoine Pitrou8b50b832011-01-15 11:57:42 +00001185
Antoine Pitrouf1dfe732011-01-15 12:10:48 +00001186Also note that combining this functionality with :c:func:`PyGILState_\*` APIs
Ezio Melottid92ab082011-05-05 14:19:48 +03001187is delicate, because these APIs assume a bijection between Python thread states
Antoine Pitrouf1dfe732011-01-15 12:10:48 +00001188and OS-level threads, an assumption broken by the presence of sub-interpreters.
1189It is highly recommended that you don't switch sub-interpreters between a pair
1190of matching :c:func:`PyGILState_Ensure` and :c:func:`PyGILState_Release` calls.
1191Furthermore, extensions (such as :mod:`ctypes`) using these APIs to allow calling
1192of Python code from non-Python created threads will probably be broken when using
1193sub-interpreters.
Antoine Pitrou8b50b832011-01-15 11:57:42 +00001194
Benjamin Petersona54c9092009-01-13 02:11:23 +00001195
1196Asynchronous Notifications
1197==========================
1198
Benjamin Petersond23f8222009-04-05 19:13:16 +00001199A mechanism is provided to make asynchronous notifications to the main
Benjamin Petersona54c9092009-01-13 02:11:23 +00001200interpreter thread. These notifications take the form of a function
Antoine Pitrou1a67bee2013-09-30 21:35:44 +02001201pointer and a void pointer argument.
Benjamin Petersona54c9092009-01-13 02:11:23 +00001202
Benjamin Petersona54c9092009-01-13 02:11:23 +00001203
Ezio Melottia782cca2011-04-28 00:53:14 +03001204.. c:function:: int Py_AddPendingCall(int (*func)(void *), void *arg)
Benjamin Petersona54c9092009-01-13 02:11:23 +00001205
1206 .. index:: single: Py_AddPendingCall()
1207
Antoine Pitrou1a67bee2013-09-30 21:35:44 +02001208 Schedule a function to be called from the main interpreter thread. On
Serhiy Storchaka1ecf7d22016-10-27 21:41:19 +03001209 success, ``0`` is returned and *func* is queued for being called in the
1210 main thread. On failure, ``-1`` is returned without setting any exception.
Benjamin Petersona54c9092009-01-13 02:11:23 +00001211
Antoine Pitrou1a67bee2013-09-30 21:35:44 +02001212 When successfully queued, *func* will be *eventually* called from the
1213 main interpreter thread with the argument *arg*. It will be called
1214 asynchronously with respect to normally running Python code, but with
1215 both these conditions met:
Benjamin Petersona54c9092009-01-13 02:11:23 +00001216
Antoine Pitrou1a67bee2013-09-30 21:35:44 +02001217 * on a :term:`bytecode` boundary;
1218 * with the main thread holding the :term:`global interpreter lock`
1219 (*func* can therefore use the full C API).
1220
Serhiy Storchaka1ecf7d22016-10-27 21:41:19 +03001221 *func* must return ``0`` on success, or ``-1`` on failure with an exception
Antoine Pitrou1a67bee2013-09-30 21:35:44 +02001222 set. *func* won't be interrupted to perform another asynchronous
1223 notification recursively, but it can still be interrupted to switch
1224 threads if the global interpreter lock is released.
1225
1226 This function doesn't need a current thread state to run, and it doesn't
1227 need the global interpreter lock.
1228
1229 .. warning::
1230 This is a low-level function, only useful for very special cases.
1231 There is no guarantee that *func* will be called as quick as
1232 possible. If the main thread is busy executing a system call,
1233 *func* won't be called before the system call returns. This
1234 function is generally **not** suitable for calling Python code from
1235 arbitrary C threads. Instead, use the :ref:`PyGILState API<gilstate>`.
Benjamin Petersona54c9092009-01-13 02:11:23 +00001236
Georg Brandl705d9d52009-05-05 09:29:50 +00001237 .. versionadded:: 3.1
Benjamin Petersona54c9092009-01-13 02:11:23 +00001238
Georg Brandl116aa622007-08-15 14:28:22 +00001239.. _profiling:
1240
1241Profiling and Tracing
1242=====================
1243
1244.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
1245
1246
1247The Python interpreter provides some low-level support for attaching profiling
1248and execution tracing facilities. These are used for profiling, debugging, and
1249coverage analysis tools.
1250
Georg Brandle6bcc912008-05-12 18:05:20 +00001251This C interface allows the profiling or tracing code to avoid the overhead of
1252calling through Python-level callable objects, making a direct C function call
1253instead. The essential attributes of the facility have not changed; the
1254interface allows trace functions to be installed per-thread, and the basic
1255events reported to the trace function are the same as had been reported to the
1256Python-level trace functions in previous versions.
Georg Brandl116aa622007-08-15 14:28:22 +00001257
1258
Georg Brandl60203b42010-10-06 10:11:56 +00001259.. c:type:: int (*Py_tracefunc)(PyObject *obj, PyFrameObject *frame, int what, PyObject *arg)
Georg Brandl116aa622007-08-15 14:28:22 +00001260
Georg Brandl60203b42010-10-06 10:11:56 +00001261 The type of the trace function registered using :c:func:`PyEval_SetProfile` and
1262 :c:func:`PyEval_SetTrace`. The first parameter is the object passed to the
Georg Brandl116aa622007-08-15 14:28:22 +00001263 registration function as *obj*, *frame* is the frame object to which the event
1264 pertains, *what* is one of the constants :const:`PyTrace_CALL`,
1265 :const:`PyTrace_EXCEPTION`, :const:`PyTrace_LINE`, :const:`PyTrace_RETURN`,
Xiang Zhang255f7a22018-01-28 17:53:38 +08001266 :const:`PyTrace_C_CALL`, :const:`PyTrace_C_EXCEPTION`, :const:`PyTrace_C_RETURN`,
1267 or :const:`PyTrace_OPCODE`, and *arg* depends on the value of *what*:
Georg Brandl116aa622007-08-15 14:28:22 +00001268
1269 +------------------------------+--------------------------------------+
1270 | Value of *what* | Meaning of *arg* |
1271 +==============================+======================================+
Xiang Zhang9ed0aee2018-01-28 15:38:21 +08001272 | :const:`PyTrace_CALL` | Always :c:data:`Py_None`. |
Georg Brandl116aa622007-08-15 14:28:22 +00001273 +------------------------------+--------------------------------------+
1274 | :const:`PyTrace_EXCEPTION` | Exception information as returned by |
1275 | | :func:`sys.exc_info`. |
1276 +------------------------------+--------------------------------------+
Xiang Zhang9ed0aee2018-01-28 15:38:21 +08001277 | :const:`PyTrace_LINE` | Always :c:data:`Py_None`. |
Georg Brandl116aa622007-08-15 14:28:22 +00001278 +------------------------------+--------------------------------------+
Georg Brandld0b0e1d2010-10-15 16:42:37 +00001279 | :const:`PyTrace_RETURN` | Value being returned to the caller, |
1280 | | or *NULL* if caused by an exception. |
Georg Brandl116aa622007-08-15 14:28:22 +00001281 +------------------------------+--------------------------------------+
Georg Brandld0b0e1d2010-10-15 16:42:37 +00001282 | :const:`PyTrace_C_CALL` | Function object being called. |
Georg Brandl116aa622007-08-15 14:28:22 +00001283 +------------------------------+--------------------------------------+
Georg Brandld0b0e1d2010-10-15 16:42:37 +00001284 | :const:`PyTrace_C_EXCEPTION` | Function object being called. |
Georg Brandl116aa622007-08-15 14:28:22 +00001285 +------------------------------+--------------------------------------+
Georg Brandld0b0e1d2010-10-15 16:42:37 +00001286 | :const:`PyTrace_C_RETURN` | Function object being called. |
Georg Brandl116aa622007-08-15 14:28:22 +00001287 +------------------------------+--------------------------------------+
Xiang Zhang255f7a22018-01-28 17:53:38 +08001288 | :const:`PyTrace_OPCODE` | Always :c:data:`Py_None`. |
1289 +------------------------------+--------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00001290
Georg Brandl60203b42010-10-06 10:11:56 +00001291.. c:var:: int PyTrace_CALL
Georg Brandl116aa622007-08-15 14:28:22 +00001292
Georg Brandl60203b42010-10-06 10:11:56 +00001293 The value of the *what* parameter to a :c:type:`Py_tracefunc` function when a new
Georg Brandl116aa622007-08-15 14:28:22 +00001294 call to a function or method is being reported, or a new entry into a generator.
1295 Note that the creation of the iterator for a generator function is not reported
1296 as there is no control transfer to the Python bytecode in the corresponding
1297 frame.
1298
1299
Georg Brandl60203b42010-10-06 10:11:56 +00001300.. c:var:: int PyTrace_EXCEPTION
Georg Brandl116aa622007-08-15 14:28:22 +00001301
Georg Brandl60203b42010-10-06 10:11:56 +00001302 The value of the *what* parameter to a :c:type:`Py_tracefunc` function when an
Georg Brandl116aa622007-08-15 14:28:22 +00001303 exception has been raised. The callback function is called with this value for
1304 *what* when after any bytecode is processed after which the exception becomes
1305 set within the frame being executed. The effect of this is that as exception
1306 propagation causes the Python stack to unwind, the callback is called upon
1307 return to each frame as the exception propagates. Only trace functions receives
1308 these events; they are not needed by the profiler.
1309
1310
Georg Brandl60203b42010-10-06 10:11:56 +00001311.. c:var:: int PyTrace_LINE
Georg Brandl116aa622007-08-15 14:28:22 +00001312
Xiang Zhang255f7a22018-01-28 17:53:38 +08001313 The value passed as the *what* parameter to a :c:type:`Py_tracefunc` function
1314 (but not a profiling function) when a line-number event is being reported.
1315 It may be disabled for a frame by setting :attr:`f_trace_lines` to *0* on that frame.
Georg Brandl116aa622007-08-15 14:28:22 +00001316
1317
Georg Brandl60203b42010-10-06 10:11:56 +00001318.. c:var:: int PyTrace_RETURN
Georg Brandl116aa622007-08-15 14:28:22 +00001319
Georg Brandl60203b42010-10-06 10:11:56 +00001320 The value for the *what* parameter to :c:type:`Py_tracefunc` functions when a
Xiang Zhang79db11c2018-01-28 22:54:42 +08001321 call is about to return.
Georg Brandl116aa622007-08-15 14:28:22 +00001322
1323
Georg Brandl60203b42010-10-06 10:11:56 +00001324.. c:var:: int PyTrace_C_CALL
Georg Brandl116aa622007-08-15 14:28:22 +00001325
Georg Brandl60203b42010-10-06 10:11:56 +00001326 The value for the *what* parameter to :c:type:`Py_tracefunc` functions when a C
Georg Brandl116aa622007-08-15 14:28:22 +00001327 function is about to be called.
1328
1329
Georg Brandl60203b42010-10-06 10:11:56 +00001330.. c:var:: int PyTrace_C_EXCEPTION
Georg Brandl116aa622007-08-15 14:28:22 +00001331
Georg Brandl60203b42010-10-06 10:11:56 +00001332 The value for the *what* parameter to :c:type:`Py_tracefunc` functions when a C
Georg Brandl7cb13192010-08-03 12:06:29 +00001333 function has raised an exception.
Georg Brandl116aa622007-08-15 14:28:22 +00001334
1335
Georg Brandl60203b42010-10-06 10:11:56 +00001336.. c:var:: int PyTrace_C_RETURN
Georg Brandl116aa622007-08-15 14:28:22 +00001337
Georg Brandl60203b42010-10-06 10:11:56 +00001338 The value for the *what* parameter to :c:type:`Py_tracefunc` functions when a C
Georg Brandl116aa622007-08-15 14:28:22 +00001339 function has returned.
1340
1341
Xiang Zhang255f7a22018-01-28 17:53:38 +08001342.. c:var:: int PyTrace_OPCODE
1343
1344 The value for the *what* parameter to :c:type:`Py_tracefunc` functions (but not
1345 profiling functions) when a new opcode is about to be executed. This event is
1346 not emitted by default: it must be explicitly requested by setting
1347 :attr:`f_trace_opcodes` to *1* on the frame.
1348
1349
Georg Brandl60203b42010-10-06 10:11:56 +00001350.. c:function:: void PyEval_SetProfile(Py_tracefunc func, PyObject *obj)
Georg Brandl116aa622007-08-15 14:28:22 +00001351
1352 Set the profiler function to *func*. The *obj* parameter is passed to the
1353 function as its first parameter, and may be any Python object, or *NULL*. If
1354 the profile function needs to maintain state, using a different value for *obj*
1355 for each thread provides a convenient and thread-safe place to store it. The
Pablo Galindo131fd7f2018-01-24 12:57:49 +00001356 profile function is called for all monitored events except :const:`PyTrace_LINE`
Xiang Zhang255f7a22018-01-28 17:53:38 +08001357 :const:`PyTrace_OPCODE` and :const:`PyTrace_EXCEPTION`.
Georg Brandl116aa622007-08-15 14:28:22 +00001358
1359
Georg Brandl60203b42010-10-06 10:11:56 +00001360.. c:function:: void PyEval_SetTrace(Py_tracefunc func, PyObject *obj)
Georg Brandl116aa622007-08-15 14:28:22 +00001361
1362 Set the tracing function to *func*. This is similar to
Georg Brandl60203b42010-10-06 10:11:56 +00001363 :c:func:`PyEval_SetProfile`, except the tracing function does receive line-number
Xiang Zhang255f7a22018-01-28 17:53:38 +08001364 events and per-opcode events, but does not receive any event related to C function
1365 objects being called. Any trace function registered using :c:func:`PyEval_SetTrace`
1366 will not receive :const:`PyTrace_C_CALL`, :const:`PyTrace_C_EXCEPTION` or
1367 :const:`PyTrace_C_RETURN` as a value for the *what* parameter.
Georg Brandl116aa622007-08-15 14:28:22 +00001368
1369.. _advanced-debugging:
1370
1371Advanced Debugger Support
1372=========================
1373
1374.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
1375
1376
1377These functions are only intended to be used by advanced debugging tools.
1378
1379
Georg Brandl60203b42010-10-06 10:11:56 +00001380.. c:function:: PyInterpreterState* PyInterpreterState_Head()
Georg Brandl116aa622007-08-15 14:28:22 +00001381
1382 Return the interpreter state object at the head of the list of all such objects.
1383
Georg Brandl116aa622007-08-15 14:28:22 +00001384
Georg Brandl60203b42010-10-06 10:11:56 +00001385.. c:function:: PyInterpreterState* PyInterpreterState_Next(PyInterpreterState *interp)
Georg Brandl116aa622007-08-15 14:28:22 +00001386
1387 Return the next interpreter state object after *interp* from the list of all
1388 such objects.
1389
Georg Brandl116aa622007-08-15 14:28:22 +00001390
Georg Brandl60203b42010-10-06 10:11:56 +00001391.. c:function:: PyThreadState * PyInterpreterState_ThreadHead(PyInterpreterState *interp)
Georg Brandl116aa622007-08-15 14:28:22 +00001392
Benjamin Peterson82f34ad2015-01-13 09:17:24 -05001393 Return the pointer to the first :c:type:`PyThreadState` object in the list of
Georg Brandl116aa622007-08-15 14:28:22 +00001394 threads associated with the interpreter *interp*.
1395
Georg Brandl116aa622007-08-15 14:28:22 +00001396
Georg Brandl60203b42010-10-06 10:11:56 +00001397.. c:function:: PyThreadState* PyThreadState_Next(PyThreadState *tstate)
Georg Brandl116aa622007-08-15 14:28:22 +00001398
1399 Return the next thread state object after *tstate* from the list of all such
Georg Brandl60203b42010-10-06 10:11:56 +00001400 objects belonging to the same :c:type:`PyInterpreterState` object.
Georg Brandl116aa622007-08-15 14:28:22 +00001401
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001402
1403.. _thread-local-storage:
1404
1405Thread Local Storage Support
1406============================
1407
1408.. sectionauthor:: Masayuki Yamamoto <ma3yuki.8mamo10@gmail.com>
1409
1410The Python interpreter provides low-level support for thread-local storage
1411(TLS) which wraps the underlying native TLS implementation to support the
1412Python-level thread local storage API (:class:`threading.local`). The
1413CPython C level APIs are similar to those offered by pthreads and Windows:
1414use a thread key and functions to associate a :c:type:`void\*` value per
1415thread.
1416
1417The GIL does *not* need to be held when calling these functions; they supply
1418their own locking.
1419
1420Note that :file:`Python.h` does not include the declaration of the TLS APIs,
1421you need to include :file:`pythread.h` to use thread-local storage.
1422
1423.. note::
1424 None of these API functions handle memory management on behalf of the
1425 :c:type:`void\*` values. You need to allocate and deallocate them yourself.
1426 If the :c:type:`void\*` values happen to be :c:type:`PyObject\*`, these
1427 functions don't do refcount operations on them either.
1428
1429.. _thread-specific-storage-api:
1430
1431Thread Specific Storage (TSS) API
1432---------------------------------
1433
1434TSS API is introduced to supersede the use of the existing TLS API within the
1435CPython interpreter. This API uses a new type :c:type:`Py_tss_t` instead of
1436:c:type:`int` to represent thread keys.
1437
1438.. versionadded:: 3.7
1439
1440.. seealso:: "A New C-API for Thread-Local Storage in CPython" (:pep:`539`)
1441
1442
1443.. c:type:: Py_tss_t
1444
1445 This data structure represents the state of a thread key, the definition of
1446 which may depend on the underlying TLS implementation, and it has an
1447 internal field representing the key's initialization state. There are no
1448 public members in this structure.
1449
1450 When :ref:`Py_LIMITED_API <stable>` is not defined, static allocation of
1451 this type by :c:macro:`Py_tss_NEEDS_INIT` is allowed.
1452
1453
1454.. c:macro:: Py_tss_NEEDS_INIT
1455
Masayuki Yamamoto831d61d2017-10-24 21:58:16 +09001456 This macro expands to the initializer for :c:type:`Py_tss_t` variables.
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001457 Note that this macro won't be defined with :ref:`Py_LIMITED_API <stable>`.
1458
1459
1460Dynamic Allocation
1461~~~~~~~~~~~~~~~~~~
1462
1463Dynamic allocation of the :c:type:`Py_tss_t`, required in extension modules
1464built with :ref:`Py_LIMITED_API <stable>`, where static allocation of this type
1465is not possible due to its implementation being opaque at build time.
1466
1467
1468.. c:function:: Py_tss_t* PyThread_tss_alloc()
1469
1470 Return a value which is the same state as a value initialized with
1471 :c:macro:`Py_tss_NEEDS_INIT`, or *NULL* in the case of dynamic allocation
1472 failure.
1473
1474
1475.. c:function:: void PyThread_tss_free(Py_tss_t *key)
1476
1477 Free the given *key* allocated by :c:func:`PyThread_tss_alloc`, after
1478 first calling :c:func:`PyThread_tss_delete` to ensure any associated
1479 thread locals have been unassigned. This is a no-op if the *key*
1480 argument is `NULL`.
1481
1482 .. note::
1483 A freed key becomes a dangling pointer, you should reset the key to
1484 `NULL`.
1485
1486
1487Methods
1488~~~~~~~
1489
1490The parameter *key* of these functions must not be *NULL*. Moreover, the
1491behaviors of :c:func:`PyThread_tss_set` and :c:func:`PyThread_tss_get` are
1492undefined if the given :c:type:`Py_tss_t` has not been initialized by
1493:c:func:`PyThread_tss_create`.
1494
1495
1496.. c:function:: int PyThread_tss_is_created(Py_tss_t *key)
1497
1498 Return a non-zero value if the given :c:type:`Py_tss_t` has been initialized
1499 by :c:func:`PyThread_tss_create`.
1500
1501
1502.. c:function:: int PyThread_tss_create(Py_tss_t *key)
1503
1504 Return a zero value on successful initialization of a TSS key. The behavior
1505 is undefined if the value pointed to by the *key* argument is not
1506 initialized by :c:macro:`Py_tss_NEEDS_INIT`. This function can be called
1507 repeatedly on the same key -- calling it on an already initialized key is a
1508 no-op and immediately returns success.
1509
1510
1511.. c:function:: void PyThread_tss_delete(Py_tss_t *key)
1512
1513 Destroy a TSS key to forget the values associated with the key across all
1514 threads, and change the key's initialization state to uninitialized. A
1515 destroyed key is able to be initialized again by
1516 :c:func:`PyThread_tss_create`. This function can be called repeatedly on
1517 the same key -- calling it on an already destroyed key is a no-op.
1518
1519
1520.. c:function:: int PyThread_tss_set(Py_tss_t *key, void *value)
1521
1522 Return a zero value to indicate successfully associating a :c:type:`void\*`
1523 value with a TSS key in the current thread. Each thread has a distinct
1524 mapping of the key to a :c:type:`void\*` value.
1525
1526
1527.. c:function:: void* PyThread_tss_get(Py_tss_t *key)
1528
1529 Return the :c:type:`void\*` value associated with a TSS key in the current
1530 thread. This returns *NULL* if no value is associated with the key in the
1531 current thread.
1532
1533
1534.. _thread-local-storage-api:
1535
1536Thread Local Storage (TLS) API
1537------------------------------
1538
1539.. deprecated:: 3.7
1540 This API is superseded by
1541 :ref:`Thread Specific Storage (TSS) API <thread-specific-storage-api>`.
1542
1543.. note::
1544 This version of the API does not support platforms where the native TLS key
1545 is defined in a way that cannot be safely cast to ``int``. On such platforms,
1546 :c:func:`PyThread_create_key` will return immediately with a failure status,
1547 and the other TLS functions will all be no-ops on such platforms.
1548
1549Due to the compatibility problem noted above, this version of the API should not
1550be used in new code.
1551
1552.. c:function:: int PyThread_create_key()
1553.. c:function:: void PyThread_delete_key(int key)
1554.. c:function:: int PyThread_set_key_value(int key, void *value)
1555.. c:function:: void* PyThread_get_key_value(int key)
1556.. c:function:: void PyThread_delete_key_value(int key)
1557.. c:function:: void PyThread_ReInitTLS()
1558