blob: 4ee61e8a1cf256914f76720f2c1784e80538d5d2 [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`
34
35* Informative functions:
36
37 * :c:func:`PyMem_GetAllocator`
38 * :c:func:`PyObject_GetArenaAllocator`
39 * :c:func:`Py_GetBuildInfo`
40 * :c:func:`Py_GetCompiler`
41 * :c:func:`Py_GetCopyright`
42 * :c:func:`Py_GetPlatform`
Victor Stinner84c4b192017-11-24 22:30:27 +010043 * :c:func:`Py_GetVersion`
44
45* Utilities:
46
47 * :c:func:`Py_DecodeLocale`
48
49* Memory allocators:
50
51 * :c:func:`PyMem_RawMalloc`
52 * :c:func:`PyMem_RawRealloc`
53 * :c:func:`PyMem_RawCalloc`
54 * :c:func:`PyMem_RawFree`
55
56.. note::
57
58 The following functions **should not be called** before
59 :c:func:`Py_Initialize`: :c:func:`Py_EncodeLocale`, :c:func:`Py_GetPath`,
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +010060 :c:func:`Py_GetPrefix`, :c:func:`Py_GetExecPrefix`,
Victor Stinner31a83932017-12-04 13:39:15 +010061 :c:func:`Py_GetProgramFullPath`, :c:func:`Py_GetPythonHome`,
62 :c:func:`Py_GetProgramName` and :c:func:`PyEval_InitThreads`.
Victor Stinner84c4b192017-11-24 22:30:27 +010063
64
65.. _global-conf-vars:
66
67Global configuration variables
68==============================
69
70Python has variables for the global configuration to control different features
71and options. By default, these flags are controlled by :ref:`command line
72options <using-on-interface-options>`.
73
74When a flag is set by an option, the value of the flag is the number of times
75that the option was set. For example, ``-b`` sets :c:data:`Py_BytesWarningFlag`
76to 1 and ``-bb`` sets :c:data:`Py_BytesWarningFlag` to 2.
77
78.. c:var:: Py_BytesWarningFlag
79
80 Issue a warning when comparing :class:`bytes` or :class:`bytearray` with
81 :class:`str` or :class:`bytes` with :class:`int`. Issue an error if greater
82 or equal to ``2``.
83
84 Set by the :option:`-b` option.
85
86.. c:var:: Py_DebugFlag
87
88 Turn on parser debugging output (for expert only, depending on compilation
89 options).
90
91 Set by the :option:`-d` option and the :envvar:`PYTHONDEBUG` environment
92 variable.
93
94.. c:var:: Py_DontWriteBytecodeFlag
95
96 If set to non-zero, Python won't try to write ``.pyc`` files on the
97 import of source modules.
98
99 Set by the :option:`-B` option and the :envvar:`PYTHONDONTWRITEBYTECODE`
100 environment variable.
101
102.. c:var:: Py_FrozenFlag
103
104 Suppress error messages when calculating the module search path in
105 :c:func:`Py_GetPath`.
106
107 Private flag used by ``_freeze_importlib`` and ``frozenmain`` programs.
108
109.. c:var:: Py_HashRandomizationFlag
110
111 Set to ``1`` if the :envvar:`PYTHONHASHSEED` environment variable is set to
112 a non-empty string.
113
114 If the flag is non-zero, read the :envvar:`PYTHONHASHSEED` environment
115 variable to initialize the secret hash seed.
116
117.. c:var:: Py_IgnoreEnvironmentFlag
118
119 Ignore all :envvar:`PYTHON*` environment variables, e.g.
120 :envvar:`PYTHONPATH` and :envvar:`PYTHONHOME`, that might be set.
121
122 Set by the :option:`-E` and :option:`-I` options.
123
124.. c:var:: Py_InspectFlag
125
126 When a script is passed as first argument or the :option:`-c` option is used,
127 enter interactive mode after executing the script or the command, even when
128 :data:`sys.stdin` does not appear to be a terminal.
129
130 Set by the :option:`-i` option and the :envvar:`PYTHONINSPECT` environment
131 variable.
132
133.. c:var:: Py_InteractiveFlag
134
135 Set by the :option:`-i` option.
136
137.. c:var:: Py_IsolatedFlag
138
139 Run Python in isolated mode. In isolated mode :data:`sys.path` contains
140 neither the script's directory nor the user's site-packages directory.
141
142 Set by the :option:`-I` option.
143
144 .. versionadded:: 3.4
145
146.. c:var:: Py_LegacyWindowsFSEncodingFlag
147
148 If the flag is non-zero, use the ``mbcs`` encoding instead of the UTF-8
149 encoding for the filesystem encoding.
150
151 Set to ``1`` if the :envvar:`PYTHONLEGACYWINDOWSFSENCODING` environment
152 variable is set to a non-empty string.
153
154 See :pep:`529` for more details.
155
156 Availability: Windows.
157
158.. c:var:: Py_LegacyWindowsStdioFlag
159
160 If the flag is non-zero, use :class:`io.FileIO` instead of
161 :class:`WindowsConsoleIO` for :mod:`sys` standard streams.
162
163 Set to ``1`` if the :envvar:`PYTHONLEGACYWINDOWSSTDIO` environment
164 variable is set to a non-empty string.
165
166 See :pep:`528` for more details.
167
168 Availability: Windows.
169
170.. c:var:: Py_NoSiteFlag
171
172 Disable the import of the module :mod:`site` and the site-dependent
173 manipulations of :data:`sys.path` that it entails. Also disable these
174 manipulations if :mod:`site` is explicitly imported later (call
175 :func:`site.main` if you want them to be triggered).
176
177 Set by the :option:`-S` option.
178
179.. c:var:: Py_NoUserSiteDirectory
180
181 Don't add the :data:`user site-packages directory <site.USER_SITE>` to
182 :data:`sys.path`.
183
184 Set by the :option:`-s` and :option:`-I` options, and the
185 :envvar:`PYTHONNOUSERSITE` environment variable.
186
187.. c:var:: Py_OptimizeFlag
188
189 Set by the :option:`-O` option and the :envvar:`PYTHONOPTIMIZE` environment
190 variable.
191
192.. c:var:: Py_QuietFlag
193
194 Don't display the copyright and version messages even in interactive mode.
195
196 Set by the :option:`-q` option.
197
198 .. versionadded:: 3.2
199
200.. c:var:: Py_UnbufferedStdioFlag
201
202 Force the stdout and stderr streams to be unbuffered.
203
204 Set by the :option:`-u` option and the :envvar:`PYTHONUNBUFFERED`
205 environment variable.
206
207.. c:var:: Py_VerboseFlag
208
209 Print a message each time a module is initialized, showing the place
210 (filename or built-in module) from which it is loaded. If greater or equal
211 to ``2``, print a message for each file that is checked for when
212 searching for a module. Also provides information on module cleanup at exit.
213
214 Set by the :option:`-v` option and the :envvar:`PYTHONVERBOSE` environment
215 variable.
216
Georg Brandl116aa622007-08-15 14:28:22 +0000217
Antoine Pitrou8b50b832011-01-15 11:57:42 +0000218Initializing and finalizing the interpreter
219===========================================
220
221
Georg Brandl60203b42010-10-06 10:11:56 +0000222.. c:function:: void Py_Initialize()
Georg Brandl116aa622007-08-15 14:28:22 +0000223
224 .. index::
225 single: Py_SetProgramName()
226 single: PyEval_InitThreads()
Georg Brandl116aa622007-08-15 14:28:22 +0000227 single: modules (in module sys)
228 single: path (in module sys)
Georg Brandl1a3284e2007-12-02 09:40:06 +0000229 module: builtins
Georg Brandl116aa622007-08-15 14:28:22 +0000230 module: __main__
231 module: sys
232 triple: module; search; path
233 single: PySys_SetArgv()
Antoine Pitrouf978fac2010-05-21 17:25:34 +0000234 single: PySys_SetArgvEx()
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000235 single: Py_FinalizeEx()
Georg Brandl116aa622007-08-15 14:28:22 +0000236
Victor Stinner84c4b192017-11-24 22:30:27 +0100237 Initialize the Python interpreter. In an application embedding Python,
238 this should be called before using any other Python/C API functions; see
239 :ref:`Before Python Initialization <pre-init-safe>` for the few exceptions.
240
241 This initializes
Georg Brandl116aa622007-08-15 14:28:22 +0000242 the table of loaded modules (``sys.modules``), and creates the fundamental
Georg Brandl1a3284e2007-12-02 09:40:06 +0000243 modules :mod:`builtins`, :mod:`__main__` and :mod:`sys`. It also initializes
Georg Brandl116aa622007-08-15 14:28:22 +0000244 the module search path (``sys.path``). It does not set ``sys.argv``; use
Georg Brandl60203b42010-10-06 10:11:56 +0000245 :c:func:`PySys_SetArgvEx` for that. This is a no-op when called for a second time
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000246 (without calling :c:func:`Py_FinalizeEx` first). There is no return value; it is a
Georg Brandl116aa622007-08-15 14:28:22 +0000247 fatal error if the initialization fails.
248
Steve Dowerde02b082016-09-09 11:46:37 -0700249 .. note::
250 On Windows, changes the console mode from ``O_TEXT`` to ``O_BINARY``, which will
251 also affect non-Python uses of the console using the C Runtime.
252
Georg Brandl116aa622007-08-15 14:28:22 +0000253
Georg Brandl60203b42010-10-06 10:11:56 +0000254.. c:function:: void Py_InitializeEx(int initsigs)
Georg Brandl116aa622007-08-15 14:28:22 +0000255
Serhiy Storchaka1ecf7d22016-10-27 21:41:19 +0300256 This function works like :c:func:`Py_Initialize` if *initsigs* is ``1``. If
257 *initsigs* is ``0``, it skips initialization registration of signal handlers, which
Georg Brandl116aa622007-08-15 14:28:22 +0000258 might be useful when Python is embedded.
259
Georg Brandl116aa622007-08-15 14:28:22 +0000260
Georg Brandl60203b42010-10-06 10:11:56 +0000261.. c:function:: int Py_IsInitialized()
Georg Brandl116aa622007-08-15 14:28:22 +0000262
263 Return true (nonzero) when the Python interpreter has been initialized, false
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000264 (zero) if not. After :c:func:`Py_FinalizeEx` is called, this returns false until
Georg Brandl60203b42010-10-06 10:11:56 +0000265 :c:func:`Py_Initialize` is called again.
Georg Brandl116aa622007-08-15 14:28:22 +0000266
267
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000268.. c:function:: int Py_FinalizeEx()
Georg Brandl116aa622007-08-15 14:28:22 +0000269
Georg Brandl60203b42010-10-06 10:11:56 +0000270 Undo all initializations made by :c:func:`Py_Initialize` and subsequent use of
Georg Brandl116aa622007-08-15 14:28:22 +0000271 Python/C API functions, and destroy all sub-interpreters (see
Georg Brandl60203b42010-10-06 10:11:56 +0000272 :c:func:`Py_NewInterpreter` below) that were created and not yet destroyed since
273 the last call to :c:func:`Py_Initialize`. Ideally, this frees all memory
Georg Brandl116aa622007-08-15 14:28:22 +0000274 allocated by the Python interpreter. This is a no-op when called for a second
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000275 time (without calling :c:func:`Py_Initialize` again first). Normally the
276 return value is 0. If there were errors during finalization
277 (flushing buffered data), -1 is returned.
Georg Brandl116aa622007-08-15 14:28:22 +0000278
279 This function is provided for a number of reasons. An embedding application
280 might want to restart Python without having to restart the application itself.
281 An application that has loaded the Python interpreter from a dynamically
282 loadable library (or DLL) might want to free all memory allocated by Python
283 before unloading the DLL. During a hunt for memory leaks in an application a
284 developer might want to free all memory allocated by Python before exiting from
285 the application.
286
287 **Bugs and caveats:** The destruction of modules and objects in modules is done
288 in random order; this may cause destructors (:meth:`__del__` methods) to fail
289 when they depend on other objects (even functions) or modules. Dynamically
290 loaded extension modules loaded by Python are not unloaded. Small amounts of
291 memory allocated by the Python interpreter may not be freed (if you find a leak,
292 please report it). Memory tied up in circular references between objects is not
293 freed. Some memory allocated by extension modules may not be freed. Some
294 extensions may not work properly if their initialization routine is called more
Georg Brandl60203b42010-10-06 10:11:56 +0000295 than once; this can happen if an application calls :c:func:`Py_Initialize` and
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000296 :c:func:`Py_FinalizeEx` more than once.
297
298 .. versionadded:: 3.6
299
300
301.. c:function:: void Py_Finalize()
302
303 This is a backwards-compatible version of :c:func:`Py_FinalizeEx` that
304 disregards the return value.
Georg Brandl116aa622007-08-15 14:28:22 +0000305
306
Antoine Pitrou8b50b832011-01-15 11:57:42 +0000307Process-wide parameters
308=======================
Georg Brandl116aa622007-08-15 14:28:22 +0000309
310
Serhiy Storchaka03863d22015-06-21 17:11:21 +0300311.. c:function:: int Py_SetStandardStreamEncoding(const char *encoding, const char *errors)
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000312
313 .. index::
314 single: Py_Initialize()
315 single: main()
316 triple: stdin; stdout; sdterr
317
Nick Coghlan1805a622013-10-18 23:11:47 +1000318 This function should be called before :c:func:`Py_Initialize`, if it is
319 called at all. It specifies which encoding and error handling to use
320 with standard IO, with the same meanings as in :func:`str.encode`.
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000321
322 It overrides :envvar:`PYTHONIOENCODING` values, and allows embedding code
Nick Coghlan1805a622013-10-18 23:11:47 +1000323 to control IO encoding when the environment variable does not work.
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000324
325 ``encoding`` and/or ``errors`` may be NULL to use
326 :envvar:`PYTHONIOENCODING` and/or default values (depending on other
327 settings).
328
329 Note that :data:`sys.stderr` always uses the "backslashreplace" error
330 handler, regardless of this (or any other) setting.
331
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000332 If :c:func:`Py_FinalizeEx` is called, this function will need to be called
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000333 again in order to affect subsequent calls to :c:func:`Py_Initialize`.
334
Serhiy Storchaka1ecf7d22016-10-27 21:41:19 +0300335 Returns ``0`` if successful, a nonzero value on error (e.g. calling after the
Nick Coghlan1805a622013-10-18 23:11:47 +1000336 interpreter has already been initialized).
337
338 .. versionadded:: 3.4
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000339
340
Serhiy Storchaka4ae06c52017-12-12 13:55:04 +0200341.. c:function:: void Py_SetProgramName(const wchar_t *name)
Georg Brandl116aa622007-08-15 14:28:22 +0000342
343 .. index::
344 single: Py_Initialize()
345 single: main()
346 single: Py_GetPath()
347
Georg Brandl60203b42010-10-06 10:11:56 +0000348 This function should be called before :c:func:`Py_Initialize` is called for
Georg Brandl116aa622007-08-15 14:28:22 +0000349 the first time, if it is called at all. It tells the interpreter the value
Georg Brandl60203b42010-10-06 10:11:56 +0000350 of the ``argv[0]`` argument to the :c:func:`main` function of the program
Martin v. Löwis790465f2008-04-05 20:41:37 +0000351 (converted to wide characters).
Georg Brandl60203b42010-10-06 10:11:56 +0000352 This is used by :c:func:`Py_GetPath` and some other functions below to find
Georg Brandl116aa622007-08-15 14:28:22 +0000353 the Python run-time libraries relative to the interpreter executable. The
354 default value is ``'python'``. The argument should point to a
Martin v. Löwis790465f2008-04-05 20:41:37 +0000355 zero-terminated wide character string in static storage whose contents will not
Georg Brandl116aa622007-08-15 14:28:22 +0000356 change for the duration of the program's execution. No code in the Python
357 interpreter will change the contents of this storage.
358
Victor Stinner25e014b2014-08-01 12:28:49 +0200359 Use :c:func:`Py_DecodeLocale` to decode a bytes string to get a
360 :c:type:`wchar_*` string.
361
Georg Brandl116aa622007-08-15 14:28:22 +0000362
Georg Brandl60203b42010-10-06 10:11:56 +0000363.. c:function:: wchar* Py_GetProgramName()
Georg Brandl116aa622007-08-15 14:28:22 +0000364
365 .. index:: single: Py_SetProgramName()
366
Georg Brandl60203b42010-10-06 10:11:56 +0000367 Return the program name set with :c:func:`Py_SetProgramName`, or the default.
Georg Brandl116aa622007-08-15 14:28:22 +0000368 The returned string points into static storage; the caller should not modify its
369 value.
370
371
Georg Brandl60203b42010-10-06 10:11:56 +0000372.. c:function:: wchar_t* Py_GetPrefix()
Georg Brandl116aa622007-08-15 14:28:22 +0000373
374 Return the *prefix* for installed platform-independent files. This is derived
375 through a number of complicated rules from the program name set with
Georg Brandl60203b42010-10-06 10:11:56 +0000376 :c:func:`Py_SetProgramName` and some environment variables; for example, if the
Georg Brandl116aa622007-08-15 14:28:22 +0000377 program name is ``'/usr/local/bin/python'``, the prefix is ``'/usr/local'``. The
378 returned string points into static storage; the caller should not modify its
379 value. This corresponds to the :makevar:`prefix` variable in the top-level
Éric Araujo37b5f9e2011-09-01 03:19:30 +0200380 :file:`Makefile` and the ``--prefix`` argument to the :program:`configure`
Georg Brandl116aa622007-08-15 14:28:22 +0000381 script at build time. The value is available to Python code as ``sys.prefix``.
382 It is only useful on Unix. See also the next function.
383
384
Georg Brandl60203b42010-10-06 10:11:56 +0000385.. c:function:: wchar_t* Py_GetExecPrefix()
Georg Brandl116aa622007-08-15 14:28:22 +0000386
387 Return the *exec-prefix* for installed platform-*dependent* files. This is
388 derived through a number of complicated rules from the program name set with
Georg Brandl60203b42010-10-06 10:11:56 +0000389 :c:func:`Py_SetProgramName` and some environment variables; for example, if the
Georg Brandl116aa622007-08-15 14:28:22 +0000390 program name is ``'/usr/local/bin/python'``, the exec-prefix is
391 ``'/usr/local'``. The returned string points into static storage; the caller
392 should not modify its value. This corresponds to the :makevar:`exec_prefix`
Éric Araujo37b5f9e2011-09-01 03:19:30 +0200393 variable in the top-level :file:`Makefile` and the ``--exec-prefix``
Georg Brandl116aa622007-08-15 14:28:22 +0000394 argument to the :program:`configure` script at build time. The value is
395 available to Python code as ``sys.exec_prefix``. It is only useful on Unix.
396
397 Background: The exec-prefix differs from the prefix when platform dependent
398 files (such as executables and shared libraries) are installed in a different
399 directory tree. In a typical installation, platform dependent files may be
400 installed in the :file:`/usr/local/plat` subtree while platform independent may
401 be installed in :file:`/usr/local`.
402
403 Generally speaking, a platform is a combination of hardware and software
404 families, e.g. Sparc machines running the Solaris 2.x operating system are
405 considered the same platform, but Intel machines running Solaris 2.x are another
406 platform, and Intel machines running Linux are yet another platform. Different
407 major revisions of the same operating system generally also form different
408 platforms. Non-Unix operating systems are a different story; the installation
409 strategies on those systems are so different that the prefix and exec-prefix are
410 meaningless, and set to the empty string. Note that compiled Python bytecode
411 files are platform independent (but not independent from the Python version by
412 which they were compiled!).
413
414 System administrators will know how to configure the :program:`mount` or
415 :program:`automount` programs to share :file:`/usr/local` between platforms
416 while having :file:`/usr/local/plat` be a different filesystem for each
417 platform.
418
419
Georg Brandl60203b42010-10-06 10:11:56 +0000420.. c:function:: wchar_t* Py_GetProgramFullPath()
Georg Brandl116aa622007-08-15 14:28:22 +0000421
422 .. index::
423 single: Py_SetProgramName()
424 single: executable (in module sys)
425
426 Return the full program name of the Python executable; this is computed as a
427 side-effect of deriving the default module search path from the program name
Georg Brandl60203b42010-10-06 10:11:56 +0000428 (set by :c:func:`Py_SetProgramName` above). The returned string points into
Georg Brandl116aa622007-08-15 14:28:22 +0000429 static storage; the caller should not modify its value. The value is available
430 to Python code as ``sys.executable``.
431
432
Georg Brandl60203b42010-10-06 10:11:56 +0000433.. c:function:: wchar_t* Py_GetPath()
Georg Brandl116aa622007-08-15 14:28:22 +0000434
435 .. index::
436 triple: module; search; path
437 single: path (in module sys)
Kristján Valur Jónsson3b69db22010-09-27 05:32:54 +0000438 single: Py_SetPath()
Georg Brandl116aa622007-08-15 14:28:22 +0000439
Benjamin Peterson46a99002010-01-09 18:45:30 +0000440 Return the default module search path; this is computed from the program name
Georg Brandl60203b42010-10-06 10:11:56 +0000441 (set by :c:func:`Py_SetProgramName` above) and some environment variables.
Benjamin Peterson46a99002010-01-09 18:45:30 +0000442 The returned string consists of a series of directory names separated by a
443 platform dependent delimiter character. The delimiter character is ``':'``
444 on Unix and Mac OS X, ``';'`` on Windows. The returned string points into
445 static storage; the caller should not modify its value. The list
446 :data:`sys.path` is initialized with this value on interpreter startup; it
447 can be (and usually is) modified later to change the search path for loading
448 modules.
Georg Brandl116aa622007-08-15 14:28:22 +0000449
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000450 .. XXX should give the exact rules
Georg Brandl116aa622007-08-15 14:28:22 +0000451
452
Georg Brandl60203b42010-10-06 10:11:56 +0000453.. c:function:: void Py_SetPath(const wchar_t *)
Kristján Valur Jónsson3b69db22010-09-27 05:32:54 +0000454
455 .. index::
456 triple: module; search; path
457 single: path (in module sys)
458 single: Py_GetPath()
459
460 Set the default module search path. If this function is called before
Georg Brandlfa4f7f92010-10-06 10:14:08 +0000461 :c:func:`Py_Initialize`, then :c:func:`Py_GetPath` won't attempt to compute a
462 default search path but uses the one provided instead. This is useful if
463 Python is embedded by an application that has full knowledge of the location
Georg Brandle8ea3552014-10-11 14:36:02 +0200464 of all modules. The path components should be separated by the platform
465 dependent delimiter character, which is ``':'`` on Unix and Mac OS X, ``';'``
466 on Windows.
Kristján Valur Jónsson3b69db22010-09-27 05:32:54 +0000467
Georg Brandlfa4f7f92010-10-06 10:14:08 +0000468 This also causes :data:`sys.executable` to be set only to the raw program
469 name (see :c:func:`Py_SetProgramName`) and for :data:`sys.prefix` and
470 :data:`sys.exec_prefix` to be empty. It is up to the caller to modify these
471 if required after calling :c:func:`Py_Initialize`.
472
Victor Stinner25e014b2014-08-01 12:28:49 +0200473 Use :c:func:`Py_DecodeLocale` to decode a bytes string to get a
474 :c:type:`wchar_*` string.
475
Benjamin Petersonb33bb892014-12-24 10:49:11 -0600476 The path argument is copied internally, so the caller may free it after the
477 call completes.
478
Kristján Valur Jónsson3b69db22010-09-27 05:32:54 +0000479
Georg Brandl60203b42010-10-06 10:11:56 +0000480.. c:function:: const char* Py_GetVersion()
Georg Brandl116aa622007-08-15 14:28:22 +0000481
482 Return the version of this Python interpreter. This is a string that looks
483 something like ::
484
Georg Brandle6bcc912008-05-12 18:05:20 +0000485 "3.0a5+ (py3k:63103M, May 12 2008, 00:53:55) \n[GCC 4.2.3]"
Georg Brandl116aa622007-08-15 14:28:22 +0000486
487 .. index:: single: version (in module sys)
488
489 The first word (up to the first space character) is the current Python version;
490 the first three characters are the major and minor version separated by a
491 period. The returned string points into static storage; the caller should not
Georg Brandle6bcc912008-05-12 18:05:20 +0000492 modify its value. The value is available to Python code as :data:`sys.version`.
Georg Brandl116aa622007-08-15 14:28:22 +0000493
494
Georg Brandl60203b42010-10-06 10:11:56 +0000495.. c:function:: const char* Py_GetPlatform()
Georg Brandl116aa622007-08-15 14:28:22 +0000496
497 .. index:: single: platform (in module sys)
498
499 Return the platform identifier for the current platform. On Unix, this is
500 formed from the "official" name of the operating system, converted to lower
501 case, followed by the major revision number; e.g., for Solaris 2.x, which is
502 also known as SunOS 5.x, the value is ``'sunos5'``. On Mac OS X, it is
503 ``'darwin'``. On Windows, it is ``'win'``. The returned string points into
504 static storage; the caller should not modify its value. The value is available
505 to Python code as ``sys.platform``.
506
507
Georg Brandl60203b42010-10-06 10:11:56 +0000508.. c:function:: const char* Py_GetCopyright()
Georg Brandl116aa622007-08-15 14:28:22 +0000509
510 Return the official copyright string for the current Python version, for example
511
512 ``'Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam'``
513
514 .. index:: single: copyright (in module sys)
515
516 The returned string points into static storage; the caller should not modify its
517 value. The value is available to Python code as ``sys.copyright``.
518
519
Georg Brandl60203b42010-10-06 10:11:56 +0000520.. c:function:: const char* Py_GetCompiler()
Georg Brandl116aa622007-08-15 14:28:22 +0000521
522 Return an indication of the compiler used to build the current Python version,
523 in square brackets, for example::
524
525 "[GCC 2.7.2.2]"
526
527 .. index:: single: version (in module sys)
528
529 The returned string points into static storage; the caller should not modify its
530 value. The value is available to Python code as part of the variable
531 ``sys.version``.
532
533
Georg Brandl60203b42010-10-06 10:11:56 +0000534.. c:function:: const char* Py_GetBuildInfo()
Georg Brandl116aa622007-08-15 14:28:22 +0000535
536 Return information about the sequence number and build date and time of the
537 current Python interpreter instance, for example ::
538
539 "#67, Aug 1 1997, 22:34:28"
540
541 .. index:: single: version (in module sys)
542
543 The returned string points into static storage; the caller should not modify its
544 value. The value is available to Python code as part of the variable
545 ``sys.version``.
546
547
Georg Brandl60203b42010-10-06 10:11:56 +0000548.. c:function:: void PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
Georg Brandl116aa622007-08-15 14:28:22 +0000549
550 .. index::
551 single: main()
552 single: Py_FatalError()
553 single: argv (in module sys)
554
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000555 Set :data:`sys.argv` based on *argc* and *argv*. These parameters are
Georg Brandl60203b42010-10-06 10:11:56 +0000556 similar to those passed to the program's :c:func:`main` function with the
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000557 difference that the first entry should refer to the script file to be
558 executed rather than the executable hosting the Python interpreter. If there
559 isn't a script that will be run, the first entry in *argv* can be an empty
560 string. If this function fails to initialize :data:`sys.argv`, a fatal
Georg Brandl60203b42010-10-06 10:11:56 +0000561 condition is signalled using :c:func:`Py_FatalError`.
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000562
Antoine Pitrouf978fac2010-05-21 17:25:34 +0000563 If *updatepath* is zero, this is all the function does. If *updatepath*
564 is non-zero, the function also modifies :data:`sys.path` according to the
565 following algorithm:
566
567 - If the name of an existing script is passed in ``argv[0]``, the absolute
568 path of the directory where the script is located is prepended to
569 :data:`sys.path`.
Serhiy Storchaka1ecf7d22016-10-27 21:41:19 +0300570 - Otherwise (that is, if *argc* is ``0`` or ``argv[0]`` doesn't point
Antoine Pitrouf978fac2010-05-21 17:25:34 +0000571 to an existing file name), an empty string is prepended to
572 :data:`sys.path`, which is the same as prepending the current working
573 directory (``"."``).
574
Victor Stinner25e014b2014-08-01 12:28:49 +0200575 Use :c:func:`Py_DecodeLocale` to decode a bytes string to get a
576 :c:type:`wchar_*` string.
577
Antoine Pitrouf978fac2010-05-21 17:25:34 +0000578 .. note::
579 It is recommended that applications embedding the Python interpreter
Serhiy Storchaka1ecf7d22016-10-27 21:41:19 +0300580 for purposes other than executing a single script pass ``0`` as *updatepath*,
Antoine Pitrouf978fac2010-05-21 17:25:34 +0000581 and update :data:`sys.path` themselves if desired.
Serhiy Storchaka6dff0202016-05-07 10:49:07 +0300582 See `CVE-2008-5983 <https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-5983>`_.
Antoine Pitrouf978fac2010-05-21 17:25:34 +0000583
584 On versions before 3.1.3, you can achieve the same effect by manually
585 popping the first :data:`sys.path` element after having called
Georg Brandl60203b42010-10-06 10:11:56 +0000586 :c:func:`PySys_SetArgv`, for example using::
Antoine Pitrouf978fac2010-05-21 17:25:34 +0000587
588 PyRun_SimpleString("import sys; sys.path.pop(0)\n");
589
590 .. versionadded:: 3.1.3
Georg Brandl116aa622007-08-15 14:28:22 +0000591
Serhiy Storchaka1ecf7d22016-10-27 21:41:19 +0300592 .. XXX impl. doesn't seem consistent in allowing ``0``/``NULL`` for the params;
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000593 check w/ Guido.
Georg Brandl116aa622007-08-15 14:28:22 +0000594
Georg Brandl116aa622007-08-15 14:28:22 +0000595
Georg Brandl60203b42010-10-06 10:11:56 +0000596.. c:function:: void PySys_SetArgv(int argc, wchar_t **argv)
Antoine Pitrouf978fac2010-05-21 17:25:34 +0000597
Christian Heimesad73a9c2013-08-10 16:36:18 +0200598 This function works like :c:func:`PySys_SetArgvEx` with *updatepath* set
Serhiy Storchaka1ecf7d22016-10-27 21:41:19 +0300599 to ``1`` unless the :program:`python` interpreter was started with the
Christian Heimesad73a9c2013-08-10 16:36:18 +0200600 :option:`-I`.
601
Victor Stinner25e014b2014-08-01 12:28:49 +0200602 Use :c:func:`Py_DecodeLocale` to decode a bytes string to get a
603 :c:type:`wchar_*` string.
604
Christian Heimesad73a9c2013-08-10 16:36:18 +0200605 .. versionchanged:: 3.4 The *updatepath* value depends on :option:`-I`.
Antoine Pitrouf978fac2010-05-21 17:25:34 +0000606
607
Serhiy Storchaka4ae06c52017-12-12 13:55:04 +0200608.. c:function:: void Py_SetPythonHome(const wchar_t *home)
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000609
610 Set the default "home" directory, that is, the location of the standard
Georg Brandlde0ab5e2010-12-02 18:02:01 +0000611 Python libraries. See :envvar:`PYTHONHOME` for the meaning of the
612 argument string.
613
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000614 The argument should point to a zero-terminated character string in static
615 storage whose contents will not change for the duration of the program's
616 execution. No code in the Python interpreter will change the contents of
617 this storage.
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000618
Victor Stinner25e014b2014-08-01 12:28:49 +0200619 Use :c:func:`Py_DecodeLocale` to decode a bytes string to get a
620 :c:type:`wchar_*` string.
621
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000622
Georg Brandl60203b42010-10-06 10:11:56 +0000623.. c:function:: w_char* Py_GetPythonHome()
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000624
625 Return the default "home", that is, the value set by a previous call to
Georg Brandl60203b42010-10-06 10:11:56 +0000626 :c:func:`Py_SetPythonHome`, or the value of the :envvar:`PYTHONHOME`
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000627 environment variable if it is set.
628
629
Georg Brandl116aa622007-08-15 14:28:22 +0000630.. _threads:
631
632Thread State and the Global Interpreter Lock
633============================================
634
635.. index::
636 single: global interpreter lock
637 single: interpreter lock
638 single: lock, interpreter
639
Georg Brandlf285bcc2010-10-19 21:07:16 +0000640The Python interpreter is not fully thread-safe. In order to support
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000641multi-threaded Python programs, there's a global lock, called the :term:`global
642interpreter lock` or :term:`GIL`, that must be held by the current thread before
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000643it can safely access Python objects. Without the lock, even the simplest
644operations could cause problems in a multi-threaded program: for example, when
645two threads simultaneously increment the reference count of the same object, the
646reference count could end up being incremented only once instead of twice.
Georg Brandl116aa622007-08-15 14:28:22 +0000647
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000648.. index:: single: setswitchinterval() (in module sys)
Georg Brandl116aa622007-08-15 14:28:22 +0000649
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000650Therefore, the rule exists that only the thread that has acquired the
651:term:`GIL` may operate on Python objects or call Python/C API functions.
652In order to emulate concurrency of execution, the interpreter regularly
653tries to switch threads (see :func:`sys.setswitchinterval`). The lock is also
654released around potentially blocking I/O operations like reading or writing
655a file, so that other Python threads can run in the meantime.
Georg Brandl116aa622007-08-15 14:28:22 +0000656
657.. index::
658 single: PyThreadState
659 single: PyThreadState
660
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000661The Python interpreter keeps some thread-specific bookkeeping information
662inside a data structure called :c:type:`PyThreadState`. There's also one
663global variable pointing to the current :c:type:`PyThreadState`: it can
664be retrieved using :c:func:`PyThreadState_Get`.
Georg Brandl116aa622007-08-15 14:28:22 +0000665
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000666Releasing the GIL from extension code
667-------------------------------------
668
669Most extension code manipulating the :term:`GIL` has the following simple
670structure::
Georg Brandl116aa622007-08-15 14:28:22 +0000671
672 Save the thread state in a local variable.
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000673 Release the global interpreter lock.
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000674 ... Do some blocking I/O operation ...
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000675 Reacquire the global interpreter lock.
Georg Brandl116aa622007-08-15 14:28:22 +0000676 Restore the thread state from the local variable.
677
678This is so common that a pair of macros exists to simplify it::
679
680 Py_BEGIN_ALLOW_THREADS
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000681 ... Do some blocking I/O operation ...
Georg Brandl116aa622007-08-15 14:28:22 +0000682 Py_END_ALLOW_THREADS
683
684.. index::
685 single: Py_BEGIN_ALLOW_THREADS
686 single: Py_END_ALLOW_THREADS
687
Georg Brandl60203b42010-10-06 10:11:56 +0000688The :c:macro:`Py_BEGIN_ALLOW_THREADS` macro opens a new block and declares a
689hidden local variable; the :c:macro:`Py_END_ALLOW_THREADS` macro closes the
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000690block. These two macros are still available when Python is compiled without
691thread support (they simply have an empty expansion).
Georg Brandl116aa622007-08-15 14:28:22 +0000692
693When thread support is enabled, the block above expands to the following code::
694
695 PyThreadState *_save;
696
697 _save = PyEval_SaveThread();
698 ...Do some blocking I/O operation...
699 PyEval_RestoreThread(_save);
700
Georg Brandl116aa622007-08-15 14:28:22 +0000701.. index::
702 single: PyEval_RestoreThread()
Georg Brandl116aa622007-08-15 14:28:22 +0000703 single: PyEval_SaveThread()
Georg Brandl116aa622007-08-15 14:28:22 +0000704
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000705Here is how these functions work: the global interpreter lock is used to protect the pointer to the
706current thread state. When releasing the lock and saving the thread state,
707the current thread state pointer must be retrieved before the lock is released
708(since another thread could immediately acquire the lock and store its own thread
709state in the global variable). Conversely, when acquiring the lock and restoring
710the thread state, the lock must be acquired before storing the thread state
711pointer.
Georg Brandl116aa622007-08-15 14:28:22 +0000712
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000713.. note::
714 Calling system I/O functions is the most common use case for releasing
715 the GIL, but it can also be useful before calling long-running computations
716 which don't need access to Python objects, such as compression or
717 cryptographic functions operating over memory buffers. For example, the
718 standard :mod:`zlib` and :mod:`hashlib` modules release the GIL when
719 compressing or hashing data.
Georg Brandl116aa622007-08-15 14:28:22 +0000720
Antoine Pitrou1a67bee2013-09-30 21:35:44 +0200721
722.. _gilstate:
723
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000724Non-Python created threads
725--------------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000726
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000727When threads are created using the dedicated Python APIs (such as the
728:mod:`threading` module), a thread state is automatically associated to them
729and the code showed above is therefore correct. However, when threads are
730created from C (for example by a third-party library with its own thread
731management), they don't hold the GIL, nor is there a thread state structure
732for them.
733
734If you need to call Python code from these threads (often this will be part
735of a callback API provided by the aforementioned third-party library),
736you must first register these threads with the interpreter by
737creating a thread state data structure, then acquiring the GIL, and finally
738storing their thread state pointer, before you can start using the Python/C
739API. When you are done, you should reset the thread state pointer, release
740the GIL, and finally free the thread state data structure.
741
742The :c:func:`PyGILState_Ensure` and :c:func:`PyGILState_Release` functions do
743all of the above automatically. The typical idiom for calling into Python
744from a C thread is::
Georg Brandl116aa622007-08-15 14:28:22 +0000745
746 PyGILState_STATE gstate;
747 gstate = PyGILState_Ensure();
748
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000749 /* Perform Python actions here. */
Georg Brandl116aa622007-08-15 14:28:22 +0000750 result = CallSomeFunction();
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000751 /* evaluate result or handle exception */
Georg Brandl116aa622007-08-15 14:28:22 +0000752
753 /* Release the thread. No Python API allowed beyond this point. */
754 PyGILState_Release(gstate);
755
Georg Brandl60203b42010-10-06 10:11:56 +0000756Note that the :c:func:`PyGILState_\*` functions assume there is only one global
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000757interpreter (created automatically by :c:func:`Py_Initialize`). Python
Georg Brandl116aa622007-08-15 14:28:22 +0000758supports the creation of additional interpreters (using
Georg Brandl60203b42010-10-06 10:11:56 +0000759:c:func:`Py_NewInterpreter`), but mixing multiple interpreters and the
760:c:func:`PyGILState_\*` API is unsupported.
Georg Brandl116aa622007-08-15 14:28:22 +0000761
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000762Another important thing to note about threads is their behaviour in the face
Georg Brandl60203b42010-10-06 10:11:56 +0000763of the C :c:func:`fork` call. On most systems with :c:func:`fork`, after a
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000764process forks only the thread that issued the fork will exist. That also
765means any locks held by other threads will never be released. Python solves
766this for :func:`os.fork` by acquiring the locks it uses internally before
767the fork, and releasing them afterwards. In addition, it resets any
768:ref:`lock-objects` in the child. When extending or embedding Python, there
769is no way to inform Python of additional (non-Python) locks that need to be
770acquired before or reset after a fork. OS facilities such as
Ezio Melotti861d27f2011-04-20 21:32:40 +0300771:c:func:`pthread_atfork` would need to be used to accomplish the same thing.
Georg Brandl60203b42010-10-06 10:11:56 +0000772Additionally, when extending or embedding Python, calling :c:func:`fork`
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000773directly rather than through :func:`os.fork` (and returning to or calling
774into Python) may result in a deadlock by one of Python's internal locks
775being held by a thread that is defunct after the fork.
Antoine Pitrouf7ecfac2017-05-28 11:35:14 +0200776:c:func:`PyOS_AfterFork_Child` tries to reset the necessary locks, but is not
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000777always able to.
Georg Brandl116aa622007-08-15 14:28:22 +0000778
Antoine Pitrou8b50b832011-01-15 11:57:42 +0000779
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000780High-level API
781--------------
782
783These are the most commonly used types and functions when writing C extension
784code, or when embedding the Python interpreter:
785
Georg Brandl60203b42010-10-06 10:11:56 +0000786.. c:type:: PyInterpreterState
Georg Brandl116aa622007-08-15 14:28:22 +0000787
788 This data structure represents the state shared by a number of cooperating
789 threads. Threads belonging to the same interpreter share their module
790 administration and a few other internal items. There are no public members in
791 this structure.
792
793 Threads belonging to different interpreters initially share nothing, except
794 process state like available memory, open file descriptors and such. The global
795 interpreter lock is also shared by all threads, regardless of to which
796 interpreter they belong.
797
798
Georg Brandl60203b42010-10-06 10:11:56 +0000799.. c:type:: PyThreadState
Georg Brandl116aa622007-08-15 14:28:22 +0000800
801 This data structure represents the state of a single thread. The only public
Georg Brandl60203b42010-10-06 10:11:56 +0000802 data member is :c:type:`PyInterpreterState \*`:attr:`interp`, which points to
Georg Brandl116aa622007-08-15 14:28:22 +0000803 this thread's interpreter state.
804
805
Georg Brandl60203b42010-10-06 10:11:56 +0000806.. c:function:: void PyEval_InitThreads()
Georg Brandl116aa622007-08-15 14:28:22 +0000807
808 .. index::
Antoine Pitrouf5cf4352011-01-15 14:31:49 +0000809 single: PyEval_AcquireThread()
Georg Brandl116aa622007-08-15 14:28:22 +0000810 single: PyEval_ReleaseThread()
811 single: PyEval_SaveThread()
812 single: PyEval_RestoreThread()
813
814 Initialize and acquire the global interpreter lock. It should be called in the
815 main thread before creating a second thread or engaging in any other thread
Antoine Pitrouf5cf4352011-01-15 14:31:49 +0000816 operations such as ``PyEval_ReleaseThread(tstate)``. It is not needed before
817 calling :c:func:`PyEval_SaveThread` or :c:func:`PyEval_RestoreThread`.
Georg Brandl116aa622007-08-15 14:28:22 +0000818
Antoine Pitrou9bd3bbc2011-03-13 23:28:28 +0100819 This is a no-op when called for a second time.
Georg Brandl116aa622007-08-15 14:28:22 +0000820
Antoine Pitrou9bb98772011-03-15 20:22:50 +0100821 .. versionchanged:: 3.2
822 This function cannot be called before :c:func:`Py_Initialize()` anymore.
823
Georg Brandl2067bfd2008-05-25 13:05:15 +0000824 .. index:: module: _thread
Georg Brandl116aa622007-08-15 14:28:22 +0000825
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000826 .. note::
Éric Araujofa5e6e42014-03-12 19:51:00 -0400827
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000828 When only the main thread exists, no GIL operations are needed. This is a
829 common situation (most Python programs do not use threads), and the lock
830 operations slow the interpreter down a bit. Therefore, the lock is not
831 created initially. This situation is equivalent to having acquired the lock:
832 when there is only a single thread, all object accesses are safe. Therefore,
833 when this function initializes the global interpreter lock, it also acquires
834 it. Before the Python :mod:`_thread` module creates a new thread, knowing
835 that either it has the lock or the lock hasn't been created yet, it calls
836 :c:func:`PyEval_InitThreads`. When this call returns, it is guaranteed that
837 the lock has been created and that the calling thread has acquired it.
Georg Brandl116aa622007-08-15 14:28:22 +0000838
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000839 It is **not** safe to call this function when it is unknown which thread (if
840 any) currently has the global interpreter lock.
Georg Brandl116aa622007-08-15 14:28:22 +0000841
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000842 This function is not available when thread support is disabled at compile time.
Georg Brandl116aa622007-08-15 14:28:22 +0000843
844
Georg Brandl60203b42010-10-06 10:11:56 +0000845.. c:function:: int PyEval_ThreadsInitialized()
Georg Brandl116aa622007-08-15 14:28:22 +0000846
Georg Brandl60203b42010-10-06 10:11:56 +0000847 Returns a non-zero value if :c:func:`PyEval_InitThreads` has been called. This
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000848 function can be called without holding the GIL, and therefore can be used to
Georg Brandl116aa622007-08-15 14:28:22 +0000849 avoid calls to the locking API when running single-threaded. This function is
850 not available when thread support is disabled at compile time.
851
Georg Brandl116aa622007-08-15 14:28:22 +0000852
Georg Brandl60203b42010-10-06 10:11:56 +0000853.. c:function:: PyThreadState* PyEval_SaveThread()
Georg Brandl116aa622007-08-15 14:28:22 +0000854
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000855 Release the global interpreter lock (if it has been created and thread
856 support is enabled) and reset the thread state to *NULL*, returning the
857 previous thread state (which is not *NULL*). If the lock has been created,
858 the current thread must have acquired it. (This function is available even
859 when thread support is disabled at compile time.)
Georg Brandl116aa622007-08-15 14:28:22 +0000860
861
Georg Brandl60203b42010-10-06 10:11:56 +0000862.. c:function:: void PyEval_RestoreThread(PyThreadState *tstate)
Georg Brandl116aa622007-08-15 14:28:22 +0000863
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000864 Acquire the global interpreter lock (if it has been created and thread
865 support is enabled) and set the thread state to *tstate*, which must not be
866 *NULL*. If the lock has been created, the current thread must not have
867 acquired it, otherwise deadlock ensues. (This function is available even
868 when thread support is disabled at compile time.)
Georg Brandl116aa622007-08-15 14:28:22 +0000869
Christian Heimesd8654cf2007-12-02 15:22:16 +0000870
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000871.. c:function:: PyThreadState* PyThreadState_Get()
872
873 Return the current thread state. The global interpreter lock must be held.
874 When the current thread state is *NULL*, this issues a fatal error (so that
875 the caller needn't check for *NULL*).
876
877
878.. c:function:: PyThreadState* PyThreadState_Swap(PyThreadState *tstate)
879
880 Swap the current thread state with the thread state given by the argument
881 *tstate*, which may be *NULL*. The global interpreter lock must be held
882 and is not released.
883
884
Georg Brandl60203b42010-10-06 10:11:56 +0000885.. c:function:: void PyEval_ReInitThreads()
Christian Heimesd8654cf2007-12-02 15:22:16 +0000886
Antoine Pitrouf7ecfac2017-05-28 11:35:14 +0200887 This function is called from :c:func:`PyOS_AfterFork_Child` to ensure
888 that newly created child processes don't hold locks referring to threads
889 which are not running in the child process.
Christian Heimesd8654cf2007-12-02 15:22:16 +0000890
891
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000892The following functions use thread-local storage, and are not compatible
893with sub-interpreters:
894
895.. c:function:: PyGILState_STATE PyGILState_Ensure()
896
897 Ensure that the current thread is ready to call the Python C API regardless
898 of the current state of Python, or of the global interpreter lock. This may
899 be called as many times as desired by a thread as long as each call is
900 matched with a call to :c:func:`PyGILState_Release`. In general, other
901 thread-related APIs may be used between :c:func:`PyGILState_Ensure` and
902 :c:func:`PyGILState_Release` calls as long as the thread state is restored to
903 its previous state before the Release(). For example, normal usage of the
904 :c:macro:`Py_BEGIN_ALLOW_THREADS` and :c:macro:`Py_END_ALLOW_THREADS` macros is
905 acceptable.
906
907 The return value is an opaque "handle" to the thread state when
908 :c:func:`PyGILState_Ensure` was called, and must be passed to
909 :c:func:`PyGILState_Release` to ensure Python is left in the same state. Even
910 though recursive calls are allowed, these handles *cannot* be shared - each
911 unique call to :c:func:`PyGILState_Ensure` must save the handle for its call
912 to :c:func:`PyGILState_Release`.
913
914 When the function returns, the current thread will hold the GIL and be able
915 to call arbitrary Python code. Failure is a fatal error.
916
917
918.. c:function:: void PyGILState_Release(PyGILState_STATE)
919
920 Release any resources previously acquired. After this call, Python's state will
921 be the same as it was prior to the corresponding :c:func:`PyGILState_Ensure` call
922 (but generally this state will be unknown to the caller, hence the use of the
923 GILState API).
924
925 Every call to :c:func:`PyGILState_Ensure` must be matched by a call to
926 :c:func:`PyGILState_Release` on the same thread.
927
928
Eli Bendersky08131682012-06-03 08:07:47 +0300929.. c:function:: PyThreadState* PyGILState_GetThisThreadState()
Sandro Tosi61baee02011-08-08 00:16:54 +0200930
931 Get the current thread state for this thread. May return ``NULL`` if no
932 GILState API has been used on the current thread. Note that the main thread
933 always has such a thread-state, even if no auto-thread-state call has been
934 made on the main thread. This is mainly a helper/diagnostic function.
935
936
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -0700937.. c:function:: int PyGILState_Check()
938
Serhiy Storchaka1ecf7d22016-10-27 21:41:19 +0300939 Return ``1`` if the current thread is holding the GIL and ``0`` otherwise.
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -0700940 This function can be called from any thread at any time.
941 Only if it has had its Python thread state initialized and currently is
Serhiy Storchaka1ecf7d22016-10-27 21:41:19 +0300942 holding the GIL will it return ``1``.
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -0700943 This is mainly a helper/diagnostic function. It can be useful
944 for example in callback contexts or memory allocation functions when
945 knowing that the GIL is locked can allow the caller to perform sensitive
946 actions or otherwise behave differently.
947
Kristján Valur Jónsson34870c42013-03-23 03:56:16 -0700948 .. versionadded:: 3.4
949
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -0700950
Georg Brandl116aa622007-08-15 14:28:22 +0000951The following macros are normally used without a trailing semicolon; look for
952example usage in the Python source distribution.
953
954
Georg Brandl60203b42010-10-06 10:11:56 +0000955.. c:macro:: Py_BEGIN_ALLOW_THREADS
Georg Brandl116aa622007-08-15 14:28:22 +0000956
957 This macro expands to ``{ PyThreadState *_save; _save = PyEval_SaveThread();``.
958 Note that it contains an opening brace; it must be matched with a following
Georg Brandl60203b42010-10-06 10:11:56 +0000959 :c:macro:`Py_END_ALLOW_THREADS` macro. See above for further discussion of this
Georg Brandl116aa622007-08-15 14:28:22 +0000960 macro. It is a no-op when thread support is disabled at compile time.
961
962
Georg Brandl60203b42010-10-06 10:11:56 +0000963.. c:macro:: Py_END_ALLOW_THREADS
Georg Brandl116aa622007-08-15 14:28:22 +0000964
965 This macro expands to ``PyEval_RestoreThread(_save); }``. Note that it contains
966 a closing brace; it must be matched with an earlier
Georg Brandl60203b42010-10-06 10:11:56 +0000967 :c:macro:`Py_BEGIN_ALLOW_THREADS` macro. See above for further discussion of
Georg Brandl116aa622007-08-15 14:28:22 +0000968 this macro. It is a no-op when thread support is disabled at compile time.
969
970
Georg Brandl60203b42010-10-06 10:11:56 +0000971.. c:macro:: Py_BLOCK_THREADS
Georg Brandl116aa622007-08-15 14:28:22 +0000972
973 This macro expands to ``PyEval_RestoreThread(_save);``: it is equivalent to
Georg Brandl60203b42010-10-06 10:11:56 +0000974 :c:macro:`Py_END_ALLOW_THREADS` without the closing brace. It is a no-op when
Georg Brandl116aa622007-08-15 14:28:22 +0000975 thread support is disabled at compile time.
976
977
Georg Brandl60203b42010-10-06 10:11:56 +0000978.. c:macro:: Py_UNBLOCK_THREADS
Georg Brandl116aa622007-08-15 14:28:22 +0000979
980 This macro expands to ``_save = PyEval_SaveThread();``: it is equivalent to
Georg Brandl60203b42010-10-06 10:11:56 +0000981 :c:macro:`Py_BEGIN_ALLOW_THREADS` without the opening brace and variable
Georg Brandl116aa622007-08-15 14:28:22 +0000982 declaration. It is a no-op when thread support is disabled at compile time.
983
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000984
985Low-level API
986-------------
987
Georg Brandl116aa622007-08-15 14:28:22 +0000988All of the following functions are only available when thread support is enabled
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000989at compile time, and must be called only when the global interpreter lock has
990been created.
Georg Brandl116aa622007-08-15 14:28:22 +0000991
992
Georg Brandl60203b42010-10-06 10:11:56 +0000993.. c:function:: PyInterpreterState* PyInterpreterState_New()
Georg Brandl116aa622007-08-15 14:28:22 +0000994
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000995 Create a new interpreter state object. The global interpreter lock need not
996 be held, but may be held if it is necessary to serialize calls to this
997 function.
Georg Brandl116aa622007-08-15 14:28:22 +0000998
999
Georg Brandl60203b42010-10-06 10:11:56 +00001000.. c:function:: void PyInterpreterState_Clear(PyInterpreterState *interp)
Georg Brandl116aa622007-08-15 14:28:22 +00001001
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001002 Reset all information in an interpreter state object. The global interpreter
1003 lock must be held.
Georg Brandl116aa622007-08-15 14:28:22 +00001004
1005
Georg Brandl60203b42010-10-06 10:11:56 +00001006.. c:function:: void PyInterpreterState_Delete(PyInterpreterState *interp)
Georg Brandl116aa622007-08-15 14:28:22 +00001007
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001008 Destroy an interpreter state object. The global interpreter lock need not be
1009 held. The interpreter state must have been reset with a previous call to
Georg Brandl60203b42010-10-06 10:11:56 +00001010 :c:func:`PyInterpreterState_Clear`.
Georg Brandl116aa622007-08-15 14:28:22 +00001011
1012
Georg Brandl60203b42010-10-06 10:11:56 +00001013.. c:function:: PyThreadState* PyThreadState_New(PyInterpreterState *interp)
Georg Brandl116aa622007-08-15 14:28:22 +00001014
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001015 Create a new thread state object belonging to the given interpreter object.
1016 The global interpreter lock need not be held, but may be held if it is
1017 necessary to serialize calls to this function.
Georg Brandl116aa622007-08-15 14:28:22 +00001018
1019
Georg Brandl60203b42010-10-06 10:11:56 +00001020.. c:function:: void PyThreadState_Clear(PyThreadState *tstate)
Georg Brandl116aa622007-08-15 14:28:22 +00001021
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001022 Reset all information in a thread state object. The global interpreter lock
1023 must be held.
Georg Brandl116aa622007-08-15 14:28:22 +00001024
1025
Georg Brandl60203b42010-10-06 10:11:56 +00001026.. c:function:: void PyThreadState_Delete(PyThreadState *tstate)
Georg Brandl116aa622007-08-15 14:28:22 +00001027
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001028 Destroy a thread state object. The global interpreter lock need not be held.
1029 The thread state must have been reset with a previous call to
Georg Brandl60203b42010-10-06 10:11:56 +00001030 :c:func:`PyThreadState_Clear`.
Georg Brandl116aa622007-08-15 14:28:22 +00001031
1032
Eric Snowe3774162017-05-22 19:46:40 -07001033.. c:function:: PY_INT64_T PyInterpreterState_GetID(PyInterpreterState *interp)
1034
1035 Return the interpreter's unique ID. If there was any error in doing
1036 so then -1 is returned and an error is set.
1037
1038 .. versionadded:: 3.7
1039
1040
Georg Brandl60203b42010-10-06 10:11:56 +00001041.. c:function:: PyObject* PyThreadState_GetDict()
Georg Brandl116aa622007-08-15 14:28:22 +00001042
1043 Return a dictionary in which extensions can store thread-specific state
1044 information. Each extension should use a unique key to use to store state in
1045 the dictionary. It is okay to call this function when no current thread state
1046 is available. If this function returns *NULL*, no exception has been raised and
1047 the caller should assume no current thread state is available.
1048
Georg Brandl116aa622007-08-15 14:28:22 +00001049
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02001050.. c:function:: int PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
Georg Brandl116aa622007-08-15 14:28:22 +00001051
1052 Asynchronously raise an exception in a thread. The *id* argument is the thread
1053 id of the target thread; *exc* is the exception object to be raised. This
1054 function does not steal any references to *exc*. To prevent naive misuse, you
1055 must write your own C extension to call this. Must be called with the GIL held.
1056 Returns the number of thread states modified; this is normally one, but will be
1057 zero if the thread id isn't found. If *exc* is :const:`NULL`, the pending
1058 exception (if any) for the thread is cleared. This raises no exceptions.
1059
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02001060 .. versionchanged:: 3.7
1061 The type of the *id* parameter changed from :c:type:`long` to
1062 :c:type:`unsigned long`.
Georg Brandl116aa622007-08-15 14:28:22 +00001063
Antoine Pitroubedd2c22011-01-15 12:54:19 +00001064.. c:function:: void PyEval_AcquireThread(PyThreadState *tstate)
Georg Brandl116aa622007-08-15 14:28:22 +00001065
Antoine Pitroubedd2c22011-01-15 12:54:19 +00001066 Acquire the global interpreter lock and set the current thread state to
1067 *tstate*, which should not be *NULL*. The lock must have been created earlier.
1068 If this thread already has the lock, deadlock ensues.
Georg Brandl116aa622007-08-15 14:28:22 +00001069
Antoine Pitrou5ace8e92011-01-15 13:11:48 +00001070 :c:func:`PyEval_RestoreThread` is a higher-level function which is always
1071 available (even when thread support isn't enabled or when threads have
1072 not been initialized).
1073
Georg Brandl116aa622007-08-15 14:28:22 +00001074
Antoine Pitroubedd2c22011-01-15 12:54:19 +00001075.. c:function:: void PyEval_ReleaseThread(PyThreadState *tstate)
Georg Brandl116aa622007-08-15 14:28:22 +00001076
Antoine Pitroubedd2c22011-01-15 12:54:19 +00001077 Reset the current thread state to *NULL* and release the global interpreter
1078 lock. The lock must have been created earlier and must be held by the current
1079 thread. The *tstate* argument, which must not be *NULL*, is only used to check
1080 that it represents the current thread state --- if it isn't, a fatal error is
1081 reported.
Georg Brandl116aa622007-08-15 14:28:22 +00001082
Antoine Pitrou5ace8e92011-01-15 13:11:48 +00001083 :c:func:`PyEval_SaveThread` is a higher-level function which is always
1084 available (even when thread support isn't enabled or when threads have
1085 not been initialized).
1086
Antoine Pitroubedd2c22011-01-15 12:54:19 +00001087
1088.. c:function:: void PyEval_AcquireLock()
1089
1090 Acquire the global interpreter lock. The lock must have been created earlier.
1091 If this thread already has the lock, a deadlock ensues.
1092
Antoine Pitrou5ace8e92011-01-15 13:11:48 +00001093 .. deprecated:: 3.2
Antoine Pitrouf5cf4352011-01-15 14:31:49 +00001094 This function does not update the current thread state. Please use
Antoine Pitrou5ace8e92011-01-15 13:11:48 +00001095 :c:func:`PyEval_RestoreThread` or :c:func:`PyEval_AcquireThread`
1096 instead.
1097
Antoine Pitroubedd2c22011-01-15 12:54:19 +00001098
1099.. c:function:: void PyEval_ReleaseLock()
1100
1101 Release the global interpreter lock. The lock must have been created earlier.
Georg Brandl116aa622007-08-15 14:28:22 +00001102
Antoine Pitrou5ace8e92011-01-15 13:11:48 +00001103 .. deprecated:: 3.2
Antoine Pitrouf5cf4352011-01-15 14:31:49 +00001104 This function does not update the current thread state. Please use
Antoine Pitrou5ace8e92011-01-15 13:11:48 +00001105 :c:func:`PyEval_SaveThread` or :c:func:`PyEval_ReleaseThread`
1106 instead.
1107
Georg Brandl116aa622007-08-15 14:28:22 +00001108
Nick Coghlan2ab5b092015-07-03 19:49:15 +10001109.. _sub-interpreter-support:
1110
Antoine Pitrou8b50b832011-01-15 11:57:42 +00001111Sub-interpreter support
1112=======================
1113
1114While in most uses, you will only embed a single Python interpreter, there
1115are cases where you need to create several independent interpreters in the
1116same process and perhaps even in the same thread. Sub-interpreters allow
Antoine Pitrou9bf8d1c2011-01-15 12:21:53 +00001117you to do that. You can switch between sub-interpreters using the
1118:c:func:`PyThreadState_Swap` function. You can create and destroy them
1119using the following functions:
Antoine Pitrou8b50b832011-01-15 11:57:42 +00001120
1121
1122.. c:function:: PyThreadState* Py_NewInterpreter()
1123
1124 .. index::
1125 module: builtins
1126 module: __main__
1127 module: sys
1128 single: stdout (in module sys)
1129 single: stderr (in module sys)
1130 single: stdin (in module sys)
1131
1132 Create a new sub-interpreter. This is an (almost) totally separate environment
1133 for the execution of Python code. In particular, the new interpreter has
1134 separate, independent versions of all imported modules, including the
1135 fundamental modules :mod:`builtins`, :mod:`__main__` and :mod:`sys`. The
1136 table of loaded modules (``sys.modules``) and the module search path
1137 (``sys.path``) are also separate. The new environment has no ``sys.argv``
1138 variable. It has new standard I/O stream file objects ``sys.stdin``,
1139 ``sys.stdout`` and ``sys.stderr`` (however these refer to the same underlying
1140 file descriptors).
1141
1142 The return value points to the first thread state created in the new
1143 sub-interpreter. This thread state is made in the current thread state.
1144 Note that no actual thread is created; see the discussion of thread states
1145 below. If creation of the new interpreter is unsuccessful, *NULL* is
1146 returned; no exception is set since the exception state is stored in the
1147 current thread state and there may not be a current thread state. (Like all
1148 other Python/C API functions, the global interpreter lock must be held before
1149 calling this function and is still held when it returns; however, unlike most
1150 other Python/C API functions, there needn't be a current thread state on
1151 entry.)
1152
1153 .. index::
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001154 single: Py_FinalizeEx()
Antoine Pitrou8b50b832011-01-15 11:57:42 +00001155 single: Py_Initialize()
1156
1157 Extension modules are shared between (sub-)interpreters as follows: the first
1158 time a particular extension is imported, it is initialized normally, and a
1159 (shallow) copy of its module's dictionary is squirreled away. When the same
1160 extension is imported by another (sub-)interpreter, a new module is initialized
1161 and filled with the contents of this copy; the extension's ``init`` function is
1162 not called. Note that this is different from what happens when an extension is
1163 imported after the interpreter has been completely re-initialized by calling
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001164 :c:func:`Py_FinalizeEx` and :c:func:`Py_Initialize`; in that case, the extension's
Antoine Pitrou8b50b832011-01-15 11:57:42 +00001165 ``initmodule`` function *is* called again.
1166
1167 .. index:: single: close() (in module os)
1168
1169
1170.. c:function:: void Py_EndInterpreter(PyThreadState *tstate)
1171
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001172 .. index:: single: Py_FinalizeEx()
Antoine Pitrou8b50b832011-01-15 11:57:42 +00001173
1174 Destroy the (sub-)interpreter represented by the given thread state. The given
1175 thread state must be the current thread state. See the discussion of thread
1176 states below. When the call returns, the current thread state is *NULL*. All
1177 thread states associated with this interpreter are destroyed. (The global
1178 interpreter lock must be held before calling this function and is still held
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001179 when it returns.) :c:func:`Py_FinalizeEx` will destroy all sub-interpreters that
Antoine Pitrou8b50b832011-01-15 11:57:42 +00001180 haven't been explicitly destroyed at that point.
1181
1182
1183Bugs and caveats
1184----------------
1185
1186Because sub-interpreters (and the main interpreter) are part of the same
1187process, the insulation between them isn't perfect --- for example, using
1188low-level file operations like :func:`os.close` they can
1189(accidentally or maliciously) affect each other's open files. Because of the
1190way extensions are shared between (sub-)interpreters, some extensions may not
1191work properly; this is especially likely when the extension makes use of
1192(static) global variables, or when the extension manipulates its module's
1193dictionary after its initialization. It is possible to insert objects created
1194in one sub-interpreter into a namespace of another sub-interpreter; this should
1195be done with great care to avoid sharing user-defined functions, methods,
1196instances or classes between sub-interpreters, since import operations executed
1197by such objects may affect the wrong (sub-)interpreter's dictionary of loaded
Antoine Pitrouf1dfe732011-01-15 12:10:48 +00001198modules.
Antoine Pitrou8b50b832011-01-15 11:57:42 +00001199
Antoine Pitrouf1dfe732011-01-15 12:10:48 +00001200Also note that combining this functionality with :c:func:`PyGILState_\*` APIs
Ezio Melottid92ab082011-05-05 14:19:48 +03001201is delicate, because these APIs assume a bijection between Python thread states
Antoine Pitrouf1dfe732011-01-15 12:10:48 +00001202and OS-level threads, an assumption broken by the presence of sub-interpreters.
1203It is highly recommended that you don't switch sub-interpreters between a pair
1204of matching :c:func:`PyGILState_Ensure` and :c:func:`PyGILState_Release` calls.
1205Furthermore, extensions (such as :mod:`ctypes`) using these APIs to allow calling
1206of Python code from non-Python created threads will probably be broken when using
1207sub-interpreters.
Antoine Pitrou8b50b832011-01-15 11:57:42 +00001208
Benjamin Petersona54c9092009-01-13 02:11:23 +00001209
1210Asynchronous Notifications
1211==========================
1212
Benjamin Petersond23f8222009-04-05 19:13:16 +00001213A mechanism is provided to make asynchronous notifications to the main
Benjamin Petersona54c9092009-01-13 02:11:23 +00001214interpreter thread. These notifications take the form of a function
Antoine Pitrou1a67bee2013-09-30 21:35:44 +02001215pointer and a void pointer argument.
Benjamin Petersona54c9092009-01-13 02:11:23 +00001216
Benjamin Petersona54c9092009-01-13 02:11:23 +00001217
Ezio Melottia782cca2011-04-28 00:53:14 +03001218.. c:function:: int Py_AddPendingCall(int (*func)(void *), void *arg)
Benjamin Petersona54c9092009-01-13 02:11:23 +00001219
1220 .. index:: single: Py_AddPendingCall()
1221
Antoine Pitrou1a67bee2013-09-30 21:35:44 +02001222 Schedule a function to be called from the main interpreter thread. On
Serhiy Storchaka1ecf7d22016-10-27 21:41:19 +03001223 success, ``0`` is returned and *func* is queued for being called in the
1224 main thread. On failure, ``-1`` is returned without setting any exception.
Benjamin Petersona54c9092009-01-13 02:11:23 +00001225
Antoine Pitrou1a67bee2013-09-30 21:35:44 +02001226 When successfully queued, *func* will be *eventually* called from the
1227 main interpreter thread with the argument *arg*. It will be called
1228 asynchronously with respect to normally running Python code, but with
1229 both these conditions met:
Benjamin Petersona54c9092009-01-13 02:11:23 +00001230
Antoine Pitrou1a67bee2013-09-30 21:35:44 +02001231 * on a :term:`bytecode` boundary;
1232 * with the main thread holding the :term:`global interpreter lock`
1233 (*func* can therefore use the full C API).
1234
Serhiy Storchaka1ecf7d22016-10-27 21:41:19 +03001235 *func* must return ``0`` on success, or ``-1`` on failure with an exception
Antoine Pitrou1a67bee2013-09-30 21:35:44 +02001236 set. *func* won't be interrupted to perform another asynchronous
1237 notification recursively, but it can still be interrupted to switch
1238 threads if the global interpreter lock is released.
1239
1240 This function doesn't need a current thread state to run, and it doesn't
1241 need the global interpreter lock.
1242
1243 .. warning::
1244 This is a low-level function, only useful for very special cases.
1245 There is no guarantee that *func* will be called as quick as
1246 possible. If the main thread is busy executing a system call,
1247 *func* won't be called before the system call returns. This
1248 function is generally **not** suitable for calling Python code from
1249 arbitrary C threads. Instead, use the :ref:`PyGILState API<gilstate>`.
Benjamin Petersona54c9092009-01-13 02:11:23 +00001250
Georg Brandl705d9d52009-05-05 09:29:50 +00001251 .. versionadded:: 3.1
Benjamin Petersona54c9092009-01-13 02:11:23 +00001252
Georg Brandl116aa622007-08-15 14:28:22 +00001253.. _profiling:
1254
1255Profiling and Tracing
1256=====================
1257
1258.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
1259
1260
1261The Python interpreter provides some low-level support for attaching profiling
1262and execution tracing facilities. These are used for profiling, debugging, and
1263coverage analysis tools.
1264
Georg Brandle6bcc912008-05-12 18:05:20 +00001265This C interface allows the profiling or tracing code to avoid the overhead of
1266calling through Python-level callable objects, making a direct C function call
1267instead. The essential attributes of the facility have not changed; the
1268interface allows trace functions to be installed per-thread, and the basic
1269events reported to the trace function are the same as had been reported to the
1270Python-level trace functions in previous versions.
Georg Brandl116aa622007-08-15 14:28:22 +00001271
1272
Georg Brandl60203b42010-10-06 10:11:56 +00001273.. c:type:: int (*Py_tracefunc)(PyObject *obj, PyFrameObject *frame, int what, PyObject *arg)
Georg Brandl116aa622007-08-15 14:28:22 +00001274
Georg Brandl60203b42010-10-06 10:11:56 +00001275 The type of the trace function registered using :c:func:`PyEval_SetProfile` and
1276 :c:func:`PyEval_SetTrace`. The first parameter is the object passed to the
Georg Brandl116aa622007-08-15 14:28:22 +00001277 registration function as *obj*, *frame* is the frame object to which the event
1278 pertains, *what* is one of the constants :const:`PyTrace_CALL`,
1279 :const:`PyTrace_EXCEPTION`, :const:`PyTrace_LINE`, :const:`PyTrace_RETURN`,
1280 :const:`PyTrace_C_CALL`, :const:`PyTrace_C_EXCEPTION`, or
1281 :const:`PyTrace_C_RETURN`, and *arg* depends on the value of *what*:
1282
1283 +------------------------------+--------------------------------------+
1284 | Value of *what* | Meaning of *arg* |
1285 +==============================+======================================+
1286 | :const:`PyTrace_CALL` | Always *NULL*. |
1287 +------------------------------+--------------------------------------+
1288 | :const:`PyTrace_EXCEPTION` | Exception information as returned by |
1289 | | :func:`sys.exc_info`. |
1290 +------------------------------+--------------------------------------+
1291 | :const:`PyTrace_LINE` | Always *NULL*. |
1292 +------------------------------+--------------------------------------+
Georg Brandld0b0e1d2010-10-15 16:42:37 +00001293 | :const:`PyTrace_RETURN` | Value being returned to the caller, |
1294 | | or *NULL* if caused by an exception. |
Georg Brandl116aa622007-08-15 14:28:22 +00001295 +------------------------------+--------------------------------------+
Georg Brandld0b0e1d2010-10-15 16:42:37 +00001296 | :const:`PyTrace_C_CALL` | Function object being called. |
Georg Brandl116aa622007-08-15 14:28:22 +00001297 +------------------------------+--------------------------------------+
Georg Brandld0b0e1d2010-10-15 16:42:37 +00001298 | :const:`PyTrace_C_EXCEPTION` | Function object being called. |
Georg Brandl116aa622007-08-15 14:28:22 +00001299 +------------------------------+--------------------------------------+
Georg Brandld0b0e1d2010-10-15 16:42:37 +00001300 | :const:`PyTrace_C_RETURN` | Function object being called. |
Georg Brandl116aa622007-08-15 14:28:22 +00001301 +------------------------------+--------------------------------------+
1302
1303
Georg Brandl60203b42010-10-06 10:11:56 +00001304.. c:var:: int PyTrace_CALL
Georg Brandl116aa622007-08-15 14:28:22 +00001305
Georg Brandl60203b42010-10-06 10:11:56 +00001306 The value of the *what* parameter to a :c:type:`Py_tracefunc` function when a new
Georg Brandl116aa622007-08-15 14:28:22 +00001307 call to a function or method is being reported, or a new entry into a generator.
1308 Note that the creation of the iterator for a generator function is not reported
1309 as there is no control transfer to the Python bytecode in the corresponding
1310 frame.
1311
1312
Georg Brandl60203b42010-10-06 10:11:56 +00001313.. c:var:: int PyTrace_EXCEPTION
Georg Brandl116aa622007-08-15 14:28:22 +00001314
Georg Brandl60203b42010-10-06 10:11:56 +00001315 The value of the *what* parameter to a :c:type:`Py_tracefunc` function when an
Georg Brandl116aa622007-08-15 14:28:22 +00001316 exception has been raised. The callback function is called with this value for
1317 *what* when after any bytecode is processed after which the exception becomes
1318 set within the frame being executed. The effect of this is that as exception
1319 propagation causes the Python stack to unwind, the callback is called upon
1320 return to each frame as the exception propagates. Only trace functions receives
1321 these events; they are not needed by the profiler.
1322
1323
Georg Brandl60203b42010-10-06 10:11:56 +00001324.. c:var:: int PyTrace_LINE
Georg Brandl116aa622007-08-15 14:28:22 +00001325
1326 The value passed as the *what* parameter to a trace function (but not a
1327 profiling function) when a line-number event is being reported.
1328
1329
Georg Brandl60203b42010-10-06 10:11:56 +00001330.. c:var:: int PyTrace_RETURN
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
Georg Brandl116aa622007-08-15 14:28:22 +00001333 call is returning without propagating an exception.
1334
1335
Georg Brandl60203b42010-10-06 10:11:56 +00001336.. c:var:: int PyTrace_C_CALL
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 is about to be called.
1340
1341
Georg Brandl60203b42010-10-06 10:11:56 +00001342.. c:var:: int PyTrace_C_EXCEPTION
Georg Brandl116aa622007-08-15 14:28:22 +00001343
Georg Brandl60203b42010-10-06 10:11:56 +00001344 The value for the *what* parameter to :c:type:`Py_tracefunc` functions when a C
Georg Brandl7cb13192010-08-03 12:06:29 +00001345 function has raised an exception.
Georg Brandl116aa622007-08-15 14:28:22 +00001346
1347
Georg Brandl60203b42010-10-06 10:11:56 +00001348.. c:var:: int PyTrace_C_RETURN
Georg Brandl116aa622007-08-15 14:28:22 +00001349
Georg Brandl60203b42010-10-06 10:11:56 +00001350 The value for the *what* parameter to :c:type:`Py_tracefunc` functions when a C
Georg Brandl116aa622007-08-15 14:28:22 +00001351 function has returned.
1352
1353
Georg Brandl60203b42010-10-06 10:11:56 +00001354.. c:function:: void PyEval_SetProfile(Py_tracefunc func, PyObject *obj)
Georg Brandl116aa622007-08-15 14:28:22 +00001355
1356 Set the profiler function to *func*. The *obj* parameter is passed to the
1357 function as its first parameter, and may be any Python object, or *NULL*. If
1358 the profile function needs to maintain state, using a different value for *obj*
1359 for each thread provides a convenient and thread-safe place to store it. The
1360 profile function is called for all monitored events except the line-number
1361 events.
1362
1363
Georg Brandl60203b42010-10-06 10:11:56 +00001364.. c:function:: void PyEval_SetTrace(Py_tracefunc func, PyObject *obj)
Georg Brandl116aa622007-08-15 14:28:22 +00001365
1366 Set the tracing function to *func*. This is similar to
Georg Brandl60203b42010-10-06 10:11:56 +00001367 :c:func:`PyEval_SetProfile`, except the tracing function does receive line-number
Georg Brandl116aa622007-08-15 14:28:22 +00001368 events.
1369
1370
1371.. _advanced-debugging:
1372
1373Advanced Debugger Support
1374=========================
1375
1376.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
1377
1378
1379These functions are only intended to be used by advanced debugging tools.
1380
1381
Georg Brandl60203b42010-10-06 10:11:56 +00001382.. c:function:: PyInterpreterState* PyInterpreterState_Head()
Georg Brandl116aa622007-08-15 14:28:22 +00001383
1384 Return the interpreter state object at the head of the list of all such objects.
1385
Georg Brandl116aa622007-08-15 14:28:22 +00001386
Georg Brandl60203b42010-10-06 10:11:56 +00001387.. c:function:: PyInterpreterState* PyInterpreterState_Next(PyInterpreterState *interp)
Georg Brandl116aa622007-08-15 14:28:22 +00001388
1389 Return the next interpreter state object after *interp* from the list of all
1390 such objects.
1391
Georg Brandl116aa622007-08-15 14:28:22 +00001392
Georg Brandl60203b42010-10-06 10:11:56 +00001393.. c:function:: PyThreadState * PyInterpreterState_ThreadHead(PyInterpreterState *interp)
Georg Brandl116aa622007-08-15 14:28:22 +00001394
Benjamin Peterson82f34ad2015-01-13 09:17:24 -05001395 Return the pointer to the first :c:type:`PyThreadState` object in the list of
Georg Brandl116aa622007-08-15 14:28:22 +00001396 threads associated with the interpreter *interp*.
1397
Georg Brandl116aa622007-08-15 14:28:22 +00001398
Georg Brandl60203b42010-10-06 10:11:56 +00001399.. c:function:: PyThreadState* PyThreadState_Next(PyThreadState *tstate)
Georg Brandl116aa622007-08-15 14:28:22 +00001400
1401 Return the next thread state object after *tstate* from the list of all such
Georg Brandl60203b42010-10-06 10:11:56 +00001402 objects belonging to the same :c:type:`PyInterpreterState` object.
Georg Brandl116aa622007-08-15 14:28:22 +00001403
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001404
1405.. _thread-local-storage:
1406
1407Thread Local Storage Support
1408============================
1409
1410.. sectionauthor:: Masayuki Yamamoto <ma3yuki.8mamo10@gmail.com>
1411
1412The Python interpreter provides low-level support for thread-local storage
1413(TLS) which wraps the underlying native TLS implementation to support the
1414Python-level thread local storage API (:class:`threading.local`). The
1415CPython C level APIs are similar to those offered by pthreads and Windows:
1416use a thread key and functions to associate a :c:type:`void\*` value per
1417thread.
1418
1419The GIL does *not* need to be held when calling these functions; they supply
1420their own locking.
1421
1422Note that :file:`Python.h` does not include the declaration of the TLS APIs,
1423you need to include :file:`pythread.h` to use thread-local storage.
1424
1425.. note::
1426 None of these API functions handle memory management on behalf of the
1427 :c:type:`void\*` values. You need to allocate and deallocate them yourself.
1428 If the :c:type:`void\*` values happen to be :c:type:`PyObject\*`, these
1429 functions don't do refcount operations on them either.
1430
1431.. _thread-specific-storage-api:
1432
1433Thread Specific Storage (TSS) API
1434---------------------------------
1435
1436TSS API is introduced to supersede the use of the existing TLS API within the
1437CPython interpreter. This API uses a new type :c:type:`Py_tss_t` instead of
1438:c:type:`int` to represent thread keys.
1439
1440.. versionadded:: 3.7
1441
1442.. seealso:: "A New C-API for Thread-Local Storage in CPython" (:pep:`539`)
1443
1444
1445.. c:type:: Py_tss_t
1446
1447 This data structure represents the state of a thread key, the definition of
1448 which may depend on the underlying TLS implementation, and it has an
1449 internal field representing the key's initialization state. There are no
1450 public members in this structure.
1451
1452 When :ref:`Py_LIMITED_API <stable>` is not defined, static allocation of
1453 this type by :c:macro:`Py_tss_NEEDS_INIT` is allowed.
1454
1455
1456.. c:macro:: Py_tss_NEEDS_INIT
1457
Masayuki Yamamoto831d61d2017-10-24 21:58:16 +09001458 This macro expands to the initializer for :c:type:`Py_tss_t` variables.
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001459 Note that this macro won't be defined with :ref:`Py_LIMITED_API <stable>`.
1460
1461
1462Dynamic Allocation
1463~~~~~~~~~~~~~~~~~~
1464
1465Dynamic allocation of the :c:type:`Py_tss_t`, required in extension modules
1466built with :ref:`Py_LIMITED_API <stable>`, where static allocation of this type
1467is not possible due to its implementation being opaque at build time.
1468
1469
1470.. c:function:: Py_tss_t* PyThread_tss_alloc()
1471
1472 Return a value which is the same state as a value initialized with
1473 :c:macro:`Py_tss_NEEDS_INIT`, or *NULL* in the case of dynamic allocation
1474 failure.
1475
1476
1477.. c:function:: void PyThread_tss_free(Py_tss_t *key)
1478
1479 Free the given *key* allocated by :c:func:`PyThread_tss_alloc`, after
1480 first calling :c:func:`PyThread_tss_delete` to ensure any associated
1481 thread locals have been unassigned. This is a no-op if the *key*
1482 argument is `NULL`.
1483
1484 .. note::
1485 A freed key becomes a dangling pointer, you should reset the key to
1486 `NULL`.
1487
1488
1489Methods
1490~~~~~~~
1491
1492The parameter *key* of these functions must not be *NULL*. Moreover, the
1493behaviors of :c:func:`PyThread_tss_set` and :c:func:`PyThread_tss_get` are
1494undefined if the given :c:type:`Py_tss_t` has not been initialized by
1495:c:func:`PyThread_tss_create`.
1496
1497
1498.. c:function:: int PyThread_tss_is_created(Py_tss_t *key)
1499
1500 Return a non-zero value if the given :c:type:`Py_tss_t` has been initialized
1501 by :c:func:`PyThread_tss_create`.
1502
1503
1504.. c:function:: int PyThread_tss_create(Py_tss_t *key)
1505
1506 Return a zero value on successful initialization of a TSS key. The behavior
1507 is undefined if the value pointed to by the *key* argument is not
1508 initialized by :c:macro:`Py_tss_NEEDS_INIT`. This function can be called
1509 repeatedly on the same key -- calling it on an already initialized key is a
1510 no-op and immediately returns success.
1511
1512
1513.. c:function:: void PyThread_tss_delete(Py_tss_t *key)
1514
1515 Destroy a TSS key to forget the values associated with the key across all
1516 threads, and change the key's initialization state to uninitialized. A
1517 destroyed key is able to be initialized again by
1518 :c:func:`PyThread_tss_create`. This function can be called repeatedly on
1519 the same key -- calling it on an already destroyed key is a no-op.
1520
1521
1522.. c:function:: int PyThread_tss_set(Py_tss_t *key, void *value)
1523
1524 Return a zero value to indicate successfully associating a :c:type:`void\*`
1525 value with a TSS key in the current thread. Each thread has a distinct
1526 mapping of the key to a :c:type:`void\*` value.
1527
1528
1529.. c:function:: void* PyThread_tss_get(Py_tss_t *key)
1530
1531 Return the :c:type:`void\*` value associated with a TSS key in the current
1532 thread. This returns *NULL* if no value is associated with the key in the
1533 current thread.
1534
1535
1536.. _thread-local-storage-api:
1537
1538Thread Local Storage (TLS) API
1539------------------------------
1540
1541.. deprecated:: 3.7
1542 This API is superseded by
1543 :ref:`Thread Specific Storage (TSS) API <thread-specific-storage-api>`.
1544
1545.. note::
1546 This version of the API does not support platforms where the native TLS key
1547 is defined in a way that cannot be safely cast to ``int``. On such platforms,
1548 :c:func:`PyThread_create_key` will return immediately with a failure status,
1549 and the other TLS functions will all be no-ops on such platforms.
1550
1551Due to the compatibility problem noted above, this version of the API should not
1552be used in new code.
1553
1554.. c:function:: int PyThread_create_key()
1555.. c:function:: void PyThread_delete_key(int key)
1556.. c:function:: int PyThread_set_key_value(int key, void *value)
1557.. c:function:: void* PyThread_get_key_value(int key)
1558.. c:function:: void PyThread_delete_key_value(int key)
1559.. c:function:: void PyThread_ReInitTLS()
1560