blob: b30649498a92ac412b40d953527d2acf55464cfc [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001.. highlightlang:: c
2
3
4.. _initialization:
5
6*****************************************
7Initialization, Finalization, and Threads
8*****************************************
9
Victor Stinner84c4b192017-11-24 22:30:27 +010010.. _pre-init-safe:
11
12Before Python Initialization
13============================
14
15In an application embedding Python, the :c:func:`Py_Initialize` function must
16be called before using any other Python/C API functions; with the exception of
17a few functions and the :ref:`global configuration variables
18<global-conf-vars>`.
19
20The following functions can be safely called before Python is initialized:
21
22* Configuration functions:
23
24 * :c:func:`PyImport_AppendInittab`
25 * :c:func:`PyImport_ExtendInittab`
26 * :c:func:`PyInitFrozenExtensions`
27 * :c:func:`PyMem_SetAllocator`
28 * :c:func:`PyMem_SetupDebugHooks`
29 * :c:func:`PyObject_SetArenaAllocator`
30 * :c:func:`Py_SetPath`
31 * :c:func:`Py_SetProgramName`
32 * :c:func:`Py_SetPythonHome`
33 * :c:func:`Py_SetStandardStreamEncoding`
Nick Coghlanbc77eff2018-03-25 20:44:30 +100034 * :c:func:`PySys_AddWarnOption`
35 * :c:func:`PySys_AddXOption`
36 * :c:func:`PySys_ResetWarnOptions`
Victor Stinner84c4b192017-11-24 22:30:27 +010037
38* Informative functions:
39
Nick Coghlanddbb9782019-03-30 21:24:05 +100040 * :c:func:`Py_IsInitialized`
Victor Stinner84c4b192017-11-24 22:30:27 +010041 * :c:func:`PyMem_GetAllocator`
42 * :c:func:`PyObject_GetArenaAllocator`
43 * :c:func:`Py_GetBuildInfo`
44 * :c:func:`Py_GetCompiler`
45 * :c:func:`Py_GetCopyright`
46 * :c:func:`Py_GetPlatform`
Victor Stinner84c4b192017-11-24 22:30:27 +010047 * :c:func:`Py_GetVersion`
48
49* Utilities:
50
51 * :c:func:`Py_DecodeLocale`
52
53* Memory allocators:
54
55 * :c:func:`PyMem_RawMalloc`
56 * :c:func:`PyMem_RawRealloc`
57 * :c:func:`PyMem_RawCalloc`
58 * :c:func:`PyMem_RawFree`
59
60.. note::
61
62 The following functions **should not be called** before
63 :c:func:`Py_Initialize`: :c:func:`Py_EncodeLocale`, :c:func:`Py_GetPath`,
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +010064 :c:func:`Py_GetPrefix`, :c:func:`Py_GetExecPrefix`,
Victor Stinner31a83932017-12-04 13:39:15 +010065 :c:func:`Py_GetProgramFullPath`, :c:func:`Py_GetPythonHome`,
66 :c:func:`Py_GetProgramName` and :c:func:`PyEval_InitThreads`.
Victor Stinner84c4b192017-11-24 22:30:27 +010067
68
69.. _global-conf-vars:
70
71Global configuration variables
72==============================
73
74Python has variables for the global configuration to control different features
75and options. By default, these flags are controlled by :ref:`command line
76options <using-on-interface-options>`.
77
78When a flag is set by an option, the value of the flag is the number of times
79that the option was set. For example, ``-b`` sets :c:data:`Py_BytesWarningFlag`
80to 1 and ``-bb`` sets :c:data:`Py_BytesWarningFlag` to 2.
81
82.. c:var:: Py_BytesWarningFlag
83
84 Issue a warning when comparing :class:`bytes` or :class:`bytearray` with
85 :class:`str` or :class:`bytes` with :class:`int`. Issue an error if greater
86 or equal to ``2``.
87
88 Set by the :option:`-b` option.
89
90.. c:var:: Py_DebugFlag
91
92 Turn on parser debugging output (for expert only, depending on compilation
93 options).
94
95 Set by the :option:`-d` option and the :envvar:`PYTHONDEBUG` environment
96 variable.
97
98.. c:var:: Py_DontWriteBytecodeFlag
99
100 If set to non-zero, Python won't try to write ``.pyc`` files on the
101 import of source modules.
102
103 Set by the :option:`-B` option and the :envvar:`PYTHONDONTWRITEBYTECODE`
104 environment variable.
105
106.. c:var:: Py_FrozenFlag
107
108 Suppress error messages when calculating the module search path in
109 :c:func:`Py_GetPath`.
110
111 Private flag used by ``_freeze_importlib`` and ``frozenmain`` programs.
112
113.. c:var:: Py_HashRandomizationFlag
114
115 Set to ``1`` if the :envvar:`PYTHONHASHSEED` environment variable is set to
116 a non-empty string.
117
118 If the flag is non-zero, read the :envvar:`PYTHONHASHSEED` environment
119 variable to initialize the secret hash seed.
120
121.. c:var:: Py_IgnoreEnvironmentFlag
122
123 Ignore all :envvar:`PYTHON*` environment variables, e.g.
124 :envvar:`PYTHONPATH` and :envvar:`PYTHONHOME`, that might be set.
125
126 Set by the :option:`-E` and :option:`-I` options.
127
128.. c:var:: Py_InspectFlag
129
130 When a script is passed as first argument or the :option:`-c` option is used,
131 enter interactive mode after executing the script or the command, even when
132 :data:`sys.stdin` does not appear to be a terminal.
133
134 Set by the :option:`-i` option and the :envvar:`PYTHONINSPECT` environment
135 variable.
136
137.. c:var:: Py_InteractiveFlag
138
139 Set by the :option:`-i` option.
140
141.. c:var:: Py_IsolatedFlag
142
143 Run Python in isolated mode. In isolated mode :data:`sys.path` contains
144 neither the script's directory nor the user's site-packages directory.
145
146 Set by the :option:`-I` option.
147
148 .. versionadded:: 3.4
149
150.. c:var:: Py_LegacyWindowsFSEncodingFlag
151
152 If the flag is non-zero, use the ``mbcs`` encoding instead of the UTF-8
153 encoding for the filesystem encoding.
154
155 Set to ``1`` if the :envvar:`PYTHONLEGACYWINDOWSFSENCODING` environment
156 variable is set to a non-empty string.
157
158 See :pep:`529` for more details.
159
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400160 .. availability:: Windows.
Victor Stinner84c4b192017-11-24 22:30:27 +0100161
162.. c:var:: Py_LegacyWindowsStdioFlag
163
164 If the flag is non-zero, use :class:`io.FileIO` instead of
165 :class:`WindowsConsoleIO` for :mod:`sys` standard streams.
166
167 Set to ``1`` if the :envvar:`PYTHONLEGACYWINDOWSSTDIO` environment
168 variable is set to a non-empty string.
169
170 See :pep:`528` for more details.
171
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400172 .. availability:: Windows.
Victor Stinner84c4b192017-11-24 22:30:27 +0100173
174.. c:var:: Py_NoSiteFlag
175
176 Disable the import of the module :mod:`site` and the site-dependent
177 manipulations of :data:`sys.path` that it entails. Also disable these
178 manipulations if :mod:`site` is explicitly imported later (call
179 :func:`site.main` if you want them to be triggered).
180
181 Set by the :option:`-S` option.
182
183.. c:var:: Py_NoUserSiteDirectory
184
185 Don't add the :data:`user site-packages directory <site.USER_SITE>` to
186 :data:`sys.path`.
187
188 Set by the :option:`-s` and :option:`-I` options, and the
189 :envvar:`PYTHONNOUSERSITE` environment variable.
190
191.. c:var:: Py_OptimizeFlag
192
193 Set by the :option:`-O` option and the :envvar:`PYTHONOPTIMIZE` environment
194 variable.
195
196.. c:var:: Py_QuietFlag
197
198 Don't display the copyright and version messages even in interactive mode.
199
200 Set by the :option:`-q` option.
201
202 .. versionadded:: 3.2
203
204.. c:var:: Py_UnbufferedStdioFlag
205
206 Force the stdout and stderr streams to be unbuffered.
207
208 Set by the :option:`-u` option and the :envvar:`PYTHONUNBUFFERED`
209 environment variable.
210
211.. c:var:: Py_VerboseFlag
212
213 Print a message each time a module is initialized, showing the place
214 (filename or built-in module) from which it is loaded. If greater or equal
215 to ``2``, print a message for each file that is checked for when
216 searching for a module. Also provides information on module cleanup at exit.
217
218 Set by the :option:`-v` option and the :envvar:`PYTHONVERBOSE` environment
219 variable.
220
Georg Brandl116aa622007-08-15 14:28:22 +0000221
Antoine Pitrou8b50b832011-01-15 11:57:42 +0000222Initializing and finalizing the interpreter
223===========================================
224
225
Georg Brandl60203b42010-10-06 10:11:56 +0000226.. c:function:: void Py_Initialize()
Georg Brandl116aa622007-08-15 14:28:22 +0000227
228 .. index::
229 single: Py_SetProgramName()
230 single: PyEval_InitThreads()
Georg Brandl116aa622007-08-15 14:28:22 +0000231 single: modules (in module sys)
232 single: path (in module sys)
Georg Brandl1a3284e2007-12-02 09:40:06 +0000233 module: builtins
Georg Brandl116aa622007-08-15 14:28:22 +0000234 module: __main__
235 module: sys
236 triple: module; search; path
237 single: PySys_SetArgv()
Antoine Pitrouf978fac2010-05-21 17:25:34 +0000238 single: PySys_SetArgvEx()
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000239 single: Py_FinalizeEx()
Georg Brandl116aa622007-08-15 14:28:22 +0000240
Victor Stinner84c4b192017-11-24 22:30:27 +0100241 Initialize the Python interpreter. In an application embedding Python,
242 this should be called before using any other Python/C API functions; see
243 :ref:`Before Python Initialization <pre-init-safe>` for the few exceptions.
244
245 This initializes
Georg Brandl116aa622007-08-15 14:28:22 +0000246 the table of loaded modules (``sys.modules``), and creates the fundamental
Georg Brandl1a3284e2007-12-02 09:40:06 +0000247 modules :mod:`builtins`, :mod:`__main__` and :mod:`sys`. It also initializes
Georg Brandl116aa622007-08-15 14:28:22 +0000248 the module search path (``sys.path``). It does not set ``sys.argv``; use
Georg Brandl60203b42010-10-06 10:11:56 +0000249 :c:func:`PySys_SetArgvEx` for that. This is a no-op when called for a second time
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000250 (without calling :c:func:`Py_FinalizeEx` first). There is no return value; it is a
Georg Brandl116aa622007-08-15 14:28:22 +0000251 fatal error if the initialization fails.
252
Steve Dowerde02b082016-09-09 11:46:37 -0700253 .. note::
254 On Windows, changes the console mode from ``O_TEXT`` to ``O_BINARY``, which will
255 also affect non-Python uses of the console using the C Runtime.
256
Georg Brandl116aa622007-08-15 14:28:22 +0000257
Georg Brandl60203b42010-10-06 10:11:56 +0000258.. c:function:: void Py_InitializeEx(int initsigs)
Georg Brandl116aa622007-08-15 14:28:22 +0000259
Serhiy Storchaka1ecf7d22016-10-27 21:41:19 +0300260 This function works like :c:func:`Py_Initialize` if *initsigs* is ``1``. If
261 *initsigs* is ``0``, it skips initialization registration of signal handlers, which
Georg Brandl116aa622007-08-15 14:28:22 +0000262 might be useful when Python is embedded.
263
Georg Brandl116aa622007-08-15 14:28:22 +0000264
Georg Brandl60203b42010-10-06 10:11:56 +0000265.. c:function:: int Py_IsInitialized()
Georg Brandl116aa622007-08-15 14:28:22 +0000266
267 Return true (nonzero) when the Python interpreter has been initialized, false
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000268 (zero) if not. After :c:func:`Py_FinalizeEx` is called, this returns false until
Georg Brandl60203b42010-10-06 10:11:56 +0000269 :c:func:`Py_Initialize` is called again.
Georg Brandl116aa622007-08-15 14:28:22 +0000270
271
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000272.. c:function:: int Py_FinalizeEx()
Georg Brandl116aa622007-08-15 14:28:22 +0000273
Georg Brandl60203b42010-10-06 10:11:56 +0000274 Undo all initializations made by :c:func:`Py_Initialize` and subsequent use of
Georg Brandl116aa622007-08-15 14:28:22 +0000275 Python/C API functions, and destroy all sub-interpreters (see
Georg Brandl60203b42010-10-06 10:11:56 +0000276 :c:func:`Py_NewInterpreter` below) that were created and not yet destroyed since
277 the last call to :c:func:`Py_Initialize`. Ideally, this frees all memory
Georg Brandl116aa622007-08-15 14:28:22 +0000278 allocated by the Python interpreter. This is a no-op when called for a second
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000279 time (without calling :c:func:`Py_Initialize` again first). Normally the
Serhiy Storchaka5bb00052018-02-09 13:31:19 +0200280 return value is ``0``. If there were errors during finalization
281 (flushing buffered data), ``-1`` is returned.
Georg Brandl116aa622007-08-15 14:28:22 +0000282
283 This function is provided for a number of reasons. An embedding application
284 might want to restart Python without having to restart the application itself.
285 An application that has loaded the Python interpreter from a dynamically
286 loadable library (or DLL) might want to free all memory allocated by Python
287 before unloading the DLL. During a hunt for memory leaks in an application a
288 developer might want to free all memory allocated by Python before exiting from
289 the application.
290
291 **Bugs and caveats:** The destruction of modules and objects in modules is done
292 in random order; this may cause destructors (:meth:`__del__` methods) to fail
293 when they depend on other objects (even functions) or modules. Dynamically
294 loaded extension modules loaded by Python are not unloaded. Small amounts of
295 memory allocated by the Python interpreter may not be freed (if you find a leak,
296 please report it). Memory tied up in circular references between objects is not
297 freed. Some memory allocated by extension modules may not be freed. Some
298 extensions may not work properly if their initialization routine is called more
Georg Brandl60203b42010-10-06 10:11:56 +0000299 than once; this can happen if an application calls :c:func:`Py_Initialize` and
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000300 :c:func:`Py_FinalizeEx` more than once.
301
302 .. versionadded:: 3.6
303
304
305.. c:function:: void Py_Finalize()
306
307 This is a backwards-compatible version of :c:func:`Py_FinalizeEx` that
308 disregards the return value.
Georg Brandl116aa622007-08-15 14:28:22 +0000309
310
Antoine Pitrou8b50b832011-01-15 11:57:42 +0000311Process-wide parameters
312=======================
Georg Brandl116aa622007-08-15 14:28:22 +0000313
314
Serhiy Storchaka03863d22015-06-21 17:11:21 +0300315.. c:function:: int Py_SetStandardStreamEncoding(const char *encoding, const char *errors)
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000316
317 .. index::
318 single: Py_Initialize()
319 single: main()
320 triple: stdin; stdout; sdterr
321
Nick Coghlan1805a622013-10-18 23:11:47 +1000322 This function should be called before :c:func:`Py_Initialize`, if it is
323 called at all. It specifies which encoding and error handling to use
324 with standard IO, with the same meanings as in :func:`str.encode`.
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000325
326 It overrides :envvar:`PYTHONIOENCODING` values, and allows embedding code
Nick Coghlan1805a622013-10-18 23:11:47 +1000327 to control IO encoding when the environment variable does not work.
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000328
329 ``encoding`` and/or ``errors`` may be NULL to use
330 :envvar:`PYTHONIOENCODING` and/or default values (depending on other
331 settings).
332
333 Note that :data:`sys.stderr` always uses the "backslashreplace" error
334 handler, regardless of this (or any other) setting.
335
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000336 If :c:func:`Py_FinalizeEx` is called, this function will need to be called
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000337 again in order to affect subsequent calls to :c:func:`Py_Initialize`.
338
Serhiy Storchaka1ecf7d22016-10-27 21:41:19 +0300339 Returns ``0`` if successful, a nonzero value on error (e.g. calling after the
Nick Coghlan1805a622013-10-18 23:11:47 +1000340 interpreter has already been initialized).
341
342 .. versionadded:: 3.4
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000343
344
Serhiy Storchaka4ae06c52017-12-12 13:55:04 +0200345.. c:function:: void Py_SetProgramName(const wchar_t *name)
Georg Brandl116aa622007-08-15 14:28:22 +0000346
347 .. index::
348 single: Py_Initialize()
349 single: main()
350 single: Py_GetPath()
351
Georg Brandl60203b42010-10-06 10:11:56 +0000352 This function should be called before :c:func:`Py_Initialize` is called for
Georg Brandl116aa622007-08-15 14:28:22 +0000353 the first time, if it is called at all. It tells the interpreter the value
Georg Brandl60203b42010-10-06 10:11:56 +0000354 of the ``argv[0]`` argument to the :c:func:`main` function of the program
Martin v. Löwis790465f2008-04-05 20:41:37 +0000355 (converted to wide characters).
Georg Brandl60203b42010-10-06 10:11:56 +0000356 This is used by :c:func:`Py_GetPath` and some other functions below to find
Georg Brandl116aa622007-08-15 14:28:22 +0000357 the Python run-time libraries relative to the interpreter executable. The
358 default value is ``'python'``. The argument should point to a
Martin v. Löwis790465f2008-04-05 20:41:37 +0000359 zero-terminated wide character string in static storage whose contents will not
Georg Brandl116aa622007-08-15 14:28:22 +0000360 change for the duration of the program's execution. No code in the Python
361 interpreter will change the contents of this storage.
362
Victor Stinner25e014b2014-08-01 12:28:49 +0200363 Use :c:func:`Py_DecodeLocale` to decode a bytes string to get a
364 :c:type:`wchar_*` string.
365
Georg Brandl116aa622007-08-15 14:28:22 +0000366
Georg Brandl60203b42010-10-06 10:11:56 +0000367.. c:function:: wchar* Py_GetProgramName()
Georg Brandl116aa622007-08-15 14:28:22 +0000368
369 .. index:: single: Py_SetProgramName()
370
Georg Brandl60203b42010-10-06 10:11:56 +0000371 Return the program name set with :c:func:`Py_SetProgramName`, or the default.
Georg Brandl116aa622007-08-15 14:28:22 +0000372 The returned string points into static storage; the caller should not modify its
373 value.
374
375
Georg Brandl60203b42010-10-06 10:11:56 +0000376.. c:function:: wchar_t* Py_GetPrefix()
Georg Brandl116aa622007-08-15 14:28:22 +0000377
378 Return the *prefix* for installed platform-independent files. This is derived
379 through a number of complicated rules from the program name set with
Georg Brandl60203b42010-10-06 10:11:56 +0000380 :c:func:`Py_SetProgramName` and some environment variables; for example, if the
Georg Brandl116aa622007-08-15 14:28:22 +0000381 program name is ``'/usr/local/bin/python'``, the prefix is ``'/usr/local'``. The
382 returned string points into static storage; the caller should not modify its
383 value. This corresponds to the :makevar:`prefix` variable in the top-level
Éric Araujo37b5f9e2011-09-01 03:19:30 +0200384 :file:`Makefile` and the ``--prefix`` argument to the :program:`configure`
Georg Brandl116aa622007-08-15 14:28:22 +0000385 script at build time. The value is available to Python code as ``sys.prefix``.
386 It is only useful on Unix. See also the next function.
387
388
Georg Brandl60203b42010-10-06 10:11:56 +0000389.. c:function:: wchar_t* Py_GetExecPrefix()
Georg Brandl116aa622007-08-15 14:28:22 +0000390
391 Return the *exec-prefix* for installed platform-*dependent* files. This is
392 derived through a number of complicated rules from the program name set with
Georg Brandl60203b42010-10-06 10:11:56 +0000393 :c:func:`Py_SetProgramName` and some environment variables; for example, if the
Georg Brandl116aa622007-08-15 14:28:22 +0000394 program name is ``'/usr/local/bin/python'``, the exec-prefix is
395 ``'/usr/local'``. The returned string points into static storage; the caller
396 should not modify its value. This corresponds to the :makevar:`exec_prefix`
Éric Araujo37b5f9e2011-09-01 03:19:30 +0200397 variable in the top-level :file:`Makefile` and the ``--exec-prefix``
Georg Brandl116aa622007-08-15 14:28:22 +0000398 argument to the :program:`configure` script at build time. The value is
399 available to Python code as ``sys.exec_prefix``. It is only useful on Unix.
400
401 Background: The exec-prefix differs from the prefix when platform dependent
402 files (such as executables and shared libraries) are installed in a different
403 directory tree. In a typical installation, platform dependent files may be
404 installed in the :file:`/usr/local/plat` subtree while platform independent may
405 be installed in :file:`/usr/local`.
406
407 Generally speaking, a platform is a combination of hardware and software
408 families, e.g. Sparc machines running the Solaris 2.x operating system are
409 considered the same platform, but Intel machines running Solaris 2.x are another
410 platform, and Intel machines running Linux are yet another platform. Different
411 major revisions of the same operating system generally also form different
412 platforms. Non-Unix operating systems are a different story; the installation
413 strategies on those systems are so different that the prefix and exec-prefix are
414 meaningless, and set to the empty string. Note that compiled Python bytecode
415 files are platform independent (but not independent from the Python version by
416 which they were compiled!).
417
418 System administrators will know how to configure the :program:`mount` or
419 :program:`automount` programs to share :file:`/usr/local` between platforms
420 while having :file:`/usr/local/plat` be a different filesystem for each
421 platform.
422
423
Georg Brandl60203b42010-10-06 10:11:56 +0000424.. c:function:: wchar_t* Py_GetProgramFullPath()
Georg Brandl116aa622007-08-15 14:28:22 +0000425
426 .. index::
427 single: Py_SetProgramName()
428 single: executable (in module sys)
429
430 Return the full program name of the Python executable; this is computed as a
431 side-effect of deriving the default module search path from the program name
Georg Brandl60203b42010-10-06 10:11:56 +0000432 (set by :c:func:`Py_SetProgramName` above). The returned string points into
Georg Brandl116aa622007-08-15 14:28:22 +0000433 static storage; the caller should not modify its value. The value is available
434 to Python code as ``sys.executable``.
435
436
Georg Brandl60203b42010-10-06 10:11:56 +0000437.. c:function:: wchar_t* Py_GetPath()
Georg Brandl116aa622007-08-15 14:28:22 +0000438
439 .. index::
440 triple: module; search; path
441 single: path (in module sys)
Kristján Valur Jónsson3b69db22010-09-27 05:32:54 +0000442 single: Py_SetPath()
Georg Brandl116aa622007-08-15 14:28:22 +0000443
Benjamin Peterson46a99002010-01-09 18:45:30 +0000444 Return the default module search path; this is computed from the program name
Georg Brandl60203b42010-10-06 10:11:56 +0000445 (set by :c:func:`Py_SetProgramName` above) and some environment variables.
Benjamin Peterson46a99002010-01-09 18:45:30 +0000446 The returned string consists of a series of directory names separated by a
447 platform dependent delimiter character. The delimiter character is ``':'``
448 on Unix and Mac OS X, ``';'`` on Windows. The returned string points into
449 static storage; the caller should not modify its value. The list
450 :data:`sys.path` is initialized with this value on interpreter startup; it
451 can be (and usually is) modified later to change the search path for loading
452 modules.
Georg Brandl116aa622007-08-15 14:28:22 +0000453
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000454 .. XXX should give the exact rules
Georg Brandl116aa622007-08-15 14:28:22 +0000455
456
Georg Brandl60203b42010-10-06 10:11:56 +0000457.. c:function:: void Py_SetPath(const wchar_t *)
Kristján Valur Jónsson3b69db22010-09-27 05:32:54 +0000458
459 .. index::
460 triple: module; search; path
461 single: path (in module sys)
462 single: Py_GetPath()
463
464 Set the default module search path. If this function is called before
Georg Brandlfa4f7f92010-10-06 10:14:08 +0000465 :c:func:`Py_Initialize`, then :c:func:`Py_GetPath` won't attempt to compute a
466 default search path but uses the one provided instead. This is useful if
467 Python is embedded by an application that has full knowledge of the location
Georg Brandle8ea3552014-10-11 14:36:02 +0200468 of all modules. The path components should be separated by the platform
469 dependent delimiter character, which is ``':'`` on Unix and Mac OS X, ``';'``
470 on Windows.
Kristján Valur Jónsson3b69db22010-09-27 05:32:54 +0000471
Georg Brandlfa4f7f92010-10-06 10:14:08 +0000472 This also causes :data:`sys.executable` to be set only to the raw program
473 name (see :c:func:`Py_SetProgramName`) and for :data:`sys.prefix` and
474 :data:`sys.exec_prefix` to be empty. It is up to the caller to modify these
475 if required after calling :c:func:`Py_Initialize`.
476
Victor Stinner25e014b2014-08-01 12:28:49 +0200477 Use :c:func:`Py_DecodeLocale` to decode a bytes string to get a
478 :c:type:`wchar_*` string.
479
Benjamin Petersonb33bb892014-12-24 10:49:11 -0600480 The path argument is copied internally, so the caller may free it after the
481 call completes.
482
Kristján Valur Jónsson3b69db22010-09-27 05:32:54 +0000483
Georg Brandl60203b42010-10-06 10:11:56 +0000484.. c:function:: const char* Py_GetVersion()
Georg Brandl116aa622007-08-15 14:28:22 +0000485
486 Return the version of this Python interpreter. This is a string that looks
487 something like ::
488
Georg Brandle6bcc912008-05-12 18:05:20 +0000489 "3.0a5+ (py3k:63103M, May 12 2008, 00:53:55) \n[GCC 4.2.3]"
Georg Brandl116aa622007-08-15 14:28:22 +0000490
491 .. index:: single: version (in module sys)
492
493 The first word (up to the first space character) is the current Python version;
494 the first three characters are the major and minor version separated by a
495 period. The returned string points into static storage; the caller should not
Georg Brandle6bcc912008-05-12 18:05:20 +0000496 modify its value. The value is available to Python code as :data:`sys.version`.
Georg Brandl116aa622007-08-15 14:28:22 +0000497
498
Georg Brandl60203b42010-10-06 10:11:56 +0000499.. c:function:: const char* Py_GetPlatform()
Georg Brandl116aa622007-08-15 14:28:22 +0000500
501 .. index:: single: platform (in module sys)
502
503 Return the platform identifier for the current platform. On Unix, this is
504 formed from the "official" name of the operating system, converted to lower
505 case, followed by the major revision number; e.g., for Solaris 2.x, which is
506 also known as SunOS 5.x, the value is ``'sunos5'``. On Mac OS X, it is
507 ``'darwin'``. On Windows, it is ``'win'``. The returned string points into
508 static storage; the caller should not modify its value. The value is available
509 to Python code as ``sys.platform``.
510
511
Georg Brandl60203b42010-10-06 10:11:56 +0000512.. c:function:: const char* Py_GetCopyright()
Georg Brandl116aa622007-08-15 14:28:22 +0000513
514 Return the official copyright string for the current Python version, for example
515
516 ``'Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam'``
517
518 .. index:: single: copyright (in module sys)
519
520 The returned string points into static storage; the caller should not modify its
521 value. The value is available to Python code as ``sys.copyright``.
522
523
Georg Brandl60203b42010-10-06 10:11:56 +0000524.. c:function:: const char* Py_GetCompiler()
Georg Brandl116aa622007-08-15 14:28:22 +0000525
526 Return an indication of the compiler used to build the current Python version,
527 in square brackets, for example::
528
529 "[GCC 2.7.2.2]"
530
531 .. index:: single: version (in module sys)
532
533 The returned string points into static storage; the caller should not modify its
534 value. The value is available to Python code as part of the variable
535 ``sys.version``.
536
537
Georg Brandl60203b42010-10-06 10:11:56 +0000538.. c:function:: const char* Py_GetBuildInfo()
Georg Brandl116aa622007-08-15 14:28:22 +0000539
540 Return information about the sequence number and build date and time of the
541 current Python interpreter instance, for example ::
542
543 "#67, Aug 1 1997, 22:34:28"
544
545 .. index:: single: version (in module sys)
546
547 The returned string points into static storage; the caller should not modify its
548 value. The value is available to Python code as part of the variable
549 ``sys.version``.
550
551
Georg Brandl60203b42010-10-06 10:11:56 +0000552.. c:function:: void PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
Georg Brandl116aa622007-08-15 14:28:22 +0000553
554 .. index::
555 single: main()
556 single: Py_FatalError()
557 single: argv (in module sys)
558
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000559 Set :data:`sys.argv` based on *argc* and *argv*. These parameters are
Georg Brandl60203b42010-10-06 10:11:56 +0000560 similar to those passed to the program's :c:func:`main` function with the
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000561 difference that the first entry should refer to the script file to be
562 executed rather than the executable hosting the Python interpreter. If there
563 isn't a script that will be run, the first entry in *argv* can be an empty
564 string. If this function fails to initialize :data:`sys.argv`, a fatal
Georg Brandl60203b42010-10-06 10:11:56 +0000565 condition is signalled using :c:func:`Py_FatalError`.
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000566
Antoine Pitrouf978fac2010-05-21 17:25:34 +0000567 If *updatepath* is zero, this is all the function does. If *updatepath*
568 is non-zero, the function also modifies :data:`sys.path` according to the
569 following algorithm:
570
571 - If the name of an existing script is passed in ``argv[0]``, the absolute
572 path of the directory where the script is located is prepended to
573 :data:`sys.path`.
Serhiy Storchaka1ecf7d22016-10-27 21:41:19 +0300574 - Otherwise (that is, if *argc* is ``0`` or ``argv[0]`` doesn't point
Antoine Pitrouf978fac2010-05-21 17:25:34 +0000575 to an existing file name), an empty string is prepended to
576 :data:`sys.path`, which is the same as prepending the current working
577 directory (``"."``).
578
Victor Stinner25e014b2014-08-01 12:28:49 +0200579 Use :c:func:`Py_DecodeLocale` to decode a bytes string to get a
580 :c:type:`wchar_*` string.
581
Antoine Pitrouf978fac2010-05-21 17:25:34 +0000582 .. note::
583 It is recommended that applications embedding the Python interpreter
Serhiy Storchaka1ecf7d22016-10-27 21:41:19 +0300584 for purposes other than executing a single script pass ``0`` as *updatepath*,
Antoine Pitrouf978fac2010-05-21 17:25:34 +0000585 and update :data:`sys.path` themselves if desired.
Serhiy Storchaka6dff0202016-05-07 10:49:07 +0300586 See `CVE-2008-5983 <https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-5983>`_.
Antoine Pitrouf978fac2010-05-21 17:25:34 +0000587
588 On versions before 3.1.3, you can achieve the same effect by manually
589 popping the first :data:`sys.path` element after having called
Georg Brandl60203b42010-10-06 10:11:56 +0000590 :c:func:`PySys_SetArgv`, for example using::
Antoine Pitrouf978fac2010-05-21 17:25:34 +0000591
592 PyRun_SimpleString("import sys; sys.path.pop(0)\n");
593
594 .. versionadded:: 3.1.3
Georg Brandl116aa622007-08-15 14:28:22 +0000595
Serhiy Storchaka1ecf7d22016-10-27 21:41:19 +0300596 .. XXX impl. doesn't seem consistent in allowing ``0``/``NULL`` for the params;
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000597 check w/ Guido.
Georg Brandl116aa622007-08-15 14:28:22 +0000598
Georg Brandl116aa622007-08-15 14:28:22 +0000599
Georg Brandl60203b42010-10-06 10:11:56 +0000600.. c:function:: void PySys_SetArgv(int argc, wchar_t **argv)
Antoine Pitrouf978fac2010-05-21 17:25:34 +0000601
Christian Heimesad73a9c2013-08-10 16:36:18 +0200602 This function works like :c:func:`PySys_SetArgvEx` with *updatepath* set
Serhiy Storchaka1ecf7d22016-10-27 21:41:19 +0300603 to ``1`` unless the :program:`python` interpreter was started with the
Christian Heimesad73a9c2013-08-10 16:36:18 +0200604 :option:`-I`.
605
Victor Stinner25e014b2014-08-01 12:28:49 +0200606 Use :c:func:`Py_DecodeLocale` to decode a bytes string to get a
607 :c:type:`wchar_*` string.
608
Christian Heimesad73a9c2013-08-10 16:36:18 +0200609 .. versionchanged:: 3.4 The *updatepath* value depends on :option:`-I`.
Antoine Pitrouf978fac2010-05-21 17:25:34 +0000610
611
Serhiy Storchaka4ae06c52017-12-12 13:55:04 +0200612.. c:function:: void Py_SetPythonHome(const wchar_t *home)
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000613
614 Set the default "home" directory, that is, the location of the standard
Georg Brandlde0ab5e2010-12-02 18:02:01 +0000615 Python libraries. See :envvar:`PYTHONHOME` for the meaning of the
616 argument string.
617
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000618 The argument should point to a zero-terminated character string in static
619 storage whose contents will not change for the duration of the program's
620 execution. No code in the Python interpreter will change the contents of
621 this storage.
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000622
Victor Stinner25e014b2014-08-01 12:28:49 +0200623 Use :c:func:`Py_DecodeLocale` to decode a bytes string to get a
624 :c:type:`wchar_*` string.
625
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000626
Georg Brandl60203b42010-10-06 10:11:56 +0000627.. c:function:: w_char* Py_GetPythonHome()
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000628
629 Return the default "home", that is, the value set by a previous call to
Georg Brandl60203b42010-10-06 10:11:56 +0000630 :c:func:`Py_SetPythonHome`, or the value of the :envvar:`PYTHONHOME`
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000631 environment variable if it is set.
632
633
Georg Brandl116aa622007-08-15 14:28:22 +0000634.. _threads:
635
636Thread State and the Global Interpreter Lock
637============================================
638
639.. index::
640 single: global interpreter lock
641 single: interpreter lock
642 single: lock, interpreter
643
Georg Brandlf285bcc2010-10-19 21:07:16 +0000644The Python interpreter is not fully thread-safe. In order to support
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000645multi-threaded Python programs, there's a global lock, called the :term:`global
646interpreter lock` or :term:`GIL`, that must be held by the current thread before
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000647it can safely access Python objects. Without the lock, even the simplest
648operations could cause problems in a multi-threaded program: for example, when
649two threads simultaneously increment the reference count of the same object, the
650reference count could end up being incremented only once instead of twice.
Georg Brandl116aa622007-08-15 14:28:22 +0000651
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000652.. index:: single: setswitchinterval() (in module sys)
Georg Brandl116aa622007-08-15 14:28:22 +0000653
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000654Therefore, the rule exists that only the thread that has acquired the
655:term:`GIL` may operate on Python objects or call Python/C API functions.
656In order to emulate concurrency of execution, the interpreter regularly
657tries to switch threads (see :func:`sys.setswitchinterval`). The lock is also
658released around potentially blocking I/O operations like reading or writing
659a file, so that other Python threads can run in the meantime.
Georg Brandl116aa622007-08-15 14:28:22 +0000660
661.. index::
662 single: PyThreadState
663 single: PyThreadState
664
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000665The Python interpreter keeps some thread-specific bookkeeping information
666inside a data structure called :c:type:`PyThreadState`. There's also one
667global variable pointing to the current :c:type:`PyThreadState`: it can
668be retrieved using :c:func:`PyThreadState_Get`.
Georg Brandl116aa622007-08-15 14:28:22 +0000669
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000670Releasing the GIL from extension code
671-------------------------------------
672
673Most extension code manipulating the :term:`GIL` has the following simple
674structure::
Georg Brandl116aa622007-08-15 14:28:22 +0000675
676 Save the thread state in a local variable.
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000677 Release the global interpreter lock.
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000678 ... Do some blocking I/O operation ...
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000679 Reacquire the global interpreter lock.
Georg Brandl116aa622007-08-15 14:28:22 +0000680 Restore the thread state from the local variable.
681
682This is so common that a pair of macros exists to simplify it::
683
684 Py_BEGIN_ALLOW_THREADS
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000685 ... Do some blocking I/O operation ...
Georg Brandl116aa622007-08-15 14:28:22 +0000686 Py_END_ALLOW_THREADS
687
688.. index::
689 single: Py_BEGIN_ALLOW_THREADS
690 single: Py_END_ALLOW_THREADS
691
Georg Brandl60203b42010-10-06 10:11:56 +0000692The :c:macro:`Py_BEGIN_ALLOW_THREADS` macro opens a new block and declares a
693hidden local variable; the :c:macro:`Py_END_ALLOW_THREADS` macro closes the
Victor Stinner2914bb32018-01-29 11:57:45 +0100694block.
Georg Brandl116aa622007-08-15 14:28:22 +0000695
Victor Stinner2914bb32018-01-29 11:57:45 +0100696The block above expands to the following code::
Georg Brandl116aa622007-08-15 14:28:22 +0000697
698 PyThreadState *_save;
699
700 _save = PyEval_SaveThread();
Victor Stinner2914bb32018-01-29 11:57:45 +0100701 ... Do some blocking I/O operation ...
Georg Brandl116aa622007-08-15 14:28:22 +0000702 PyEval_RestoreThread(_save);
703
Georg Brandl116aa622007-08-15 14:28:22 +0000704.. index::
705 single: PyEval_RestoreThread()
Georg Brandl116aa622007-08-15 14:28:22 +0000706 single: PyEval_SaveThread()
Georg Brandl116aa622007-08-15 14:28:22 +0000707
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000708Here is how these functions work: the global interpreter lock is used to protect the pointer to the
709current thread state. When releasing the lock and saving the thread state,
710the current thread state pointer must be retrieved before the lock is released
711(since another thread could immediately acquire the lock and store its own thread
712state in the global variable). Conversely, when acquiring the lock and restoring
713the thread state, the lock must be acquired before storing the thread state
714pointer.
Georg Brandl116aa622007-08-15 14:28:22 +0000715
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000716.. note::
717 Calling system I/O functions is the most common use case for releasing
718 the GIL, but it can also be useful before calling long-running computations
719 which don't need access to Python objects, such as compression or
720 cryptographic functions operating over memory buffers. For example, the
721 standard :mod:`zlib` and :mod:`hashlib` modules release the GIL when
722 compressing or hashing data.
Georg Brandl116aa622007-08-15 14:28:22 +0000723
Antoine Pitrou1a67bee2013-09-30 21:35:44 +0200724
725.. _gilstate:
726
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000727Non-Python created threads
728--------------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000729
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000730When threads are created using the dedicated Python APIs (such as the
731:mod:`threading` module), a thread state is automatically associated to them
732and the code showed above is therefore correct. However, when threads are
733created from C (for example by a third-party library with its own thread
734management), they don't hold the GIL, nor is there a thread state structure
735for them.
736
737If you need to call Python code from these threads (often this will be part
738of a callback API provided by the aforementioned third-party library),
739you must first register these threads with the interpreter by
740creating a thread state data structure, then acquiring the GIL, and finally
741storing their thread state pointer, before you can start using the Python/C
742API. When you are done, you should reset the thread state pointer, release
743the GIL, and finally free the thread state data structure.
744
745The :c:func:`PyGILState_Ensure` and :c:func:`PyGILState_Release` functions do
746all of the above automatically. The typical idiom for calling into Python
747from a C thread is::
Georg Brandl116aa622007-08-15 14:28:22 +0000748
749 PyGILState_STATE gstate;
750 gstate = PyGILState_Ensure();
751
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000752 /* Perform Python actions here. */
Georg Brandl116aa622007-08-15 14:28:22 +0000753 result = CallSomeFunction();
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000754 /* evaluate result or handle exception */
Georg Brandl116aa622007-08-15 14:28:22 +0000755
756 /* Release the thread. No Python API allowed beyond this point. */
757 PyGILState_Release(gstate);
758
Georg Brandl60203b42010-10-06 10:11:56 +0000759Note that the :c:func:`PyGILState_\*` functions assume there is only one global
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000760interpreter (created automatically by :c:func:`Py_Initialize`). Python
Georg Brandl116aa622007-08-15 14:28:22 +0000761supports the creation of additional interpreters (using
Georg Brandl60203b42010-10-06 10:11:56 +0000762:c:func:`Py_NewInterpreter`), but mixing multiple interpreters and the
763:c:func:`PyGILState_\*` API is unsupported.
Georg Brandl116aa622007-08-15 14:28:22 +0000764
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000765Another important thing to note about threads is their behaviour in the face
Georg Brandl60203b42010-10-06 10:11:56 +0000766of the C :c:func:`fork` call. On most systems with :c:func:`fork`, after a
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000767process forks only the thread that issued the fork will exist. That also
768means any locks held by other threads will never be released. Python solves
769this for :func:`os.fork` by acquiring the locks it uses internally before
770the fork, and releasing them afterwards. In addition, it resets any
771:ref:`lock-objects` in the child. When extending or embedding Python, there
772is no way to inform Python of additional (non-Python) locks that need to be
773acquired before or reset after a fork. OS facilities such as
Ezio Melotti861d27f2011-04-20 21:32:40 +0300774:c:func:`pthread_atfork` would need to be used to accomplish the same thing.
Georg Brandl60203b42010-10-06 10:11:56 +0000775Additionally, when extending or embedding Python, calling :c:func:`fork`
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000776directly rather than through :func:`os.fork` (and returning to or calling
777into Python) may result in a deadlock by one of Python's internal locks
778being held by a thread that is defunct after the fork.
Antoine Pitrouf7ecfac2017-05-28 11:35:14 +0200779:c:func:`PyOS_AfterFork_Child` tries to reset the necessary locks, but is not
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000780always able to.
Georg Brandl116aa622007-08-15 14:28:22 +0000781
Antoine Pitrou8b50b832011-01-15 11:57:42 +0000782
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000783High-level API
784--------------
785
786These are the most commonly used types and functions when writing C extension
787code, or when embedding the Python interpreter:
788
Georg Brandl60203b42010-10-06 10:11:56 +0000789.. c:type:: PyInterpreterState
Georg Brandl116aa622007-08-15 14:28:22 +0000790
791 This data structure represents the state shared by a number of cooperating
792 threads. Threads belonging to the same interpreter share their module
793 administration and a few other internal items. There are no public members in
794 this structure.
795
796 Threads belonging to different interpreters initially share nothing, except
797 process state like available memory, open file descriptors and such. The global
798 interpreter lock is also shared by all threads, regardless of to which
799 interpreter they belong.
800
801
Georg Brandl60203b42010-10-06 10:11:56 +0000802.. c:type:: PyThreadState
Georg Brandl116aa622007-08-15 14:28:22 +0000803
804 This data structure represents the state of a single thread. The only public
Georg Brandl60203b42010-10-06 10:11:56 +0000805 data member is :c:type:`PyInterpreterState \*`:attr:`interp`, which points to
Georg Brandl116aa622007-08-15 14:28:22 +0000806 this thread's interpreter state.
807
808
Georg Brandl60203b42010-10-06 10:11:56 +0000809.. c:function:: void PyEval_InitThreads()
Georg Brandl116aa622007-08-15 14:28:22 +0000810
811 .. index::
Antoine Pitrouf5cf4352011-01-15 14:31:49 +0000812 single: PyEval_AcquireThread()
Georg Brandl116aa622007-08-15 14:28:22 +0000813 single: PyEval_ReleaseThread()
814 single: PyEval_SaveThread()
815 single: PyEval_RestoreThread()
816
817 Initialize and acquire the global interpreter lock. It should be called in the
818 main thread before creating a second thread or engaging in any other thread
Antoine Pitrouf5cf4352011-01-15 14:31:49 +0000819 operations such as ``PyEval_ReleaseThread(tstate)``. It is not needed before
820 calling :c:func:`PyEval_SaveThread` or :c:func:`PyEval_RestoreThread`.
Georg Brandl116aa622007-08-15 14:28:22 +0000821
Antoine Pitrou9bd3bbc2011-03-13 23:28:28 +0100822 This is a no-op when called for a second time.
Georg Brandl116aa622007-08-15 14:28:22 +0000823
Victor Stinner2914bb32018-01-29 11:57:45 +0100824 .. versionchanged:: 3.7
825 This function is now called by :c:func:`Py_Initialize()`, so you don't
826 have to call it yourself anymore.
827
Antoine Pitrou9bb98772011-03-15 20:22:50 +0100828 .. versionchanged:: 3.2
829 This function cannot be called before :c:func:`Py_Initialize()` anymore.
830
Georg Brandl2067bfd2008-05-25 13:05:15 +0000831 .. index:: module: _thread
Georg Brandl116aa622007-08-15 14:28:22 +0000832
Georg Brandl116aa622007-08-15 14:28:22 +0000833
Georg Brandl60203b42010-10-06 10:11:56 +0000834.. c:function:: int PyEval_ThreadsInitialized()
Georg Brandl116aa622007-08-15 14:28:22 +0000835
Georg Brandl60203b42010-10-06 10:11:56 +0000836 Returns a non-zero value if :c:func:`PyEval_InitThreads` has been called. This
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000837 function can be called without holding the GIL, and therefore can be used to
Victor Stinner2914bb32018-01-29 11:57:45 +0100838 avoid calls to the locking API when running single-threaded.
839
840 .. versionchanged:: 3.7
841 The :term:`GIL` is now initialized by :c:func:`Py_Initialize()`.
Georg Brandl116aa622007-08-15 14:28:22 +0000842
Georg Brandl116aa622007-08-15 14:28:22 +0000843
Georg Brandl60203b42010-10-06 10:11:56 +0000844.. c:function:: PyThreadState* PyEval_SaveThread()
Georg Brandl116aa622007-08-15 14:28:22 +0000845
Zackery Spytzeef05962018-09-29 10:07:11 -0600846 Release the global interpreter lock (if it has been created) and reset the
847 thread state to *NULL*, returning the previous thread state (which is not
848 *NULL*). If the lock has been created, the current thread must have
849 acquired it.
Georg Brandl116aa622007-08-15 14:28:22 +0000850
851
Georg Brandl60203b42010-10-06 10:11:56 +0000852.. c:function:: void PyEval_RestoreThread(PyThreadState *tstate)
Georg Brandl116aa622007-08-15 14:28:22 +0000853
Zackery Spytzeef05962018-09-29 10:07:11 -0600854 Acquire the global interpreter lock (if it has been created) and set the
855 thread state to *tstate*, which must not be *NULL*. If the lock has been
856 created, the current thread must not have acquired it, otherwise deadlock
857 ensues.
Georg Brandl116aa622007-08-15 14:28:22 +0000858
Pablo Galindofde9b332019-04-13 17:23:24 +0100859 .. note::
860 Calling this function from a thread when the runtime is finalizing
861 will terminate the thread, even if the thread was not created by Python.
862 You can use :c:func:`_Py_IsFinalizing` or :func:`sys.is_finalizing` to
863 check if the interpreter is in process of being finalized before calling
864 this function to avoid unwanted termination.
Christian Heimesd8654cf2007-12-02 15:22:16 +0000865
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000866.. c:function:: PyThreadState* PyThreadState_Get()
867
868 Return the current thread state. The global interpreter lock must be held.
869 When the current thread state is *NULL*, this issues a fatal error (so that
870 the caller needn't check for *NULL*).
871
872
873.. c:function:: PyThreadState* PyThreadState_Swap(PyThreadState *tstate)
874
875 Swap the current thread state with the thread state given by the argument
876 *tstate*, which may be *NULL*. The global interpreter lock must be held
877 and is not released.
878
879
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000880The following functions use thread-local storage, and are not compatible
881with sub-interpreters:
882
883.. c:function:: PyGILState_STATE PyGILState_Ensure()
884
885 Ensure that the current thread is ready to call the Python C API regardless
886 of the current state of Python, or of the global interpreter lock. This may
887 be called as many times as desired by a thread as long as each call is
888 matched with a call to :c:func:`PyGILState_Release`. In general, other
889 thread-related APIs may be used between :c:func:`PyGILState_Ensure` and
890 :c:func:`PyGILState_Release` calls as long as the thread state is restored to
891 its previous state before the Release(). For example, normal usage of the
892 :c:macro:`Py_BEGIN_ALLOW_THREADS` and :c:macro:`Py_END_ALLOW_THREADS` macros is
893 acceptable.
894
895 The return value is an opaque "handle" to the thread state when
896 :c:func:`PyGILState_Ensure` was called, and must be passed to
897 :c:func:`PyGILState_Release` to ensure Python is left in the same state. Even
898 though recursive calls are allowed, these handles *cannot* be shared - each
899 unique call to :c:func:`PyGILState_Ensure` must save the handle for its call
900 to :c:func:`PyGILState_Release`.
901
902 When the function returns, the current thread will hold the GIL and be able
903 to call arbitrary Python code. Failure is a fatal error.
904
Pablo Galindofde9b332019-04-13 17:23:24 +0100905 .. note::
906 Calling this function from a thread when the runtime is finalizing
907 will terminate the thread, even if the thread was not created by Python.
908 You can use :c:func:`_Py_IsFinalizing` or :func:`sys.is_finalizing` to
909 check if the interpreter is in process of being finalized before calling
910 this function to avoid unwanted termination.
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000911
912.. c:function:: void PyGILState_Release(PyGILState_STATE)
913
914 Release any resources previously acquired. After this call, Python's state will
915 be the same as it was prior to the corresponding :c:func:`PyGILState_Ensure` call
916 (but generally this state will be unknown to the caller, hence the use of the
917 GILState API).
918
919 Every call to :c:func:`PyGILState_Ensure` must be matched by a call to
920 :c:func:`PyGILState_Release` on the same thread.
921
922
Eli Bendersky08131682012-06-03 08:07:47 +0300923.. c:function:: PyThreadState* PyGILState_GetThisThreadState()
Sandro Tosi61baee02011-08-08 00:16:54 +0200924
925 Get the current thread state for this thread. May return ``NULL`` if no
926 GILState API has been used on the current thread. Note that the main thread
927 always has such a thread-state, even if no auto-thread-state call has been
928 made on the main thread. This is mainly a helper/diagnostic function.
929
930
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -0700931.. c:function:: int PyGILState_Check()
932
Serhiy Storchaka1ecf7d22016-10-27 21:41:19 +0300933 Return ``1`` if the current thread is holding the GIL and ``0`` otherwise.
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -0700934 This function can be called from any thread at any time.
935 Only if it has had its Python thread state initialized and currently is
Serhiy Storchaka1ecf7d22016-10-27 21:41:19 +0300936 holding the GIL will it return ``1``.
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -0700937 This is mainly a helper/diagnostic function. It can be useful
938 for example in callback contexts or memory allocation functions when
939 knowing that the GIL is locked can allow the caller to perform sensitive
940 actions or otherwise behave differently.
941
Kristján Valur Jónsson34870c42013-03-23 03:56:16 -0700942 .. versionadded:: 3.4
943
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -0700944
Georg Brandl116aa622007-08-15 14:28:22 +0000945The following macros are normally used without a trailing semicolon; look for
946example usage in the Python source distribution.
947
948
Georg Brandl60203b42010-10-06 10:11:56 +0000949.. c:macro:: Py_BEGIN_ALLOW_THREADS
Georg Brandl116aa622007-08-15 14:28:22 +0000950
951 This macro expands to ``{ PyThreadState *_save; _save = PyEval_SaveThread();``.
952 Note that it contains an opening brace; it must be matched with a following
Georg Brandl60203b42010-10-06 10:11:56 +0000953 :c:macro:`Py_END_ALLOW_THREADS` macro. See above for further discussion of this
Victor Stinner2914bb32018-01-29 11:57:45 +0100954 macro.
Georg Brandl116aa622007-08-15 14:28:22 +0000955
956
Georg Brandl60203b42010-10-06 10:11:56 +0000957.. c:macro:: Py_END_ALLOW_THREADS
Georg Brandl116aa622007-08-15 14:28:22 +0000958
959 This macro expands to ``PyEval_RestoreThread(_save); }``. Note that it contains
960 a closing brace; it must be matched with an earlier
Georg Brandl60203b42010-10-06 10:11:56 +0000961 :c:macro:`Py_BEGIN_ALLOW_THREADS` macro. See above for further discussion of
Victor Stinner2914bb32018-01-29 11:57:45 +0100962 this macro.
Georg Brandl116aa622007-08-15 14:28:22 +0000963
964
Georg Brandl60203b42010-10-06 10:11:56 +0000965.. c:macro:: Py_BLOCK_THREADS
Georg Brandl116aa622007-08-15 14:28:22 +0000966
967 This macro expands to ``PyEval_RestoreThread(_save);``: it is equivalent to
Victor Stinner2914bb32018-01-29 11:57:45 +0100968 :c:macro:`Py_END_ALLOW_THREADS` without the closing brace.
Georg Brandl116aa622007-08-15 14:28:22 +0000969
970
Georg Brandl60203b42010-10-06 10:11:56 +0000971.. c:macro:: Py_UNBLOCK_THREADS
Georg Brandl116aa622007-08-15 14:28:22 +0000972
973 This macro expands to ``_save = PyEval_SaveThread();``: it is equivalent to
Georg Brandl60203b42010-10-06 10:11:56 +0000974 :c:macro:`Py_BEGIN_ALLOW_THREADS` without the opening brace and variable
Victor Stinner2914bb32018-01-29 11:57:45 +0100975 declaration.
Georg Brandl116aa622007-08-15 14:28:22 +0000976
Antoine Pitroubedd2c22011-01-15 12:54:19 +0000977
978Low-level API
979-------------
980
Victor Stinner2914bb32018-01-29 11:57:45 +0100981All of the following functions must be called after :c:func:`Py_Initialize`.
982
983.. versionchanged:: 3.7
984 :c:func:`Py_Initialize()` now initializes the :term:`GIL`.
Georg Brandl116aa622007-08-15 14:28:22 +0000985
986
Georg Brandl60203b42010-10-06 10:11:56 +0000987.. c:function:: PyInterpreterState* PyInterpreterState_New()
Georg Brandl116aa622007-08-15 14:28:22 +0000988
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000989 Create a new interpreter state object. The global interpreter lock need not
990 be held, but may be held if it is necessary to serialize calls to this
991 function.
Georg Brandl116aa622007-08-15 14:28:22 +0000992
993
Georg Brandl60203b42010-10-06 10:11:56 +0000994.. c:function:: void PyInterpreterState_Clear(PyInterpreterState *interp)
Georg Brandl116aa622007-08-15 14:28:22 +0000995
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000996 Reset all information in an interpreter state object. The global interpreter
997 lock must be held.
Georg Brandl116aa622007-08-15 14:28:22 +0000998
999
Georg Brandl60203b42010-10-06 10:11:56 +00001000.. c:function:: void PyInterpreterState_Delete(PyInterpreterState *interp)
Georg Brandl116aa622007-08-15 14:28:22 +00001001
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001002 Destroy an interpreter state object. The global interpreter lock need not be
1003 held. The interpreter state must have been reset with a previous call to
Georg Brandl60203b42010-10-06 10:11:56 +00001004 :c:func:`PyInterpreterState_Clear`.
Georg Brandl116aa622007-08-15 14:28:22 +00001005
1006
Georg Brandl60203b42010-10-06 10:11:56 +00001007.. c:function:: PyThreadState* PyThreadState_New(PyInterpreterState *interp)
Georg Brandl116aa622007-08-15 14:28:22 +00001008
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001009 Create a new thread state object belonging to the given interpreter object.
1010 The global interpreter lock need not be held, but may be held if it is
1011 necessary to serialize calls to this function.
Georg Brandl116aa622007-08-15 14:28:22 +00001012
1013
Georg Brandl60203b42010-10-06 10:11:56 +00001014.. c:function:: void PyThreadState_Clear(PyThreadState *tstate)
Georg Brandl116aa622007-08-15 14:28:22 +00001015
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001016 Reset all information in a thread state object. The global interpreter lock
1017 must be held.
Georg Brandl116aa622007-08-15 14:28:22 +00001018
1019
Georg Brandl60203b42010-10-06 10:11:56 +00001020.. c:function:: void PyThreadState_Delete(PyThreadState *tstate)
Georg Brandl116aa622007-08-15 14:28:22 +00001021
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001022 Destroy a thread state object. The global interpreter lock need not be held.
1023 The thread state must have been reset with a previous call to
Georg Brandl60203b42010-10-06 10:11:56 +00001024 :c:func:`PyThreadState_Clear`.
Georg Brandl116aa622007-08-15 14:28:22 +00001025
1026
Eric Snowe3774162017-05-22 19:46:40 -07001027.. c:function:: PY_INT64_T PyInterpreterState_GetID(PyInterpreterState *interp)
1028
1029 Return the interpreter's unique ID. If there was any error in doing
Serhiy Storchaka5bb00052018-02-09 13:31:19 +02001030 so then ``-1`` is returned and an error is set.
Eric Snowe3774162017-05-22 19:46:40 -07001031
1032 .. versionadded:: 3.7
1033
1034
Eric Snowd2fdd1f2019-03-15 17:47:43 -06001035.. c:function:: PyObject* PyInterpreterState_GetDict(PyInterpreterState *interp)
1036
1037 Return a dictionary in which interpreter-specific data may be stored.
1038 If this function returns *NULL* then no exception has been raised and
1039 the caller should assume no interpreter-specific dict is available.
1040
1041 This is not a replacement for :c:func:`PyModule_GetState()`, which
1042 extensions should use to store interpreter-specific state information.
1043
1044 .. versionadded:: 3.8
1045
1046
Georg Brandl60203b42010-10-06 10:11:56 +00001047.. c:function:: PyObject* PyThreadState_GetDict()
Georg Brandl116aa622007-08-15 14:28:22 +00001048
1049 Return a dictionary in which extensions can store thread-specific state
1050 information. Each extension should use a unique key to use to store state in
1051 the dictionary. It is okay to call this function when no current thread state
1052 is available. If this function returns *NULL*, no exception has been raised and
1053 the caller should assume no current thread state is available.
1054
Georg Brandl116aa622007-08-15 14:28:22 +00001055
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02001056.. c:function:: int PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
Georg Brandl116aa622007-08-15 14:28:22 +00001057
1058 Asynchronously raise an exception in a thread. The *id* argument is the thread
1059 id of the target thread; *exc* is the exception object to be raised. This
1060 function does not steal any references to *exc*. To prevent naive misuse, you
1061 must write your own C extension to call this. Must be called with the GIL held.
1062 Returns the number of thread states modified; this is normally one, but will be
1063 zero if the thread id isn't found. If *exc* is :const:`NULL`, the pending
1064 exception (if any) for the thread is cleared. This raises no exceptions.
1065
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02001066 .. versionchanged:: 3.7
1067 The type of the *id* parameter changed from :c:type:`long` to
1068 :c:type:`unsigned long`.
Georg Brandl116aa622007-08-15 14:28:22 +00001069
Antoine Pitroubedd2c22011-01-15 12:54:19 +00001070.. c:function:: void PyEval_AcquireThread(PyThreadState *tstate)
Georg Brandl116aa622007-08-15 14:28:22 +00001071
Antoine Pitroubedd2c22011-01-15 12:54:19 +00001072 Acquire the global interpreter lock and set the current thread state to
1073 *tstate*, which should not be *NULL*. The lock must have been created earlier.
1074 If this thread already has the lock, deadlock ensues.
Georg Brandl116aa622007-08-15 14:28:22 +00001075
Joannah Nanjekyef781d202019-04-29 04:38:45 -04001076 .. note::
1077 Calling this function from a thread when the runtime is finalizing
1078 will terminate the thread, even if the thread was not created by Python.
1079 You can use :c:func:`_Py_IsFinalizing` or :func:`sys.is_finalizing` to
1080 check if the interpreter is in process of being finalized before calling
1081 this function to avoid unwanted termination.
1082
1083 .. versionchanged:: 3.8
1084 Updated to be consistent with :c:func:`PyEval_RestoreThread`,
1085 :c:func:`Py_END_ALLOW_THREADS`, and :c:func:`PyGILState_Ensure`,
1086 and terminate the current thread if called while the interpreter is finalizing.
1087
Antoine Pitrou5ace8e92011-01-15 13:11:48 +00001088 :c:func:`PyEval_RestoreThread` is a higher-level function which is always
Victor Stinner2914bb32018-01-29 11:57:45 +01001089 available (even when threads have not been initialized).
Antoine Pitrou5ace8e92011-01-15 13:11:48 +00001090
Georg Brandl116aa622007-08-15 14:28:22 +00001091
Antoine Pitroubedd2c22011-01-15 12:54:19 +00001092.. c:function:: void PyEval_ReleaseThread(PyThreadState *tstate)
Georg Brandl116aa622007-08-15 14:28:22 +00001093
Antoine Pitroubedd2c22011-01-15 12:54:19 +00001094 Reset the current thread state to *NULL* and release the global interpreter
1095 lock. The lock must have been created earlier and must be held by the current
1096 thread. The *tstate* argument, which must not be *NULL*, is only used to check
1097 that it represents the current thread state --- if it isn't, a fatal error is
1098 reported.
Georg Brandl116aa622007-08-15 14:28:22 +00001099
Antoine Pitrou5ace8e92011-01-15 13:11:48 +00001100 :c:func:`PyEval_SaveThread` is a higher-level function which is always
Victor Stinner2914bb32018-01-29 11:57:45 +01001101 available (even when threads have not been initialized).
Antoine Pitrou5ace8e92011-01-15 13:11:48 +00001102
Antoine Pitroubedd2c22011-01-15 12:54:19 +00001103
1104.. c:function:: void PyEval_AcquireLock()
1105
1106 Acquire the global interpreter lock. The lock must have been created earlier.
1107 If this thread already has the lock, a deadlock ensues.
1108
Antoine Pitrou5ace8e92011-01-15 13:11:48 +00001109 .. deprecated:: 3.2
Antoine Pitrouf5cf4352011-01-15 14:31:49 +00001110 This function does not update the current thread state. Please use
Antoine Pitrou5ace8e92011-01-15 13:11:48 +00001111 :c:func:`PyEval_RestoreThread` or :c:func:`PyEval_AcquireThread`
1112 instead.
1113
Joannah Nanjekyef781d202019-04-29 04:38:45 -04001114 .. note::
1115 Calling this function from a thread when the runtime is finalizing
1116 will terminate the thread, even if the thread was not created by Python.
1117 You can use :c:func:`_Py_IsFinalizing` or :func:`sys.is_finalizing` to
1118 check if the interpreter is in process of being finalized before calling
1119 this function to avoid unwanted termination.
1120
1121 .. versionchanged:: 3.8
1122 Updated to be consistent with :c:func:`PyEval_RestoreThread`,
1123 :c:func:`Py_END_ALLOW_THREADS`, and :c:func:`PyGILState_Ensure`,
1124 and terminate the current thread if called while the interpreter is finalizing.
1125
Antoine Pitroubedd2c22011-01-15 12:54:19 +00001126
1127.. c:function:: void PyEval_ReleaseLock()
1128
1129 Release the global interpreter lock. The lock must have been created earlier.
Georg Brandl116aa622007-08-15 14:28:22 +00001130
Antoine Pitrou5ace8e92011-01-15 13:11:48 +00001131 .. deprecated:: 3.2
Antoine Pitrouf5cf4352011-01-15 14:31:49 +00001132 This function does not update the current thread state. Please use
Antoine Pitrou5ace8e92011-01-15 13:11:48 +00001133 :c:func:`PyEval_SaveThread` or :c:func:`PyEval_ReleaseThread`
1134 instead.
1135
Georg Brandl116aa622007-08-15 14:28:22 +00001136
Nick Coghlan2ab5b092015-07-03 19:49:15 +10001137.. _sub-interpreter-support:
1138
Antoine Pitrou8b50b832011-01-15 11:57:42 +00001139Sub-interpreter support
1140=======================
1141
1142While in most uses, you will only embed a single Python interpreter, there
1143are cases where you need to create several independent interpreters in the
1144same process and perhaps even in the same thread. Sub-interpreters allow
Antoine Pitrou9bf8d1c2011-01-15 12:21:53 +00001145you to do that. You can switch between sub-interpreters using the
1146:c:func:`PyThreadState_Swap` function. You can create and destroy them
1147using the following functions:
Antoine Pitrou8b50b832011-01-15 11:57:42 +00001148
1149
1150.. c:function:: PyThreadState* Py_NewInterpreter()
1151
1152 .. index::
1153 module: builtins
1154 module: __main__
1155 module: sys
1156 single: stdout (in module sys)
1157 single: stderr (in module sys)
1158 single: stdin (in module sys)
1159
1160 Create a new sub-interpreter. This is an (almost) totally separate environment
1161 for the execution of Python code. In particular, the new interpreter has
1162 separate, independent versions of all imported modules, including the
1163 fundamental modules :mod:`builtins`, :mod:`__main__` and :mod:`sys`. The
1164 table of loaded modules (``sys.modules``) and the module search path
1165 (``sys.path``) are also separate. The new environment has no ``sys.argv``
1166 variable. It has new standard I/O stream file objects ``sys.stdin``,
1167 ``sys.stdout`` and ``sys.stderr`` (however these refer to the same underlying
1168 file descriptors).
1169
1170 The return value points to the first thread state created in the new
1171 sub-interpreter. This thread state is made in the current thread state.
1172 Note that no actual thread is created; see the discussion of thread states
1173 below. If creation of the new interpreter is unsuccessful, *NULL* is
1174 returned; no exception is set since the exception state is stored in the
1175 current thread state and there may not be a current thread state. (Like all
1176 other Python/C API functions, the global interpreter lock must be held before
1177 calling this function and is still held when it returns; however, unlike most
1178 other Python/C API functions, there needn't be a current thread state on
1179 entry.)
1180
1181 .. index::
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001182 single: Py_FinalizeEx()
Antoine Pitrou8b50b832011-01-15 11:57:42 +00001183 single: Py_Initialize()
1184
1185 Extension modules are shared between (sub-)interpreters as follows: the first
1186 time a particular extension is imported, it is initialized normally, and a
1187 (shallow) copy of its module's dictionary is squirreled away. When the same
1188 extension is imported by another (sub-)interpreter, a new module is initialized
1189 and filled with the contents of this copy; the extension's ``init`` function is
1190 not called. Note that this is different from what happens when an extension is
1191 imported after the interpreter has been completely re-initialized by calling
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001192 :c:func:`Py_FinalizeEx` and :c:func:`Py_Initialize`; in that case, the extension's
Antoine Pitrou8b50b832011-01-15 11:57:42 +00001193 ``initmodule`` function *is* called again.
1194
1195 .. index:: single: close() (in module os)
1196
1197
1198.. c:function:: void Py_EndInterpreter(PyThreadState *tstate)
1199
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001200 .. index:: single: Py_FinalizeEx()
Antoine Pitrou8b50b832011-01-15 11:57:42 +00001201
1202 Destroy the (sub-)interpreter represented by the given thread state. The given
1203 thread state must be the current thread state. See the discussion of thread
1204 states below. When the call returns, the current thread state is *NULL*. All
1205 thread states associated with this interpreter are destroyed. (The global
1206 interpreter lock must be held before calling this function and is still held
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001207 when it returns.) :c:func:`Py_FinalizeEx` will destroy all sub-interpreters that
Antoine Pitrou8b50b832011-01-15 11:57:42 +00001208 haven't been explicitly destroyed at that point.
1209
1210
1211Bugs and caveats
1212----------------
1213
1214Because sub-interpreters (and the main interpreter) are part of the same
1215process, the insulation between them isn't perfect --- for example, using
1216low-level file operations like :func:`os.close` they can
1217(accidentally or maliciously) affect each other's open files. Because of the
1218way extensions are shared between (sub-)interpreters, some extensions may not
1219work properly; this is especially likely when the extension makes use of
1220(static) global variables, or when the extension manipulates its module's
1221dictionary after its initialization. It is possible to insert objects created
1222in one sub-interpreter into a namespace of another sub-interpreter; this should
1223be done with great care to avoid sharing user-defined functions, methods,
1224instances or classes between sub-interpreters, since import operations executed
1225by such objects may affect the wrong (sub-)interpreter's dictionary of loaded
Antoine Pitrouf1dfe732011-01-15 12:10:48 +00001226modules.
Antoine Pitrou8b50b832011-01-15 11:57:42 +00001227
Antoine Pitrouf1dfe732011-01-15 12:10:48 +00001228Also note that combining this functionality with :c:func:`PyGILState_\*` APIs
Ezio Melottid92ab082011-05-05 14:19:48 +03001229is delicate, because these APIs assume a bijection between Python thread states
Antoine Pitrouf1dfe732011-01-15 12:10:48 +00001230and OS-level threads, an assumption broken by the presence of sub-interpreters.
1231It is highly recommended that you don't switch sub-interpreters between a pair
1232of matching :c:func:`PyGILState_Ensure` and :c:func:`PyGILState_Release` calls.
1233Furthermore, extensions (such as :mod:`ctypes`) using these APIs to allow calling
1234of Python code from non-Python created threads will probably be broken when using
1235sub-interpreters.
Antoine Pitrou8b50b832011-01-15 11:57:42 +00001236
Benjamin Petersona54c9092009-01-13 02:11:23 +00001237
1238Asynchronous Notifications
1239==========================
1240
Benjamin Petersond23f8222009-04-05 19:13:16 +00001241A mechanism is provided to make asynchronous notifications to the main
Benjamin Petersona54c9092009-01-13 02:11:23 +00001242interpreter thread. These notifications take the form of a function
Antoine Pitrou1a67bee2013-09-30 21:35:44 +02001243pointer and a void pointer argument.
Benjamin Petersona54c9092009-01-13 02:11:23 +00001244
Benjamin Petersona54c9092009-01-13 02:11:23 +00001245
Ezio Melottia782cca2011-04-28 00:53:14 +03001246.. c:function:: int Py_AddPendingCall(int (*func)(void *), void *arg)
Benjamin Petersona54c9092009-01-13 02:11:23 +00001247
1248 .. index:: single: Py_AddPendingCall()
1249
Antoine Pitrou1a67bee2013-09-30 21:35:44 +02001250 Schedule a function to be called from the main interpreter thread. On
Serhiy Storchaka1ecf7d22016-10-27 21:41:19 +03001251 success, ``0`` is returned and *func* is queued for being called in the
1252 main thread. On failure, ``-1`` is returned without setting any exception.
Benjamin Petersona54c9092009-01-13 02:11:23 +00001253
Antoine Pitrou1a67bee2013-09-30 21:35:44 +02001254 When successfully queued, *func* will be *eventually* called from the
1255 main interpreter thread with the argument *arg*. It will be called
1256 asynchronously with respect to normally running Python code, but with
1257 both these conditions met:
Benjamin Petersona54c9092009-01-13 02:11:23 +00001258
Antoine Pitrou1a67bee2013-09-30 21:35:44 +02001259 * on a :term:`bytecode` boundary;
1260 * with the main thread holding the :term:`global interpreter lock`
1261 (*func* can therefore use the full C API).
1262
Serhiy Storchaka1ecf7d22016-10-27 21:41:19 +03001263 *func* must return ``0`` on success, or ``-1`` on failure with an exception
Antoine Pitrou1a67bee2013-09-30 21:35:44 +02001264 set. *func* won't be interrupted to perform another asynchronous
1265 notification recursively, but it can still be interrupted to switch
1266 threads if the global interpreter lock is released.
1267
1268 This function doesn't need a current thread state to run, and it doesn't
1269 need the global interpreter lock.
1270
1271 .. warning::
1272 This is a low-level function, only useful for very special cases.
1273 There is no guarantee that *func* will be called as quick as
1274 possible. If the main thread is busy executing a system call,
1275 *func* won't be called before the system call returns. This
1276 function is generally **not** suitable for calling Python code from
1277 arbitrary C threads. Instead, use the :ref:`PyGILState API<gilstate>`.
Benjamin Petersona54c9092009-01-13 02:11:23 +00001278
Georg Brandl705d9d52009-05-05 09:29:50 +00001279 .. versionadded:: 3.1
Benjamin Petersona54c9092009-01-13 02:11:23 +00001280
Georg Brandl116aa622007-08-15 14:28:22 +00001281.. _profiling:
1282
1283Profiling and Tracing
1284=====================
1285
1286.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
1287
1288
1289The Python interpreter provides some low-level support for attaching profiling
1290and execution tracing facilities. These are used for profiling, debugging, and
1291coverage analysis tools.
1292
Georg Brandle6bcc912008-05-12 18:05:20 +00001293This C interface allows the profiling or tracing code to avoid the overhead of
1294calling through Python-level callable objects, making a direct C function call
1295instead. The essential attributes of the facility have not changed; the
1296interface allows trace functions to be installed per-thread, and the basic
1297events reported to the trace function are the same as had been reported to the
1298Python-level trace functions in previous versions.
Georg Brandl116aa622007-08-15 14:28:22 +00001299
1300
Georg Brandl60203b42010-10-06 10:11:56 +00001301.. c:type:: int (*Py_tracefunc)(PyObject *obj, PyFrameObject *frame, int what, PyObject *arg)
Georg Brandl116aa622007-08-15 14:28:22 +00001302
Georg Brandl60203b42010-10-06 10:11:56 +00001303 The type of the trace function registered using :c:func:`PyEval_SetProfile` and
1304 :c:func:`PyEval_SetTrace`. The first parameter is the object passed to the
Georg Brandl116aa622007-08-15 14:28:22 +00001305 registration function as *obj*, *frame* is the frame object to which the event
1306 pertains, *what* is one of the constants :const:`PyTrace_CALL`,
1307 :const:`PyTrace_EXCEPTION`, :const:`PyTrace_LINE`, :const:`PyTrace_RETURN`,
Xiang Zhang255f7a22018-01-28 17:53:38 +08001308 :const:`PyTrace_C_CALL`, :const:`PyTrace_C_EXCEPTION`, :const:`PyTrace_C_RETURN`,
1309 or :const:`PyTrace_OPCODE`, and *arg* depends on the value of *what*:
Georg Brandl116aa622007-08-15 14:28:22 +00001310
1311 +------------------------------+--------------------------------------+
1312 | Value of *what* | Meaning of *arg* |
1313 +==============================+======================================+
Xiang Zhang9ed0aee2018-01-28 15:38:21 +08001314 | :const:`PyTrace_CALL` | Always :c:data:`Py_None`. |
Georg Brandl116aa622007-08-15 14:28:22 +00001315 +------------------------------+--------------------------------------+
1316 | :const:`PyTrace_EXCEPTION` | Exception information as returned by |
1317 | | :func:`sys.exc_info`. |
1318 +------------------------------+--------------------------------------+
Xiang Zhang9ed0aee2018-01-28 15:38:21 +08001319 | :const:`PyTrace_LINE` | Always :c:data:`Py_None`. |
Georg Brandl116aa622007-08-15 14:28:22 +00001320 +------------------------------+--------------------------------------+
Georg Brandld0b0e1d2010-10-15 16:42:37 +00001321 | :const:`PyTrace_RETURN` | Value being returned to the caller, |
1322 | | or *NULL* if caused by an exception. |
Georg Brandl116aa622007-08-15 14:28:22 +00001323 +------------------------------+--------------------------------------+
Georg Brandld0b0e1d2010-10-15 16:42:37 +00001324 | :const:`PyTrace_C_CALL` | Function object being called. |
Georg Brandl116aa622007-08-15 14:28:22 +00001325 +------------------------------+--------------------------------------+
Georg Brandld0b0e1d2010-10-15 16:42:37 +00001326 | :const:`PyTrace_C_EXCEPTION` | Function object being called. |
Georg Brandl116aa622007-08-15 14:28:22 +00001327 +------------------------------+--------------------------------------+
Georg Brandld0b0e1d2010-10-15 16:42:37 +00001328 | :const:`PyTrace_C_RETURN` | Function object being called. |
Georg Brandl116aa622007-08-15 14:28:22 +00001329 +------------------------------+--------------------------------------+
Xiang Zhang255f7a22018-01-28 17:53:38 +08001330 | :const:`PyTrace_OPCODE` | Always :c:data:`Py_None`. |
1331 +------------------------------+--------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00001332
Georg Brandl60203b42010-10-06 10:11:56 +00001333.. c:var:: int PyTrace_CALL
Georg Brandl116aa622007-08-15 14:28:22 +00001334
Georg Brandl60203b42010-10-06 10:11:56 +00001335 The value of the *what* parameter to a :c:type:`Py_tracefunc` function when a new
Georg Brandl116aa622007-08-15 14:28:22 +00001336 call to a function or method is being reported, or a new entry into a generator.
1337 Note that the creation of the iterator for a generator function is not reported
1338 as there is no control transfer to the Python bytecode in the corresponding
1339 frame.
1340
1341
Georg Brandl60203b42010-10-06 10:11:56 +00001342.. c:var:: int PyTrace_EXCEPTION
Georg Brandl116aa622007-08-15 14:28:22 +00001343
Georg Brandl60203b42010-10-06 10:11:56 +00001344 The value of the *what* parameter to a :c:type:`Py_tracefunc` function when an
Georg Brandl116aa622007-08-15 14:28:22 +00001345 exception has been raised. The callback function is called with this value for
1346 *what* when after any bytecode is processed after which the exception becomes
1347 set within the frame being executed. The effect of this is that as exception
1348 propagation causes the Python stack to unwind, the callback is called upon
1349 return to each frame as the exception propagates. Only trace functions receives
1350 these events; they are not needed by the profiler.
1351
1352
Georg Brandl60203b42010-10-06 10:11:56 +00001353.. c:var:: int PyTrace_LINE
Georg Brandl116aa622007-08-15 14:28:22 +00001354
Xiang Zhang255f7a22018-01-28 17:53:38 +08001355 The value passed as the *what* parameter to a :c:type:`Py_tracefunc` function
1356 (but not a profiling function) when a line-number event is being reported.
1357 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 +00001358
1359
Georg Brandl60203b42010-10-06 10:11:56 +00001360.. c:var:: int PyTrace_RETURN
Georg Brandl116aa622007-08-15 14:28:22 +00001361
Georg Brandl60203b42010-10-06 10:11:56 +00001362 The value for the *what* parameter to :c:type:`Py_tracefunc` functions when a
Xiang Zhang79db11c2018-01-28 22:54:42 +08001363 call is about to return.
Georg Brandl116aa622007-08-15 14:28:22 +00001364
1365
Georg Brandl60203b42010-10-06 10:11:56 +00001366.. c:var:: int PyTrace_C_CALL
Georg Brandl116aa622007-08-15 14:28:22 +00001367
Georg Brandl60203b42010-10-06 10:11:56 +00001368 The value for the *what* parameter to :c:type:`Py_tracefunc` functions when a C
Georg Brandl116aa622007-08-15 14:28:22 +00001369 function is about to be called.
1370
1371
Georg Brandl60203b42010-10-06 10:11:56 +00001372.. c:var:: int PyTrace_C_EXCEPTION
Georg Brandl116aa622007-08-15 14:28:22 +00001373
Georg Brandl60203b42010-10-06 10:11:56 +00001374 The value for the *what* parameter to :c:type:`Py_tracefunc` functions when a C
Georg Brandl7cb13192010-08-03 12:06:29 +00001375 function has raised an exception.
Georg Brandl116aa622007-08-15 14:28:22 +00001376
1377
Georg Brandl60203b42010-10-06 10:11:56 +00001378.. c:var:: int PyTrace_C_RETURN
Georg Brandl116aa622007-08-15 14:28:22 +00001379
Georg Brandl60203b42010-10-06 10:11:56 +00001380 The value for the *what* parameter to :c:type:`Py_tracefunc` functions when a C
Georg Brandl116aa622007-08-15 14:28:22 +00001381 function has returned.
1382
1383
Xiang Zhang255f7a22018-01-28 17:53:38 +08001384.. c:var:: int PyTrace_OPCODE
1385
1386 The value for the *what* parameter to :c:type:`Py_tracefunc` functions (but not
1387 profiling functions) when a new opcode is about to be executed. This event is
1388 not emitted by default: it must be explicitly requested by setting
1389 :attr:`f_trace_opcodes` to *1* on the frame.
1390
1391
Georg Brandl60203b42010-10-06 10:11:56 +00001392.. c:function:: void PyEval_SetProfile(Py_tracefunc func, PyObject *obj)
Georg Brandl116aa622007-08-15 14:28:22 +00001393
1394 Set the profiler function to *func*. The *obj* parameter is passed to the
1395 function as its first parameter, and may be any Python object, or *NULL*. If
1396 the profile function needs to maintain state, using a different value for *obj*
1397 for each thread provides a convenient and thread-safe place to store it. The
Pablo Galindo131fd7f2018-01-24 12:57:49 +00001398 profile function is called for all monitored events except :const:`PyTrace_LINE`
Xiang Zhang255f7a22018-01-28 17:53:38 +08001399 :const:`PyTrace_OPCODE` and :const:`PyTrace_EXCEPTION`.
Georg Brandl116aa622007-08-15 14:28:22 +00001400
1401
Georg Brandl60203b42010-10-06 10:11:56 +00001402.. c:function:: void PyEval_SetTrace(Py_tracefunc func, PyObject *obj)
Georg Brandl116aa622007-08-15 14:28:22 +00001403
1404 Set the tracing function to *func*. This is similar to
Georg Brandl60203b42010-10-06 10:11:56 +00001405 :c:func:`PyEval_SetProfile`, except the tracing function does receive line-number
Xiang Zhang255f7a22018-01-28 17:53:38 +08001406 events and per-opcode events, but does not receive any event related to C function
1407 objects being called. Any trace function registered using :c:func:`PyEval_SetTrace`
1408 will not receive :const:`PyTrace_C_CALL`, :const:`PyTrace_C_EXCEPTION` or
1409 :const:`PyTrace_C_RETURN` as a value for the *what* parameter.
Georg Brandl116aa622007-08-15 14:28:22 +00001410
1411.. _advanced-debugging:
1412
1413Advanced Debugger Support
1414=========================
1415
1416.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
1417
1418
1419These functions are only intended to be used by advanced debugging tools.
1420
1421
Georg Brandl60203b42010-10-06 10:11:56 +00001422.. c:function:: PyInterpreterState* PyInterpreterState_Head()
Georg Brandl116aa622007-08-15 14:28:22 +00001423
1424 Return the interpreter state object at the head of the list of all such objects.
1425
Georg Brandl116aa622007-08-15 14:28:22 +00001426
Joannah Nanjekye8c617392019-04-01 18:08:43 +03001427.. c:function:: PyInterpreterState* PyInterpreterState_Main()
1428
1429 Return the main interpreter state object.
1430
1431
Georg Brandl60203b42010-10-06 10:11:56 +00001432.. c:function:: PyInterpreterState* PyInterpreterState_Next(PyInterpreterState *interp)
Georg Brandl116aa622007-08-15 14:28:22 +00001433
1434 Return the next interpreter state object after *interp* from the list of all
1435 such objects.
1436
Georg Brandl116aa622007-08-15 14:28:22 +00001437
Georg Brandl60203b42010-10-06 10:11:56 +00001438.. c:function:: PyThreadState * PyInterpreterState_ThreadHead(PyInterpreterState *interp)
Georg Brandl116aa622007-08-15 14:28:22 +00001439
Benjamin Peterson82f34ad2015-01-13 09:17:24 -05001440 Return the pointer to the first :c:type:`PyThreadState` object in the list of
Georg Brandl116aa622007-08-15 14:28:22 +00001441 threads associated with the interpreter *interp*.
1442
Georg Brandl116aa622007-08-15 14:28:22 +00001443
Georg Brandl60203b42010-10-06 10:11:56 +00001444.. c:function:: PyThreadState* PyThreadState_Next(PyThreadState *tstate)
Georg Brandl116aa622007-08-15 14:28:22 +00001445
1446 Return the next thread state object after *tstate* from the list of all such
Georg Brandl60203b42010-10-06 10:11:56 +00001447 objects belonging to the same :c:type:`PyInterpreterState` object.
Georg Brandl116aa622007-08-15 14:28:22 +00001448
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001449
1450.. _thread-local-storage:
1451
1452Thread Local Storage Support
1453============================
1454
1455.. sectionauthor:: Masayuki Yamamoto <ma3yuki.8mamo10@gmail.com>
1456
1457The Python interpreter provides low-level support for thread-local storage
1458(TLS) which wraps the underlying native TLS implementation to support the
1459Python-level thread local storage API (:class:`threading.local`). The
1460CPython C level APIs are similar to those offered by pthreads and Windows:
1461use a thread key and functions to associate a :c:type:`void\*` value per
1462thread.
1463
1464The GIL does *not* need to be held when calling these functions; they supply
1465their own locking.
1466
1467Note that :file:`Python.h` does not include the declaration of the TLS APIs,
1468you need to include :file:`pythread.h` to use thread-local storage.
1469
1470.. note::
1471 None of these API functions handle memory management on behalf of the
1472 :c:type:`void\*` values. You need to allocate and deallocate them yourself.
1473 If the :c:type:`void\*` values happen to be :c:type:`PyObject\*`, these
1474 functions don't do refcount operations on them either.
1475
1476.. _thread-specific-storage-api:
1477
1478Thread Specific Storage (TSS) API
1479---------------------------------
1480
1481TSS API is introduced to supersede the use of the existing TLS API within the
1482CPython interpreter. This API uses a new type :c:type:`Py_tss_t` instead of
1483:c:type:`int` to represent thread keys.
1484
1485.. versionadded:: 3.7
1486
1487.. seealso:: "A New C-API for Thread-Local Storage in CPython" (:pep:`539`)
1488
1489
1490.. c:type:: Py_tss_t
1491
1492 This data structure represents the state of a thread key, the definition of
1493 which may depend on the underlying TLS implementation, and it has an
1494 internal field representing the key's initialization state. There are no
1495 public members in this structure.
1496
1497 When :ref:`Py_LIMITED_API <stable>` is not defined, static allocation of
1498 this type by :c:macro:`Py_tss_NEEDS_INIT` is allowed.
1499
1500
1501.. c:macro:: Py_tss_NEEDS_INIT
1502
Masayuki Yamamoto831d61d2017-10-24 21:58:16 +09001503 This macro expands to the initializer for :c:type:`Py_tss_t` variables.
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001504 Note that this macro won't be defined with :ref:`Py_LIMITED_API <stable>`.
1505
1506
1507Dynamic Allocation
1508~~~~~~~~~~~~~~~~~~
1509
1510Dynamic allocation of the :c:type:`Py_tss_t`, required in extension modules
1511built with :ref:`Py_LIMITED_API <stable>`, where static allocation of this type
1512is not possible due to its implementation being opaque at build time.
1513
1514
1515.. c:function:: Py_tss_t* PyThread_tss_alloc()
1516
1517 Return a value which is the same state as a value initialized with
1518 :c:macro:`Py_tss_NEEDS_INIT`, or *NULL* in the case of dynamic allocation
1519 failure.
1520
1521
1522.. c:function:: void PyThread_tss_free(Py_tss_t *key)
1523
1524 Free the given *key* allocated by :c:func:`PyThread_tss_alloc`, after
1525 first calling :c:func:`PyThread_tss_delete` to ensure any associated
1526 thread locals have been unassigned. This is a no-op if the *key*
1527 argument is `NULL`.
1528
1529 .. note::
1530 A freed key becomes a dangling pointer, you should reset the key to
1531 `NULL`.
1532
1533
1534Methods
1535~~~~~~~
1536
1537The parameter *key* of these functions must not be *NULL*. Moreover, the
1538behaviors of :c:func:`PyThread_tss_set` and :c:func:`PyThread_tss_get` are
1539undefined if the given :c:type:`Py_tss_t` has not been initialized by
1540:c:func:`PyThread_tss_create`.
1541
1542
1543.. c:function:: int PyThread_tss_is_created(Py_tss_t *key)
1544
1545 Return a non-zero value if the given :c:type:`Py_tss_t` has been initialized
1546 by :c:func:`PyThread_tss_create`.
1547
1548
1549.. c:function:: int PyThread_tss_create(Py_tss_t *key)
1550
1551 Return a zero value on successful initialization of a TSS key. The behavior
1552 is undefined if the value pointed to by the *key* argument is not
1553 initialized by :c:macro:`Py_tss_NEEDS_INIT`. This function can be called
1554 repeatedly on the same key -- calling it on an already initialized key is a
1555 no-op and immediately returns success.
1556
1557
1558.. c:function:: void PyThread_tss_delete(Py_tss_t *key)
1559
1560 Destroy a TSS key to forget the values associated with the key across all
1561 threads, and change the key's initialization state to uninitialized. A
1562 destroyed key is able to be initialized again by
1563 :c:func:`PyThread_tss_create`. This function can be called repeatedly on
1564 the same key -- calling it on an already destroyed key is a no-op.
1565
1566
1567.. c:function:: int PyThread_tss_set(Py_tss_t *key, void *value)
1568
1569 Return a zero value to indicate successfully associating a :c:type:`void\*`
1570 value with a TSS key in the current thread. Each thread has a distinct
1571 mapping of the key to a :c:type:`void\*` value.
1572
1573
1574.. c:function:: void* PyThread_tss_get(Py_tss_t *key)
1575
1576 Return the :c:type:`void\*` value associated with a TSS key in the current
1577 thread. This returns *NULL* if no value is associated with the key in the
1578 current thread.
1579
1580
1581.. _thread-local-storage-api:
1582
1583Thread Local Storage (TLS) API
1584------------------------------
1585
1586.. deprecated:: 3.7
1587 This API is superseded by
1588 :ref:`Thread Specific Storage (TSS) API <thread-specific-storage-api>`.
1589
1590.. note::
1591 This version of the API does not support platforms where the native TLS key
1592 is defined in a way that cannot be safely cast to ``int``. On such platforms,
1593 :c:func:`PyThread_create_key` will return immediately with a failure status,
1594 and the other TLS functions will all be no-ops on such platforms.
1595
1596Due to the compatibility problem noted above, this version of the API should not
1597be used in new code.
1598
1599.. c:function:: int PyThread_create_key()
1600.. c:function:: void PyThread_delete_key(int key)
1601.. c:function:: int PyThread_set_key_value(int key, void *value)
1602.. c:function:: void* PyThread_get_key_value(int key)
1603.. c:function:: void PyThread_delete_key_value(int key)
1604.. c:function:: void PyThread_ReInitTLS()
1605