blob: f2564c44147280d28f87665a7b2ac71df976da18 [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
Miss Islington (bot)3a047a72018-02-09 04:08:04 -0800276 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
Victor Stinner2914bb32018-01-29 11:57:45 +0100690block.
Georg Brandl116aa622007-08-15 14:28:22 +0000691
Victor Stinner2914bb32018-01-29 11:57:45 +0100692The block above expands to the following code::
Georg Brandl116aa622007-08-15 14:28:22 +0000693
694 PyThreadState *_save;
695
696 _save = PyEval_SaveThread();
Victor Stinner2914bb32018-01-29 11:57:45 +0100697 ... Do some blocking I/O operation ...
Georg Brandl116aa622007-08-15 14:28:22 +0000698 PyEval_RestoreThread(_save);
699
Georg Brandl116aa622007-08-15 14:28:22 +0000700.. index::
701 single: PyEval_RestoreThread()
Georg Brandl116aa622007-08-15 14:28:22 +0000702 single: PyEval_SaveThread()
Georg Brandl116aa622007-08-15 14:28:22 +0000703
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000704Here is how these functions work: the global interpreter lock is used to protect the pointer to the
705current thread state. When releasing the lock and saving the thread state,
706the current thread state pointer must be retrieved before the lock is released
707(since another thread could immediately acquire the lock and store its own thread
708state in the global variable). Conversely, when acquiring the lock and restoring
709the thread state, the lock must be acquired before storing the thread state
710pointer.
Georg Brandl116aa622007-08-15 14:28:22 +0000711
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000712.. note::
713 Calling system I/O functions is the most common use case for releasing
714 the GIL, but it can also be useful before calling long-running computations
715 which don't need access to Python objects, such as compression or
716 cryptographic functions operating over memory buffers. For example, the
717 standard :mod:`zlib` and :mod:`hashlib` modules release the GIL when
718 compressing or hashing data.
Georg Brandl116aa622007-08-15 14:28:22 +0000719
Antoine Pitrou1a67bee2013-09-30 21:35:44 +0200720
721.. _gilstate:
722
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000723Non-Python created threads
724--------------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000725
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000726When threads are created using the dedicated Python APIs (such as the
727:mod:`threading` module), a thread state is automatically associated to them
728and the code showed above is therefore correct. However, when threads are
729created from C (for example by a third-party library with its own thread
730management), they don't hold the GIL, nor is there a thread state structure
731for them.
732
733If you need to call Python code from these threads (often this will be part
734of a callback API provided by the aforementioned third-party library),
735you must first register these threads with the interpreter by
736creating a thread state data structure, then acquiring the GIL, and finally
737storing their thread state pointer, before you can start using the Python/C
738API. When you are done, you should reset the thread state pointer, release
739the GIL, and finally free the thread state data structure.
740
741The :c:func:`PyGILState_Ensure` and :c:func:`PyGILState_Release` functions do
742all of the above automatically. The typical idiom for calling into Python
743from a C thread is::
Georg Brandl116aa622007-08-15 14:28:22 +0000744
745 PyGILState_STATE gstate;
746 gstate = PyGILState_Ensure();
747
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000748 /* Perform Python actions here. */
Georg Brandl116aa622007-08-15 14:28:22 +0000749 result = CallSomeFunction();
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000750 /* evaluate result or handle exception */
Georg Brandl116aa622007-08-15 14:28:22 +0000751
752 /* Release the thread. No Python API allowed beyond this point. */
753 PyGILState_Release(gstate);
754
Georg Brandl60203b42010-10-06 10:11:56 +0000755Note that the :c:func:`PyGILState_\*` functions assume there is only one global
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000756interpreter (created automatically by :c:func:`Py_Initialize`). Python
Georg Brandl116aa622007-08-15 14:28:22 +0000757supports the creation of additional interpreters (using
Georg Brandl60203b42010-10-06 10:11:56 +0000758:c:func:`Py_NewInterpreter`), but mixing multiple interpreters and the
759:c:func:`PyGILState_\*` API is unsupported.
Georg Brandl116aa622007-08-15 14:28:22 +0000760
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000761Another important thing to note about threads is their behaviour in the face
Georg Brandl60203b42010-10-06 10:11:56 +0000762of the C :c:func:`fork` call. On most systems with :c:func:`fork`, after a
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000763process forks only the thread that issued the fork will exist. That also
764means any locks held by other threads will never be released. Python solves
765this for :func:`os.fork` by acquiring the locks it uses internally before
766the fork, and releasing them afterwards. In addition, it resets any
767:ref:`lock-objects` in the child. When extending or embedding Python, there
768is no way to inform Python of additional (non-Python) locks that need to be
769acquired before or reset after a fork. OS facilities such as
Ezio Melotti861d27f2011-04-20 21:32:40 +0300770:c:func:`pthread_atfork` would need to be used to accomplish the same thing.
Georg Brandl60203b42010-10-06 10:11:56 +0000771Additionally, when extending or embedding Python, calling :c:func:`fork`
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000772directly rather than through :func:`os.fork` (and returning to or calling
773into Python) may result in a deadlock by one of Python's internal locks
774being held by a thread that is defunct after the fork.
Antoine Pitrouf7ecfac2017-05-28 11:35:14 +0200775:c:func:`PyOS_AfterFork_Child` tries to reset the necessary locks, but is not
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000776always able to.
Georg Brandl116aa622007-08-15 14:28:22 +0000777
Antoine Pitrou8b50b832011-01-15 11:57:42 +0000778
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000779High-level API
780--------------
781
782These are the most commonly used types and functions when writing C extension
783code, or when embedding the Python interpreter:
784
Georg Brandl60203b42010-10-06 10:11:56 +0000785.. c:type:: PyInterpreterState
Georg Brandl116aa622007-08-15 14:28:22 +0000786
787 This data structure represents the state shared by a number of cooperating
788 threads. Threads belonging to the same interpreter share their module
789 administration and a few other internal items. There are no public members in
790 this structure.
791
792 Threads belonging to different interpreters initially share nothing, except
793 process state like available memory, open file descriptors and such. The global
794 interpreter lock is also shared by all threads, regardless of to which
795 interpreter they belong.
796
797
Georg Brandl60203b42010-10-06 10:11:56 +0000798.. c:type:: PyThreadState
Georg Brandl116aa622007-08-15 14:28:22 +0000799
800 This data structure represents the state of a single thread. The only public
Georg Brandl60203b42010-10-06 10:11:56 +0000801 data member is :c:type:`PyInterpreterState \*`:attr:`interp`, which points to
Georg Brandl116aa622007-08-15 14:28:22 +0000802 this thread's interpreter state.
803
804
Georg Brandl60203b42010-10-06 10:11:56 +0000805.. c:function:: void PyEval_InitThreads()
Georg Brandl116aa622007-08-15 14:28:22 +0000806
807 .. index::
Antoine Pitrouf5cf4352011-01-15 14:31:49 +0000808 single: PyEval_AcquireThread()
Georg Brandl116aa622007-08-15 14:28:22 +0000809 single: PyEval_ReleaseThread()
810 single: PyEval_SaveThread()
811 single: PyEval_RestoreThread()
812
813 Initialize and acquire the global interpreter lock. It should be called in the
814 main thread before creating a second thread or engaging in any other thread
Antoine Pitrouf5cf4352011-01-15 14:31:49 +0000815 operations such as ``PyEval_ReleaseThread(tstate)``. It is not needed before
816 calling :c:func:`PyEval_SaveThread` or :c:func:`PyEval_RestoreThread`.
Georg Brandl116aa622007-08-15 14:28:22 +0000817
Antoine Pitrou9bd3bbc2011-03-13 23:28:28 +0100818 This is a no-op when called for a second time.
Georg Brandl116aa622007-08-15 14:28:22 +0000819
Victor Stinner2914bb32018-01-29 11:57:45 +0100820 .. versionchanged:: 3.7
821 This function is now called by :c:func:`Py_Initialize()`, so you don't
822 have to call it yourself anymore.
823
Antoine Pitrou9bb98772011-03-15 20:22:50 +0100824 .. versionchanged:: 3.2
825 This function cannot be called before :c:func:`Py_Initialize()` anymore.
826
Georg Brandl2067bfd2008-05-25 13:05:15 +0000827 .. index:: module: _thread
Georg Brandl116aa622007-08-15 14:28:22 +0000828
Georg Brandl116aa622007-08-15 14:28:22 +0000829
Georg Brandl60203b42010-10-06 10:11:56 +0000830.. c:function:: int PyEval_ThreadsInitialized()
Georg Brandl116aa622007-08-15 14:28:22 +0000831
Georg Brandl60203b42010-10-06 10:11:56 +0000832 Returns a non-zero value if :c:func:`PyEval_InitThreads` has been called. This
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000833 function can be called without holding the GIL, and therefore can be used to
Victor Stinner2914bb32018-01-29 11:57:45 +0100834 avoid calls to the locking API when running single-threaded.
835
836 .. versionchanged:: 3.7
837 The :term:`GIL` is now initialized by :c:func:`Py_Initialize()`.
Georg Brandl116aa622007-08-15 14:28:22 +0000838
Georg Brandl116aa622007-08-15 14:28:22 +0000839
Georg Brandl60203b42010-10-06 10:11:56 +0000840.. c:function:: PyThreadState* PyEval_SaveThread()
Georg Brandl116aa622007-08-15 14:28:22 +0000841
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000842 Release the global interpreter lock (if it has been created and thread
843 support is enabled) and reset the thread state to *NULL*, returning the
844 previous thread state (which is not *NULL*). If the lock has been created,
Victor Stinner2914bb32018-01-29 11:57:45 +0100845 the current thread must have acquired it.
Georg Brandl116aa622007-08-15 14:28:22 +0000846
847
Georg Brandl60203b42010-10-06 10:11:56 +0000848.. c:function:: void PyEval_RestoreThread(PyThreadState *tstate)
Georg Brandl116aa622007-08-15 14:28:22 +0000849
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000850 Acquire the global interpreter lock (if it has been created and thread
851 support is enabled) and set the thread state to *tstate*, which must not be
852 *NULL*. If the lock has been created, the current thread must not have
Victor Stinner2914bb32018-01-29 11:57:45 +0100853 acquired it, otherwise deadlock ensues.
Georg Brandl116aa622007-08-15 14:28:22 +0000854
Christian Heimesd8654cf2007-12-02 15:22:16 +0000855
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000856.. c:function:: PyThreadState* PyThreadState_Get()
857
858 Return the current thread state. The global interpreter lock must be held.
859 When the current thread state is *NULL*, this issues a fatal error (so that
860 the caller needn't check for *NULL*).
861
862
863.. c:function:: PyThreadState* PyThreadState_Swap(PyThreadState *tstate)
864
865 Swap the current thread state with the thread state given by the argument
866 *tstate*, which may be *NULL*. The global interpreter lock must be held
867 and is not released.
868
869
Georg Brandl60203b42010-10-06 10:11:56 +0000870.. c:function:: void PyEval_ReInitThreads()
Christian Heimesd8654cf2007-12-02 15:22:16 +0000871
Antoine Pitrouf7ecfac2017-05-28 11:35:14 +0200872 This function is called from :c:func:`PyOS_AfterFork_Child` to ensure
873 that newly created child processes don't hold locks referring to threads
874 which are not running in the child process.
Christian Heimesd8654cf2007-12-02 15:22:16 +0000875
876
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000877The following functions use thread-local storage, and are not compatible
878with sub-interpreters:
879
880.. c:function:: PyGILState_STATE PyGILState_Ensure()
881
882 Ensure that the current thread is ready to call the Python C API regardless
883 of the current state of Python, or of the global interpreter lock. This may
884 be called as many times as desired by a thread as long as each call is
885 matched with a call to :c:func:`PyGILState_Release`. In general, other
886 thread-related APIs may be used between :c:func:`PyGILState_Ensure` and
887 :c:func:`PyGILState_Release` calls as long as the thread state is restored to
888 its previous state before the Release(). For example, normal usage of the
889 :c:macro:`Py_BEGIN_ALLOW_THREADS` and :c:macro:`Py_END_ALLOW_THREADS` macros is
890 acceptable.
891
892 The return value is an opaque "handle" to the thread state when
893 :c:func:`PyGILState_Ensure` was called, and must be passed to
894 :c:func:`PyGILState_Release` to ensure Python is left in the same state. Even
895 though recursive calls are allowed, these handles *cannot* be shared - each
896 unique call to :c:func:`PyGILState_Ensure` must save the handle for its call
897 to :c:func:`PyGILState_Release`.
898
899 When the function returns, the current thread will hold the GIL and be able
900 to call arbitrary Python code. Failure is a fatal error.
901
902
903.. c:function:: void PyGILState_Release(PyGILState_STATE)
904
905 Release any resources previously acquired. After this call, Python's state will
906 be the same as it was prior to the corresponding :c:func:`PyGILState_Ensure` call
907 (but generally this state will be unknown to the caller, hence the use of the
908 GILState API).
909
910 Every call to :c:func:`PyGILState_Ensure` must be matched by a call to
911 :c:func:`PyGILState_Release` on the same thread.
912
913
Eli Bendersky08131682012-06-03 08:07:47 +0300914.. c:function:: PyThreadState* PyGILState_GetThisThreadState()
Sandro Tosi61baee02011-08-08 00:16:54 +0200915
916 Get the current thread state for this thread. May return ``NULL`` if no
917 GILState API has been used on the current thread. Note that the main thread
918 always has such a thread-state, even if no auto-thread-state call has been
919 made on the main thread. This is mainly a helper/diagnostic function.
920
921
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -0700922.. c:function:: int PyGILState_Check()
923
Serhiy Storchaka1ecf7d22016-10-27 21:41:19 +0300924 Return ``1`` if the current thread is holding the GIL and ``0`` otherwise.
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -0700925 This function can be called from any thread at any time.
926 Only if it has had its Python thread state initialized and currently is
Serhiy Storchaka1ecf7d22016-10-27 21:41:19 +0300927 holding the GIL will it return ``1``.
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -0700928 This is mainly a helper/diagnostic function. It can be useful
929 for example in callback contexts or memory allocation functions when
930 knowing that the GIL is locked can allow the caller to perform sensitive
931 actions or otherwise behave differently.
932
Kristján Valur Jónsson34870c42013-03-23 03:56:16 -0700933 .. versionadded:: 3.4
934
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -0700935
Georg Brandl116aa622007-08-15 14:28:22 +0000936The following macros are normally used without a trailing semicolon; look for
937example usage in the Python source distribution.
938
939
Georg Brandl60203b42010-10-06 10:11:56 +0000940.. c:macro:: Py_BEGIN_ALLOW_THREADS
Georg Brandl116aa622007-08-15 14:28:22 +0000941
942 This macro expands to ``{ PyThreadState *_save; _save = PyEval_SaveThread();``.
943 Note that it contains an opening brace; it must be matched with a following
Georg Brandl60203b42010-10-06 10:11:56 +0000944 :c:macro:`Py_END_ALLOW_THREADS` macro. See above for further discussion of this
Victor Stinner2914bb32018-01-29 11:57:45 +0100945 macro.
Georg Brandl116aa622007-08-15 14:28:22 +0000946
947
Georg Brandl60203b42010-10-06 10:11:56 +0000948.. c:macro:: Py_END_ALLOW_THREADS
Georg Brandl116aa622007-08-15 14:28:22 +0000949
950 This macro expands to ``PyEval_RestoreThread(_save); }``. Note that it contains
951 a closing brace; it must be matched with an earlier
Georg Brandl60203b42010-10-06 10:11:56 +0000952 :c:macro:`Py_BEGIN_ALLOW_THREADS` macro. See above for further discussion of
Victor Stinner2914bb32018-01-29 11:57:45 +0100953 this macro.
Georg Brandl116aa622007-08-15 14:28:22 +0000954
955
Georg Brandl60203b42010-10-06 10:11:56 +0000956.. c:macro:: Py_BLOCK_THREADS
Georg Brandl116aa622007-08-15 14:28:22 +0000957
958 This macro expands to ``PyEval_RestoreThread(_save);``: it is equivalent to
Victor Stinner2914bb32018-01-29 11:57:45 +0100959 :c:macro:`Py_END_ALLOW_THREADS` without the closing brace.
Georg Brandl116aa622007-08-15 14:28:22 +0000960
961
Georg Brandl60203b42010-10-06 10:11:56 +0000962.. c:macro:: Py_UNBLOCK_THREADS
Georg Brandl116aa622007-08-15 14:28:22 +0000963
964 This macro expands to ``_save = PyEval_SaveThread();``: it is equivalent to
Georg Brandl60203b42010-10-06 10:11:56 +0000965 :c:macro:`Py_BEGIN_ALLOW_THREADS` without the opening brace and variable
Victor Stinner2914bb32018-01-29 11:57:45 +0100966 declaration.
Georg Brandl116aa622007-08-15 14:28:22 +0000967
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000968
969Low-level API
970-------------
971
Victor Stinner2914bb32018-01-29 11:57:45 +0100972All of the following functions must be called after :c:func:`Py_Initialize`.
973
974.. versionchanged:: 3.7
975 :c:func:`Py_Initialize()` now initializes the :term:`GIL`.
Georg Brandl116aa622007-08-15 14:28:22 +0000976
977
Georg Brandl60203b42010-10-06 10:11:56 +0000978.. c:function:: PyInterpreterState* PyInterpreterState_New()
Georg Brandl116aa622007-08-15 14:28:22 +0000979
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000980 Create a new interpreter state object. The global interpreter lock need not
981 be held, but may be held if it is necessary to serialize calls to this
982 function.
Georg Brandl116aa622007-08-15 14:28:22 +0000983
984
Georg Brandl60203b42010-10-06 10:11:56 +0000985.. c:function:: void PyInterpreterState_Clear(PyInterpreterState *interp)
Georg Brandl116aa622007-08-15 14:28:22 +0000986
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000987 Reset all information in an interpreter state object. The global interpreter
988 lock must be held.
Georg Brandl116aa622007-08-15 14:28:22 +0000989
990
Georg Brandl60203b42010-10-06 10:11:56 +0000991.. c:function:: void PyInterpreterState_Delete(PyInterpreterState *interp)
Georg Brandl116aa622007-08-15 14:28:22 +0000992
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000993 Destroy an interpreter state object. The global interpreter lock need not be
994 held. The interpreter state must have been reset with a previous call to
Georg Brandl60203b42010-10-06 10:11:56 +0000995 :c:func:`PyInterpreterState_Clear`.
Georg Brandl116aa622007-08-15 14:28:22 +0000996
997
Georg Brandl60203b42010-10-06 10:11:56 +0000998.. c:function:: PyThreadState* PyThreadState_New(PyInterpreterState *interp)
Georg Brandl116aa622007-08-15 14:28:22 +0000999
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001000 Create a new thread state object belonging to the given interpreter object.
1001 The global interpreter lock need not be held, but may be held if it is
1002 necessary to serialize calls to this function.
Georg Brandl116aa622007-08-15 14:28:22 +00001003
1004
Georg Brandl60203b42010-10-06 10:11:56 +00001005.. c:function:: void PyThreadState_Clear(PyThreadState *tstate)
Georg Brandl116aa622007-08-15 14:28:22 +00001006
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001007 Reset all information in a thread state object. The global interpreter lock
1008 must be held.
Georg Brandl116aa622007-08-15 14:28:22 +00001009
1010
Georg Brandl60203b42010-10-06 10:11:56 +00001011.. c:function:: void PyThreadState_Delete(PyThreadState *tstate)
Georg Brandl116aa622007-08-15 14:28:22 +00001012
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001013 Destroy a thread state object. The global interpreter lock need not be held.
1014 The thread state must have been reset with a previous call to
Georg Brandl60203b42010-10-06 10:11:56 +00001015 :c:func:`PyThreadState_Clear`.
Georg Brandl116aa622007-08-15 14:28:22 +00001016
1017
Eric Snowe3774162017-05-22 19:46:40 -07001018.. c:function:: PY_INT64_T PyInterpreterState_GetID(PyInterpreterState *interp)
1019
1020 Return the interpreter's unique ID. If there was any error in doing
Miss Islington (bot)3a047a72018-02-09 04:08:04 -08001021 so then ``-1`` is returned and an error is set.
Eric Snowe3774162017-05-22 19:46:40 -07001022
1023 .. versionadded:: 3.7
1024
1025
Georg Brandl60203b42010-10-06 10:11:56 +00001026.. c:function:: PyObject* PyThreadState_GetDict()
Georg Brandl116aa622007-08-15 14:28:22 +00001027
1028 Return a dictionary in which extensions can store thread-specific state
1029 information. Each extension should use a unique key to use to store state in
1030 the dictionary. It is okay to call this function when no current thread state
1031 is available. If this function returns *NULL*, no exception has been raised and
1032 the caller should assume no current thread state is available.
1033
Georg Brandl116aa622007-08-15 14:28:22 +00001034
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02001035.. c:function:: int PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
Georg Brandl116aa622007-08-15 14:28:22 +00001036
1037 Asynchronously raise an exception in a thread. The *id* argument is the thread
1038 id of the target thread; *exc* is the exception object to be raised. This
1039 function does not steal any references to *exc*. To prevent naive misuse, you
1040 must write your own C extension to call this. Must be called with the GIL held.
1041 Returns the number of thread states modified; this is normally one, but will be
1042 zero if the thread id isn't found. If *exc* is :const:`NULL`, the pending
1043 exception (if any) for the thread is cleared. This raises no exceptions.
1044
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02001045 .. versionchanged:: 3.7
1046 The type of the *id* parameter changed from :c:type:`long` to
1047 :c:type:`unsigned long`.
Georg Brandl116aa622007-08-15 14:28:22 +00001048
Antoine Pitroubedd2c22011-01-15 12:54:19 +00001049.. c:function:: void PyEval_AcquireThread(PyThreadState *tstate)
Georg Brandl116aa622007-08-15 14:28:22 +00001050
Antoine Pitroubedd2c22011-01-15 12:54:19 +00001051 Acquire the global interpreter lock and set the current thread state to
1052 *tstate*, which should not be *NULL*. The lock must have been created earlier.
1053 If this thread already has the lock, deadlock ensues.
Georg Brandl116aa622007-08-15 14:28:22 +00001054
Antoine Pitrou5ace8e92011-01-15 13:11:48 +00001055 :c:func:`PyEval_RestoreThread` is a higher-level function which is always
Victor Stinner2914bb32018-01-29 11:57:45 +01001056 available (even when threads have not been initialized).
Antoine Pitrou5ace8e92011-01-15 13:11:48 +00001057
Georg Brandl116aa622007-08-15 14:28:22 +00001058
Antoine Pitroubedd2c22011-01-15 12:54:19 +00001059.. c:function:: void PyEval_ReleaseThread(PyThreadState *tstate)
Georg Brandl116aa622007-08-15 14:28:22 +00001060
Antoine Pitroubedd2c22011-01-15 12:54:19 +00001061 Reset the current thread state to *NULL* and release the global interpreter
1062 lock. The lock must have been created earlier and must be held by the current
1063 thread. The *tstate* argument, which must not be *NULL*, is only used to check
1064 that it represents the current thread state --- if it isn't, a fatal error is
1065 reported.
Georg Brandl116aa622007-08-15 14:28:22 +00001066
Antoine Pitrou5ace8e92011-01-15 13:11:48 +00001067 :c:func:`PyEval_SaveThread` is a higher-level function which is always
Victor Stinner2914bb32018-01-29 11:57:45 +01001068 available (even when threads have not been initialized).
Antoine Pitrou5ace8e92011-01-15 13:11:48 +00001069
Antoine Pitroubedd2c22011-01-15 12:54:19 +00001070
1071.. c:function:: void PyEval_AcquireLock()
1072
1073 Acquire the global interpreter lock. The lock must have been created earlier.
1074 If this thread already has the lock, a deadlock ensues.
1075
Antoine Pitrou5ace8e92011-01-15 13:11:48 +00001076 .. deprecated:: 3.2
Antoine Pitrouf5cf4352011-01-15 14:31:49 +00001077 This function does not update the current thread state. Please use
Antoine Pitrou5ace8e92011-01-15 13:11:48 +00001078 :c:func:`PyEval_RestoreThread` or :c:func:`PyEval_AcquireThread`
1079 instead.
1080
Antoine Pitroubedd2c22011-01-15 12:54:19 +00001081
1082.. c:function:: void PyEval_ReleaseLock()
1083
1084 Release the global interpreter lock. The lock must have been created earlier.
Georg Brandl116aa622007-08-15 14:28:22 +00001085
Antoine Pitrou5ace8e92011-01-15 13:11:48 +00001086 .. deprecated:: 3.2
Antoine Pitrouf5cf4352011-01-15 14:31:49 +00001087 This function does not update the current thread state. Please use
Antoine Pitrou5ace8e92011-01-15 13:11:48 +00001088 :c:func:`PyEval_SaveThread` or :c:func:`PyEval_ReleaseThread`
1089 instead.
1090
Georg Brandl116aa622007-08-15 14:28:22 +00001091
Nick Coghlan2ab5b092015-07-03 19:49:15 +10001092.. _sub-interpreter-support:
1093
Antoine Pitrou8b50b832011-01-15 11:57:42 +00001094Sub-interpreter support
1095=======================
1096
1097While in most uses, you will only embed a single Python interpreter, there
1098are cases where you need to create several independent interpreters in the
1099same process and perhaps even in the same thread. Sub-interpreters allow
Antoine Pitrou9bf8d1c2011-01-15 12:21:53 +00001100you to do that. You can switch between sub-interpreters using the
1101:c:func:`PyThreadState_Swap` function. You can create and destroy them
1102using the following functions:
Antoine Pitrou8b50b832011-01-15 11:57:42 +00001103
1104
1105.. c:function:: PyThreadState* Py_NewInterpreter()
1106
1107 .. index::
1108 module: builtins
1109 module: __main__
1110 module: sys
1111 single: stdout (in module sys)
1112 single: stderr (in module sys)
1113 single: stdin (in module sys)
1114
1115 Create a new sub-interpreter. This is an (almost) totally separate environment
1116 for the execution of Python code. In particular, the new interpreter has
1117 separate, independent versions of all imported modules, including the
1118 fundamental modules :mod:`builtins`, :mod:`__main__` and :mod:`sys`. The
1119 table of loaded modules (``sys.modules``) and the module search path
1120 (``sys.path``) are also separate. The new environment has no ``sys.argv``
1121 variable. It has new standard I/O stream file objects ``sys.stdin``,
1122 ``sys.stdout`` and ``sys.stderr`` (however these refer to the same underlying
1123 file descriptors).
1124
1125 The return value points to the first thread state created in the new
1126 sub-interpreter. This thread state is made in the current thread state.
1127 Note that no actual thread is created; see the discussion of thread states
1128 below. If creation of the new interpreter is unsuccessful, *NULL* is
1129 returned; no exception is set since the exception state is stored in the
1130 current thread state and there may not be a current thread state. (Like all
1131 other Python/C API functions, the global interpreter lock must be held before
1132 calling this function and is still held when it returns; however, unlike most
1133 other Python/C API functions, there needn't be a current thread state on
1134 entry.)
1135
1136 .. index::
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001137 single: Py_FinalizeEx()
Antoine Pitrou8b50b832011-01-15 11:57:42 +00001138 single: Py_Initialize()
1139
1140 Extension modules are shared between (sub-)interpreters as follows: the first
1141 time a particular extension is imported, it is initialized normally, and a
1142 (shallow) copy of its module's dictionary is squirreled away. When the same
1143 extension is imported by another (sub-)interpreter, a new module is initialized
1144 and filled with the contents of this copy; the extension's ``init`` function is
1145 not called. Note that this is different from what happens when an extension is
1146 imported after the interpreter has been completely re-initialized by calling
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001147 :c:func:`Py_FinalizeEx` and :c:func:`Py_Initialize`; in that case, the extension's
Antoine Pitrou8b50b832011-01-15 11:57:42 +00001148 ``initmodule`` function *is* called again.
1149
1150 .. index:: single: close() (in module os)
1151
1152
1153.. c:function:: void Py_EndInterpreter(PyThreadState *tstate)
1154
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001155 .. index:: single: Py_FinalizeEx()
Antoine Pitrou8b50b832011-01-15 11:57:42 +00001156
1157 Destroy the (sub-)interpreter represented by the given thread state. The given
1158 thread state must be the current thread state. See the discussion of thread
1159 states below. When the call returns, the current thread state is *NULL*. All
1160 thread states associated with this interpreter are destroyed. (The global
1161 interpreter lock must be held before calling this function and is still held
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001162 when it returns.) :c:func:`Py_FinalizeEx` will destroy all sub-interpreters that
Antoine Pitrou8b50b832011-01-15 11:57:42 +00001163 haven't been explicitly destroyed at that point.
1164
1165
1166Bugs and caveats
1167----------------
1168
1169Because sub-interpreters (and the main interpreter) are part of the same
1170process, the insulation between them isn't perfect --- for example, using
1171low-level file operations like :func:`os.close` they can
1172(accidentally or maliciously) affect each other's open files. Because of the
1173way extensions are shared between (sub-)interpreters, some extensions may not
1174work properly; this is especially likely when the extension makes use of
1175(static) global variables, or when the extension manipulates its module's
1176dictionary after its initialization. It is possible to insert objects created
1177in one sub-interpreter into a namespace of another sub-interpreter; this should
1178be done with great care to avoid sharing user-defined functions, methods,
1179instances or classes between sub-interpreters, since import operations executed
1180by such objects may affect the wrong (sub-)interpreter's dictionary of loaded
Antoine Pitrouf1dfe732011-01-15 12:10:48 +00001181modules.
Antoine Pitrou8b50b832011-01-15 11:57:42 +00001182
Antoine Pitrouf1dfe732011-01-15 12:10:48 +00001183Also note that combining this functionality with :c:func:`PyGILState_\*` APIs
Ezio Melottid92ab082011-05-05 14:19:48 +03001184is delicate, because these APIs assume a bijection between Python thread states
Antoine Pitrouf1dfe732011-01-15 12:10:48 +00001185and OS-level threads, an assumption broken by the presence of sub-interpreters.
1186It is highly recommended that you don't switch sub-interpreters between a pair
1187of matching :c:func:`PyGILState_Ensure` and :c:func:`PyGILState_Release` calls.
1188Furthermore, extensions (such as :mod:`ctypes`) using these APIs to allow calling
1189of Python code from non-Python created threads will probably be broken when using
1190sub-interpreters.
Antoine Pitrou8b50b832011-01-15 11:57:42 +00001191
Benjamin Petersona54c9092009-01-13 02:11:23 +00001192
1193Asynchronous Notifications
1194==========================
1195
Benjamin Petersond23f8222009-04-05 19:13:16 +00001196A mechanism is provided to make asynchronous notifications to the main
Benjamin Petersona54c9092009-01-13 02:11:23 +00001197interpreter thread. These notifications take the form of a function
Antoine Pitrou1a67bee2013-09-30 21:35:44 +02001198pointer and a void pointer argument.
Benjamin Petersona54c9092009-01-13 02:11:23 +00001199
Benjamin Petersona54c9092009-01-13 02:11:23 +00001200
Ezio Melottia782cca2011-04-28 00:53:14 +03001201.. c:function:: int Py_AddPendingCall(int (*func)(void *), void *arg)
Benjamin Petersona54c9092009-01-13 02:11:23 +00001202
1203 .. index:: single: Py_AddPendingCall()
1204
Antoine Pitrou1a67bee2013-09-30 21:35:44 +02001205 Schedule a function to be called from the main interpreter thread. On
Serhiy Storchaka1ecf7d22016-10-27 21:41:19 +03001206 success, ``0`` is returned and *func* is queued for being called in the
1207 main thread. On failure, ``-1`` is returned without setting any exception.
Benjamin Petersona54c9092009-01-13 02:11:23 +00001208
Antoine Pitrou1a67bee2013-09-30 21:35:44 +02001209 When successfully queued, *func* will be *eventually* called from the
1210 main interpreter thread with the argument *arg*. It will be called
1211 asynchronously with respect to normally running Python code, but with
1212 both these conditions met:
Benjamin Petersona54c9092009-01-13 02:11:23 +00001213
Antoine Pitrou1a67bee2013-09-30 21:35:44 +02001214 * on a :term:`bytecode` boundary;
1215 * with the main thread holding the :term:`global interpreter lock`
1216 (*func* can therefore use the full C API).
1217
Serhiy Storchaka1ecf7d22016-10-27 21:41:19 +03001218 *func* must return ``0`` on success, or ``-1`` on failure with an exception
Antoine Pitrou1a67bee2013-09-30 21:35:44 +02001219 set. *func* won't be interrupted to perform another asynchronous
1220 notification recursively, but it can still be interrupted to switch
1221 threads if the global interpreter lock is released.
1222
1223 This function doesn't need a current thread state to run, and it doesn't
1224 need the global interpreter lock.
1225
1226 .. warning::
1227 This is a low-level function, only useful for very special cases.
1228 There is no guarantee that *func* will be called as quick as
1229 possible. If the main thread is busy executing a system call,
1230 *func* won't be called before the system call returns. This
1231 function is generally **not** suitable for calling Python code from
1232 arbitrary C threads. Instead, use the :ref:`PyGILState API<gilstate>`.
Benjamin Petersona54c9092009-01-13 02:11:23 +00001233
Georg Brandl705d9d52009-05-05 09:29:50 +00001234 .. versionadded:: 3.1
Benjamin Petersona54c9092009-01-13 02:11:23 +00001235
Georg Brandl116aa622007-08-15 14:28:22 +00001236.. _profiling:
1237
1238Profiling and Tracing
1239=====================
1240
1241.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
1242
1243
1244The Python interpreter provides some low-level support for attaching profiling
1245and execution tracing facilities. These are used for profiling, debugging, and
1246coverage analysis tools.
1247
Georg Brandle6bcc912008-05-12 18:05:20 +00001248This C interface allows the profiling or tracing code to avoid the overhead of
1249calling through Python-level callable objects, making a direct C function call
1250instead. The essential attributes of the facility have not changed; the
1251interface allows trace functions to be installed per-thread, and the basic
1252events reported to the trace function are the same as had been reported to the
1253Python-level trace functions in previous versions.
Georg Brandl116aa622007-08-15 14:28:22 +00001254
1255
Georg Brandl60203b42010-10-06 10:11:56 +00001256.. c:type:: int (*Py_tracefunc)(PyObject *obj, PyFrameObject *frame, int what, PyObject *arg)
Georg Brandl116aa622007-08-15 14:28:22 +00001257
Georg Brandl60203b42010-10-06 10:11:56 +00001258 The type of the trace function registered using :c:func:`PyEval_SetProfile` and
1259 :c:func:`PyEval_SetTrace`. The first parameter is the object passed to the
Georg Brandl116aa622007-08-15 14:28:22 +00001260 registration function as *obj*, *frame* is the frame object to which the event
1261 pertains, *what* is one of the constants :const:`PyTrace_CALL`,
1262 :const:`PyTrace_EXCEPTION`, :const:`PyTrace_LINE`, :const:`PyTrace_RETURN`,
Xiang Zhang255f7a22018-01-28 17:53:38 +08001263 :const:`PyTrace_C_CALL`, :const:`PyTrace_C_EXCEPTION`, :const:`PyTrace_C_RETURN`,
1264 or :const:`PyTrace_OPCODE`, and *arg* depends on the value of *what*:
Georg Brandl116aa622007-08-15 14:28:22 +00001265
1266 +------------------------------+--------------------------------------+
1267 | Value of *what* | Meaning of *arg* |
1268 +==============================+======================================+
Xiang Zhang9ed0aee2018-01-28 15:38:21 +08001269 | :const:`PyTrace_CALL` | Always :c:data:`Py_None`. |
Georg Brandl116aa622007-08-15 14:28:22 +00001270 +------------------------------+--------------------------------------+
1271 | :const:`PyTrace_EXCEPTION` | Exception information as returned by |
1272 | | :func:`sys.exc_info`. |
1273 +------------------------------+--------------------------------------+
Xiang Zhang9ed0aee2018-01-28 15:38:21 +08001274 | :const:`PyTrace_LINE` | Always :c:data:`Py_None`. |
Georg Brandl116aa622007-08-15 14:28:22 +00001275 +------------------------------+--------------------------------------+
Georg Brandld0b0e1d2010-10-15 16:42:37 +00001276 | :const:`PyTrace_RETURN` | Value being returned to the caller, |
1277 | | or *NULL* if caused by an exception. |
Georg Brandl116aa622007-08-15 14:28:22 +00001278 +------------------------------+--------------------------------------+
Georg Brandld0b0e1d2010-10-15 16:42:37 +00001279 | :const:`PyTrace_C_CALL` | Function object being called. |
Georg Brandl116aa622007-08-15 14:28:22 +00001280 +------------------------------+--------------------------------------+
Georg Brandld0b0e1d2010-10-15 16:42:37 +00001281 | :const:`PyTrace_C_EXCEPTION` | Function object being called. |
Georg Brandl116aa622007-08-15 14:28:22 +00001282 +------------------------------+--------------------------------------+
Georg Brandld0b0e1d2010-10-15 16:42:37 +00001283 | :const:`PyTrace_C_RETURN` | Function object being called. |
Georg Brandl116aa622007-08-15 14:28:22 +00001284 +------------------------------+--------------------------------------+
Xiang Zhang255f7a22018-01-28 17:53:38 +08001285 | :const:`PyTrace_OPCODE` | Always :c:data:`Py_None`. |
1286 +------------------------------+--------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00001287
Georg Brandl60203b42010-10-06 10:11:56 +00001288.. c:var:: int PyTrace_CALL
Georg Brandl116aa622007-08-15 14:28:22 +00001289
Georg Brandl60203b42010-10-06 10:11:56 +00001290 The value of the *what* parameter to a :c:type:`Py_tracefunc` function when a new
Georg Brandl116aa622007-08-15 14:28:22 +00001291 call to a function or method is being reported, or a new entry into a generator.
1292 Note that the creation of the iterator for a generator function is not reported
1293 as there is no control transfer to the Python bytecode in the corresponding
1294 frame.
1295
1296
Georg Brandl60203b42010-10-06 10:11:56 +00001297.. c:var:: int PyTrace_EXCEPTION
Georg Brandl116aa622007-08-15 14:28:22 +00001298
Georg Brandl60203b42010-10-06 10:11:56 +00001299 The value of the *what* parameter to a :c:type:`Py_tracefunc` function when an
Georg Brandl116aa622007-08-15 14:28:22 +00001300 exception has been raised. The callback function is called with this value for
1301 *what* when after any bytecode is processed after which the exception becomes
1302 set within the frame being executed. The effect of this is that as exception
1303 propagation causes the Python stack to unwind, the callback is called upon
1304 return to each frame as the exception propagates. Only trace functions receives
1305 these events; they are not needed by the profiler.
1306
1307
Georg Brandl60203b42010-10-06 10:11:56 +00001308.. c:var:: int PyTrace_LINE
Georg Brandl116aa622007-08-15 14:28:22 +00001309
Xiang Zhang255f7a22018-01-28 17:53:38 +08001310 The value passed as the *what* parameter to a :c:type:`Py_tracefunc` function
1311 (but not a profiling function) when a line-number event is being reported.
1312 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 +00001313
1314
Georg Brandl60203b42010-10-06 10:11:56 +00001315.. c:var:: int PyTrace_RETURN
Georg Brandl116aa622007-08-15 14:28:22 +00001316
Georg Brandl60203b42010-10-06 10:11:56 +00001317 The value for the *what* parameter to :c:type:`Py_tracefunc` functions when a
Xiang Zhang79db11c2018-01-28 22:54:42 +08001318 call is about to return.
Georg Brandl116aa622007-08-15 14:28:22 +00001319
1320
Georg Brandl60203b42010-10-06 10:11:56 +00001321.. c:var:: int PyTrace_C_CALL
Georg Brandl116aa622007-08-15 14:28:22 +00001322
Georg Brandl60203b42010-10-06 10:11:56 +00001323 The value for the *what* parameter to :c:type:`Py_tracefunc` functions when a C
Georg Brandl116aa622007-08-15 14:28:22 +00001324 function is about to be called.
1325
1326
Georg Brandl60203b42010-10-06 10:11:56 +00001327.. c:var:: int PyTrace_C_EXCEPTION
Georg Brandl116aa622007-08-15 14:28:22 +00001328
Georg Brandl60203b42010-10-06 10:11:56 +00001329 The value for the *what* parameter to :c:type:`Py_tracefunc` functions when a C
Georg Brandl7cb13192010-08-03 12:06:29 +00001330 function has raised an exception.
Georg Brandl116aa622007-08-15 14:28:22 +00001331
1332
Georg Brandl60203b42010-10-06 10:11:56 +00001333.. c:var:: int PyTrace_C_RETURN
Georg Brandl116aa622007-08-15 14:28:22 +00001334
Georg Brandl60203b42010-10-06 10:11:56 +00001335 The value for the *what* parameter to :c:type:`Py_tracefunc` functions when a C
Georg Brandl116aa622007-08-15 14:28:22 +00001336 function has returned.
1337
1338
Xiang Zhang255f7a22018-01-28 17:53:38 +08001339.. c:var:: int PyTrace_OPCODE
1340
1341 The value for the *what* parameter to :c:type:`Py_tracefunc` functions (but not
1342 profiling functions) when a new opcode is about to be executed. This event is
1343 not emitted by default: it must be explicitly requested by setting
1344 :attr:`f_trace_opcodes` to *1* on the frame.
1345
1346
Georg Brandl60203b42010-10-06 10:11:56 +00001347.. c:function:: void PyEval_SetProfile(Py_tracefunc func, PyObject *obj)
Georg Brandl116aa622007-08-15 14:28:22 +00001348
1349 Set the profiler function to *func*. The *obj* parameter is passed to the
1350 function as its first parameter, and may be any Python object, or *NULL*. If
1351 the profile function needs to maintain state, using a different value for *obj*
1352 for each thread provides a convenient and thread-safe place to store it. The
Pablo Galindo131fd7f2018-01-24 12:57:49 +00001353 profile function is called for all monitored events except :const:`PyTrace_LINE`
Xiang Zhang255f7a22018-01-28 17:53:38 +08001354 :const:`PyTrace_OPCODE` and :const:`PyTrace_EXCEPTION`.
Georg Brandl116aa622007-08-15 14:28:22 +00001355
1356
Georg Brandl60203b42010-10-06 10:11:56 +00001357.. c:function:: void PyEval_SetTrace(Py_tracefunc func, PyObject *obj)
Georg Brandl116aa622007-08-15 14:28:22 +00001358
1359 Set the tracing function to *func*. This is similar to
Georg Brandl60203b42010-10-06 10:11:56 +00001360 :c:func:`PyEval_SetProfile`, except the tracing function does receive line-number
Xiang Zhang255f7a22018-01-28 17:53:38 +08001361 events and per-opcode events, but does not receive any event related to C function
1362 objects being called. Any trace function registered using :c:func:`PyEval_SetTrace`
1363 will not receive :const:`PyTrace_C_CALL`, :const:`PyTrace_C_EXCEPTION` or
1364 :const:`PyTrace_C_RETURN` as a value for the *what* parameter.
Georg Brandl116aa622007-08-15 14:28:22 +00001365
1366.. _advanced-debugging:
1367
1368Advanced Debugger Support
1369=========================
1370
1371.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
1372
1373
1374These functions are only intended to be used by advanced debugging tools.
1375
1376
Georg Brandl60203b42010-10-06 10:11:56 +00001377.. c:function:: PyInterpreterState* PyInterpreterState_Head()
Georg Brandl116aa622007-08-15 14:28:22 +00001378
1379 Return the interpreter state object at the head of the list of all such objects.
1380
Georg Brandl116aa622007-08-15 14:28:22 +00001381
Georg Brandl60203b42010-10-06 10:11:56 +00001382.. c:function:: PyInterpreterState* PyInterpreterState_Next(PyInterpreterState *interp)
Georg Brandl116aa622007-08-15 14:28:22 +00001383
1384 Return the next interpreter state object after *interp* from the list of all
1385 such objects.
1386
Georg Brandl116aa622007-08-15 14:28:22 +00001387
Georg Brandl60203b42010-10-06 10:11:56 +00001388.. c:function:: PyThreadState * PyInterpreterState_ThreadHead(PyInterpreterState *interp)
Georg Brandl116aa622007-08-15 14:28:22 +00001389
Benjamin Peterson82f34ad2015-01-13 09:17:24 -05001390 Return the pointer to the first :c:type:`PyThreadState` object in the list of
Georg Brandl116aa622007-08-15 14:28:22 +00001391 threads associated with the interpreter *interp*.
1392
Georg Brandl116aa622007-08-15 14:28:22 +00001393
Georg Brandl60203b42010-10-06 10:11:56 +00001394.. c:function:: PyThreadState* PyThreadState_Next(PyThreadState *tstate)
Georg Brandl116aa622007-08-15 14:28:22 +00001395
1396 Return the next thread state object after *tstate* from the list of all such
Georg Brandl60203b42010-10-06 10:11:56 +00001397 objects belonging to the same :c:type:`PyInterpreterState` object.
Georg Brandl116aa622007-08-15 14:28:22 +00001398
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001399
1400.. _thread-local-storage:
1401
1402Thread Local Storage Support
1403============================
1404
1405.. sectionauthor:: Masayuki Yamamoto <ma3yuki.8mamo10@gmail.com>
1406
1407The Python interpreter provides low-level support for thread-local storage
1408(TLS) which wraps the underlying native TLS implementation to support the
1409Python-level thread local storage API (:class:`threading.local`). The
1410CPython C level APIs are similar to those offered by pthreads and Windows:
1411use a thread key and functions to associate a :c:type:`void\*` value per
1412thread.
1413
1414The GIL does *not* need to be held when calling these functions; they supply
1415their own locking.
1416
1417Note that :file:`Python.h` does not include the declaration of the TLS APIs,
1418you need to include :file:`pythread.h` to use thread-local storage.
1419
1420.. note::
1421 None of these API functions handle memory management on behalf of the
1422 :c:type:`void\*` values. You need to allocate and deallocate them yourself.
1423 If the :c:type:`void\*` values happen to be :c:type:`PyObject\*`, these
1424 functions don't do refcount operations on them either.
1425
1426.. _thread-specific-storage-api:
1427
1428Thread Specific Storage (TSS) API
1429---------------------------------
1430
1431TSS API is introduced to supersede the use of the existing TLS API within the
1432CPython interpreter. This API uses a new type :c:type:`Py_tss_t` instead of
1433:c:type:`int` to represent thread keys.
1434
1435.. versionadded:: 3.7
1436
1437.. seealso:: "A New C-API for Thread-Local Storage in CPython" (:pep:`539`)
1438
1439
1440.. c:type:: Py_tss_t
1441
1442 This data structure represents the state of a thread key, the definition of
1443 which may depend on the underlying TLS implementation, and it has an
1444 internal field representing the key's initialization state. There are no
1445 public members in this structure.
1446
1447 When :ref:`Py_LIMITED_API <stable>` is not defined, static allocation of
1448 this type by :c:macro:`Py_tss_NEEDS_INIT` is allowed.
1449
1450
1451.. c:macro:: Py_tss_NEEDS_INIT
1452
Masayuki Yamamoto831d61d2017-10-24 21:58:16 +09001453 This macro expands to the initializer for :c:type:`Py_tss_t` variables.
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001454 Note that this macro won't be defined with :ref:`Py_LIMITED_API <stable>`.
1455
1456
1457Dynamic Allocation
1458~~~~~~~~~~~~~~~~~~
1459
1460Dynamic allocation of the :c:type:`Py_tss_t`, required in extension modules
1461built with :ref:`Py_LIMITED_API <stable>`, where static allocation of this type
1462is not possible due to its implementation being opaque at build time.
1463
1464
1465.. c:function:: Py_tss_t* PyThread_tss_alloc()
1466
1467 Return a value which is the same state as a value initialized with
1468 :c:macro:`Py_tss_NEEDS_INIT`, or *NULL* in the case of dynamic allocation
1469 failure.
1470
1471
1472.. c:function:: void PyThread_tss_free(Py_tss_t *key)
1473
1474 Free the given *key* allocated by :c:func:`PyThread_tss_alloc`, after
1475 first calling :c:func:`PyThread_tss_delete` to ensure any associated
1476 thread locals have been unassigned. This is a no-op if the *key*
1477 argument is `NULL`.
1478
1479 .. note::
1480 A freed key becomes a dangling pointer, you should reset the key to
1481 `NULL`.
1482
1483
1484Methods
1485~~~~~~~
1486
1487The parameter *key* of these functions must not be *NULL*. Moreover, the
1488behaviors of :c:func:`PyThread_tss_set` and :c:func:`PyThread_tss_get` are
1489undefined if the given :c:type:`Py_tss_t` has not been initialized by
1490:c:func:`PyThread_tss_create`.
1491
1492
1493.. c:function:: int PyThread_tss_is_created(Py_tss_t *key)
1494
1495 Return a non-zero value if the given :c:type:`Py_tss_t` has been initialized
1496 by :c:func:`PyThread_tss_create`.
1497
1498
1499.. c:function:: int PyThread_tss_create(Py_tss_t *key)
1500
1501 Return a zero value on successful initialization of a TSS key. The behavior
1502 is undefined if the value pointed to by the *key* argument is not
1503 initialized by :c:macro:`Py_tss_NEEDS_INIT`. This function can be called
1504 repeatedly on the same key -- calling it on an already initialized key is a
1505 no-op and immediately returns success.
1506
1507
1508.. c:function:: void PyThread_tss_delete(Py_tss_t *key)
1509
1510 Destroy a TSS key to forget the values associated with the key across all
1511 threads, and change the key's initialization state to uninitialized. A
1512 destroyed key is able to be initialized again by
1513 :c:func:`PyThread_tss_create`. This function can be called repeatedly on
1514 the same key -- calling it on an already destroyed key is a no-op.
1515
1516
1517.. c:function:: int PyThread_tss_set(Py_tss_t *key, void *value)
1518
1519 Return a zero value to indicate successfully associating a :c:type:`void\*`
1520 value with a TSS key in the current thread. Each thread has a distinct
1521 mapping of the key to a :c:type:`void\*` value.
1522
1523
1524.. c:function:: void* PyThread_tss_get(Py_tss_t *key)
1525
1526 Return the :c:type:`void\*` value associated with a TSS key in the current
1527 thread. This returns *NULL* if no value is associated with the key in the
1528 current thread.
1529
1530
1531.. _thread-local-storage-api:
1532
1533Thread Local Storage (TLS) API
1534------------------------------
1535
1536.. deprecated:: 3.7
1537 This API is superseded by
1538 :ref:`Thread Specific Storage (TSS) API <thread-specific-storage-api>`.
1539
1540.. note::
1541 This version of the API does not support platforms where the native TLS key
1542 is defined in a way that cannot be safely cast to ``int``. On such platforms,
1543 :c:func:`PyThread_create_key` will return immediately with a failure status,
1544 and the other TLS functions will all be no-ops on such platforms.
1545
1546Due to the compatibility problem noted above, this version of the API should not
1547be used in new code.
1548
1549.. c:function:: int PyThread_create_key()
1550.. c:function:: void PyThread_delete_key(int key)
1551.. c:function:: int PyThread_set_key_value(int key, void *value)
1552.. c:function:: void* PyThread_get_key_value(int key)
1553.. c:function:: void PyThread_delete_key_value(int key)
1554.. c:function:: void PyThread_ReInitTLS()
1555