blob: 7f31df2b413491ae478aef0f30f8d9329ac02f93 [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
10
Antoine Pitrou3acd3e92011-01-15 14:19:53 +000011Initializing and finalizing the interpreter
12===========================================
13
14
Georg Brandl116aa622007-08-15 14:28:22 +000015.. cfunction:: void Py_Initialize()
16
17 .. index::
18 single: Py_SetProgramName()
19 single: PyEval_InitThreads()
20 single: PyEval_ReleaseLock()
21 single: PyEval_AcquireLock()
22 single: modules (in module sys)
23 single: path (in module sys)
Georg Brandl1a3284e2007-12-02 09:40:06 +000024 module: builtins
Georg Brandl116aa622007-08-15 14:28:22 +000025 module: __main__
26 module: sys
27 triple: module; search; path
28 single: PySys_SetArgv()
Antoine Pitrou71d305c2010-05-21 17:33:14 +000029 single: PySys_SetArgvEx()
Georg Brandl116aa622007-08-15 14:28:22 +000030 single: Py_Finalize()
31
32 Initialize the Python interpreter. In an application embedding Python, this
33 should be called before using any other Python/C API functions; with the
34 exception of :cfunc:`Py_SetProgramName`, :cfunc:`PyEval_InitThreads`,
35 :cfunc:`PyEval_ReleaseLock`, and :cfunc:`PyEval_AcquireLock`. This initializes
36 the table of loaded modules (``sys.modules``), and creates the fundamental
Georg Brandl1a3284e2007-12-02 09:40:06 +000037 modules :mod:`builtins`, :mod:`__main__` and :mod:`sys`. It also initializes
Georg Brandl116aa622007-08-15 14:28:22 +000038 the module search path (``sys.path``). It does not set ``sys.argv``; use
Antoine Pitrou71d305c2010-05-21 17:33:14 +000039 :cfunc:`PySys_SetArgvEx` for that. This is a no-op when called for a second time
Georg Brandl116aa622007-08-15 14:28:22 +000040 (without calling :cfunc:`Py_Finalize` first). There is no return value; it is a
41 fatal error if the initialization fails.
42
43
44.. cfunction:: void Py_InitializeEx(int initsigs)
45
46 This function works like :cfunc:`Py_Initialize` if *initsigs* is 1. If
47 *initsigs* is 0, it skips initialization registration of signal handlers, which
48 might be useful when Python is embedded.
49
Georg Brandl116aa622007-08-15 14:28:22 +000050
51.. cfunction:: int Py_IsInitialized()
52
53 Return true (nonzero) when the Python interpreter has been initialized, false
54 (zero) if not. After :cfunc:`Py_Finalize` is called, this returns false until
55 :cfunc:`Py_Initialize` is called again.
56
57
58.. cfunction:: void Py_Finalize()
59
60 Undo all initializations made by :cfunc:`Py_Initialize` and subsequent use of
61 Python/C API functions, and destroy all sub-interpreters (see
62 :cfunc:`Py_NewInterpreter` below) that were created and not yet destroyed since
63 the last call to :cfunc:`Py_Initialize`. Ideally, this frees all memory
64 allocated by the Python interpreter. This is a no-op when called for a second
65 time (without calling :cfunc:`Py_Initialize` again first). There is no return
66 value; errors during finalization are ignored.
67
68 This function is provided for a number of reasons. An embedding application
69 might want to restart Python without having to restart the application itself.
70 An application that has loaded the Python interpreter from a dynamically
71 loadable library (or DLL) might want to free all memory allocated by Python
72 before unloading the DLL. During a hunt for memory leaks in an application a
73 developer might want to free all memory allocated by Python before exiting from
74 the application.
75
76 **Bugs and caveats:** The destruction of modules and objects in modules is done
77 in random order; this may cause destructors (:meth:`__del__` methods) to fail
78 when they depend on other objects (even functions) or modules. Dynamically
79 loaded extension modules loaded by Python are not unloaded. Small amounts of
80 memory allocated by the Python interpreter may not be freed (if you find a leak,
81 please report it). Memory tied up in circular references between objects is not
82 freed. Some memory allocated by extension modules may not be freed. Some
83 extensions may not work properly if their initialization routine is called more
84 than once; this can happen if an application calls :cfunc:`Py_Initialize` and
85 :cfunc:`Py_Finalize` more than once.
86
87
Antoine Pitrou3acd3e92011-01-15 14:19:53 +000088Process-wide parameters
89=======================
Georg Brandl116aa622007-08-15 14:28:22 +000090
91
Martin v. Löwis790465f2008-04-05 20:41:37 +000092.. cfunction:: void Py_SetProgramName(wchar_t *name)
Georg Brandl116aa622007-08-15 14:28:22 +000093
94 .. index::
95 single: Py_Initialize()
96 single: main()
97 single: Py_GetPath()
98
99 This function should be called before :cfunc:`Py_Initialize` is called for
100 the first time, if it is called at all. It tells the interpreter the value
Martin v. Löwis790465f2008-04-05 20:41:37 +0000101 of the ``argv[0]`` argument to the :cfunc:`main` function of the program
102 (converted to wide characters).
Georg Brandl116aa622007-08-15 14:28:22 +0000103 This is used by :cfunc:`Py_GetPath` and some other functions below to find
104 the Python run-time libraries relative to the interpreter executable. The
105 default value is ``'python'``. The argument should point to a
Martin v. Löwis790465f2008-04-05 20:41:37 +0000106 zero-terminated wide character string in static storage whose contents will not
Georg Brandl116aa622007-08-15 14:28:22 +0000107 change for the duration of the program's execution. No code in the Python
108 interpreter will change the contents of this storage.
109
110
Benjamin Peterson53991142008-08-17 18:57:58 +0000111.. cfunction:: wchar* Py_GetProgramName()
Georg Brandl116aa622007-08-15 14:28:22 +0000112
113 .. index:: single: Py_SetProgramName()
114
115 Return the program name set with :cfunc:`Py_SetProgramName`, or the default.
116 The returned string points into static storage; the caller should not modify its
117 value.
118
119
Martin v. Löwis790465f2008-04-05 20:41:37 +0000120.. cfunction:: wchar_t* Py_GetPrefix()
Georg Brandl116aa622007-08-15 14:28:22 +0000121
122 Return the *prefix* for installed platform-independent files. This is derived
123 through a number of complicated rules from the program name set with
124 :cfunc:`Py_SetProgramName` and some environment variables; for example, if the
125 program name is ``'/usr/local/bin/python'``, the prefix is ``'/usr/local'``. The
126 returned string points into static storage; the caller should not modify its
127 value. This corresponds to the :makevar:`prefix` variable in the top-level
128 :file:`Makefile` and the :option:`--prefix` argument to the :program:`configure`
129 script at build time. The value is available to Python code as ``sys.prefix``.
130 It is only useful on Unix. See also the next function.
131
132
Martin v. Löwis790465f2008-04-05 20:41:37 +0000133.. cfunction:: wchar_t* Py_GetExecPrefix()
Georg Brandl116aa622007-08-15 14:28:22 +0000134
135 Return the *exec-prefix* for installed platform-*dependent* files. This is
136 derived through a number of complicated rules from the program name set with
137 :cfunc:`Py_SetProgramName` and some environment variables; for example, if the
138 program name is ``'/usr/local/bin/python'``, the exec-prefix is
139 ``'/usr/local'``. The returned string points into static storage; the caller
140 should not modify its value. This corresponds to the :makevar:`exec_prefix`
141 variable in the top-level :file:`Makefile` and the :option:`--exec-prefix`
142 argument to the :program:`configure` script at build time. The value is
143 available to Python code as ``sys.exec_prefix``. It is only useful on Unix.
144
145 Background: The exec-prefix differs from the prefix when platform dependent
146 files (such as executables and shared libraries) are installed in a different
147 directory tree. In a typical installation, platform dependent files may be
148 installed in the :file:`/usr/local/plat` subtree while platform independent may
149 be installed in :file:`/usr/local`.
150
151 Generally speaking, a platform is a combination of hardware and software
152 families, e.g. Sparc machines running the Solaris 2.x operating system are
153 considered the same platform, but Intel machines running Solaris 2.x are another
154 platform, and Intel machines running Linux are yet another platform. Different
155 major revisions of the same operating system generally also form different
156 platforms. Non-Unix operating systems are a different story; the installation
157 strategies on those systems are so different that the prefix and exec-prefix are
158 meaningless, and set to the empty string. Note that compiled Python bytecode
159 files are platform independent (but not independent from the Python version by
160 which they were compiled!).
161
162 System administrators will know how to configure the :program:`mount` or
163 :program:`automount` programs to share :file:`/usr/local` between platforms
164 while having :file:`/usr/local/plat` be a different filesystem for each
165 platform.
166
167
Martin v. Löwis790465f2008-04-05 20:41:37 +0000168.. cfunction:: wchar_t* Py_GetProgramFullPath()
Georg Brandl116aa622007-08-15 14:28:22 +0000169
170 .. index::
171 single: Py_SetProgramName()
172 single: executable (in module sys)
173
174 Return the full program name of the Python executable; this is computed as a
175 side-effect of deriving the default module search path from the program name
176 (set by :cfunc:`Py_SetProgramName` above). The returned string points into
177 static storage; the caller should not modify its value. The value is available
178 to Python code as ``sys.executable``.
179
180
Martin v. Löwis790465f2008-04-05 20:41:37 +0000181.. cfunction:: wchar_t* Py_GetPath()
Georg Brandl116aa622007-08-15 14:28:22 +0000182
183 .. index::
184 triple: module; search; path
185 single: path (in module sys)
186
Benjamin Petersonffeda292010-01-09 18:48:46 +0000187 Return the default module search path; this is computed from the program name
188 (set by :cfunc:`Py_SetProgramName` above) and some environment variables.
189 The returned string consists of a series of directory names separated by a
190 platform dependent delimiter character. The delimiter character is ``':'``
191 on Unix and Mac OS X, ``';'`` on Windows. The returned string points into
192 static storage; the caller should not modify its value. The list
193 :data:`sys.path` is initialized with this value on interpreter startup; it
194 can be (and usually is) modified later to change the search path for loading
195 modules.
Georg Brandl116aa622007-08-15 14:28:22 +0000196
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000197 .. XXX should give the exact rules
Georg Brandl116aa622007-08-15 14:28:22 +0000198
199
200.. cfunction:: const char* Py_GetVersion()
201
202 Return the version of this Python interpreter. This is a string that looks
203 something like ::
204
Georg Brandle6bcc912008-05-12 18:05:20 +0000205 "3.0a5+ (py3k:63103M, May 12 2008, 00:53:55) \n[GCC 4.2.3]"
Georg Brandl116aa622007-08-15 14:28:22 +0000206
207 .. index:: single: version (in module sys)
208
209 The first word (up to the first space character) is the current Python version;
210 the first three characters are the major and minor version separated by a
211 period. The returned string points into static storage; the caller should not
Georg Brandle6bcc912008-05-12 18:05:20 +0000212 modify its value. The value is available to Python code as :data:`sys.version`.
Georg Brandl116aa622007-08-15 14:28:22 +0000213
214
Georg Brandl116aa622007-08-15 14:28:22 +0000215.. cfunction:: const char* Py_GetPlatform()
216
217 .. index:: single: platform (in module sys)
218
219 Return the platform identifier for the current platform. On Unix, this is
220 formed from the "official" name of the operating system, converted to lower
221 case, followed by the major revision number; e.g., for Solaris 2.x, which is
222 also known as SunOS 5.x, the value is ``'sunos5'``. On Mac OS X, it is
223 ``'darwin'``. On Windows, it is ``'win'``. The returned string points into
224 static storage; the caller should not modify its value. The value is available
225 to Python code as ``sys.platform``.
226
227
228.. cfunction:: const char* Py_GetCopyright()
229
230 Return the official copyright string for the current Python version, for example
231
232 ``'Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam'``
233
234 .. index:: single: copyright (in module sys)
235
236 The returned string points into static storage; the caller should not modify its
237 value. The value is available to Python code as ``sys.copyright``.
238
239
240.. cfunction:: const char* Py_GetCompiler()
241
242 Return an indication of the compiler used to build the current Python version,
243 in square brackets, for example::
244
245 "[GCC 2.7.2.2]"
246
247 .. index:: single: version (in module sys)
248
249 The returned string points into static storage; the caller should not modify its
250 value. The value is available to Python code as part of the variable
251 ``sys.version``.
252
253
254.. cfunction:: const char* Py_GetBuildInfo()
255
256 Return information about the sequence number and build date and time of the
257 current Python interpreter instance, for example ::
258
259 "#67, Aug 1 1997, 22:34:28"
260
261 .. index:: single: version (in module sys)
262
263 The returned string points into static storage; the caller should not modify its
264 value. The value is available to Python code as part of the variable
265 ``sys.version``.
266
267
Antoine Pitrou71d305c2010-05-21 17:33:14 +0000268.. cfunction:: void PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
Georg Brandl116aa622007-08-15 14:28:22 +0000269
270 .. index::
271 single: main()
272 single: Py_FatalError()
273 single: argv (in module sys)
274
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000275 Set :data:`sys.argv` based on *argc* and *argv*. These parameters are
276 similar to those passed to the program's :cfunc:`main` function with the
277 difference that the first entry should refer to the script file to be
278 executed rather than the executable hosting the Python interpreter. If there
279 isn't a script that will be run, the first entry in *argv* can be an empty
280 string. If this function fails to initialize :data:`sys.argv`, a fatal
281 condition is signalled using :cfunc:`Py_FatalError`.
282
Antoine Pitrou71d305c2010-05-21 17:33:14 +0000283 If *updatepath* is zero, this is all the function does. If *updatepath*
284 is non-zero, the function also modifies :data:`sys.path` according to the
285 following algorithm:
286
287 - If the name of an existing script is passed in ``argv[0]``, the absolute
288 path of the directory where the script is located is prepended to
289 :data:`sys.path`.
290 - Otherwise (that is, if *argc* is 0 or ``argv[0]`` doesn't point
291 to an existing file name), an empty string is prepended to
292 :data:`sys.path`, which is the same as prepending the current working
293 directory (``"."``).
294
295 .. note::
296 It is recommended that applications embedding the Python interpreter
297 for purposes other than executing a single script pass 0 as *updatepath*,
298 and update :data:`sys.path` themselves if desired.
299 See `CVE-2008-5983 <http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-5983>`_.
300
301 On versions before 3.1.3, you can achieve the same effect by manually
302 popping the first :data:`sys.path` element after having called
303 :cfunc:`PySys_SetArgv`, for example using::
304
305 PyRun_SimpleString("import sys; sys.path.pop(0)\n");
306
307 .. versionadded:: 3.1.3
Georg Brandl116aa622007-08-15 14:28:22 +0000308
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000309 .. XXX impl. doesn't seem consistent in allowing 0/NULL for the params;
310 check w/ Guido.
Georg Brandl116aa622007-08-15 14:28:22 +0000311
Georg Brandl116aa622007-08-15 14:28:22 +0000312
Antoine Pitrou71d305c2010-05-21 17:33:14 +0000313.. cfunction:: void PySys_SetArgv(int argc, wchar_t **argv)
314
Georg Brandlc62efa82010-07-11 10:41:07 +0000315 This function works like :cfunc:`PySys_SetArgvEx` with *updatepath* set to 1.
Antoine Pitrou71d305c2010-05-21 17:33:14 +0000316
317
Benjamin Petersonb8f68ee2009-09-15 03:38:09 +0000318.. cfunction:: void Py_SetPythonHome(wchar_t *home)
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000319
320 Set the default "home" directory, that is, the location of the standard
321 Python libraries. The libraries are searched in
322 :file:`{home}/lib/python{version}` and :file:`{home}/lib/python{version}`.
Benjamin Petersonf3d7dbe2009-10-04 14:54:52 +0000323 The argument should point to a zero-terminated character string in static
324 storage whose contents will not change for the duration of the program's
325 execution. No code in the Python interpreter will change the contents of
326 this storage.
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000327
328
Benjamin Petersonb8f68ee2009-09-15 03:38:09 +0000329.. cfunction:: w_char* Py_GetPythonHome()
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000330
331 Return the default "home", that is, the value set by a previous call to
332 :cfunc:`Py_SetPythonHome`, or the value of the :envvar:`PYTHONHOME`
333 environment variable if it is set.
334
335
Georg Brandl116aa622007-08-15 14:28:22 +0000336.. _threads:
337
338Thread State and the Global Interpreter Lock
339============================================
340
341.. index::
342 single: global interpreter lock
343 single: interpreter lock
344 single: lock, interpreter
345
Georg Brandld62ecbf2010-11-26 08:52:36 +0000346The Python interpreter is not fully thread-safe. In order to support
Antoine Pitrou3acd3e92011-01-15 14:19:53 +0000347multi-threaded Python programs, there's a global lock, called the :term:`global
348interpreter lock` or :term:`GIL`, that must be held by the current thread before
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000349it can safely access Python objects. Without the lock, even the simplest
350operations could cause problems in a multi-threaded program: for example, when
351two threads simultaneously increment the reference count of the same object, the
352reference count could end up being incremented only once instead of twice.
Georg Brandl116aa622007-08-15 14:28:22 +0000353
354.. index:: single: setcheckinterval() (in module sys)
355
Antoine Pitrou3acd3e92011-01-15 14:19:53 +0000356Therefore, the rule exists that only the thread that has acquired the
357:term:`GIL` may operate on Python objects or call Python/C API functions.
358In order to emulate concurrency of execution, the interpreter regularly
359tries to switch threads (see :func:`sys.setcheckinterval`). The lock is also
360released around potentially blocking I/O operations like reading or writing
361a file, so that other Python threads can run in the meantime.
Georg Brandl116aa622007-08-15 14:28:22 +0000362
363.. index::
364 single: PyThreadState
365 single: PyThreadState
366
Antoine Pitrou3acd3e92011-01-15 14:19:53 +0000367The Python interpreter keeps some thread-specific bookkeeping information
368inside a data structure called :ctype:`PyThreadState`. There's also one
369global variable pointing to the current :ctype:`PyThreadState`: it can
370be retrieved using :cfunc:`PyThreadState_Get`.
Georg Brandl116aa622007-08-15 14:28:22 +0000371
Antoine Pitrou3acd3e92011-01-15 14:19:53 +0000372Releasing the GIL from extension code
373-------------------------------------
374
375Most extension code manipulating the :term:`GIL` has the following simple
376structure::
Georg Brandl116aa622007-08-15 14:28:22 +0000377
378 Save the thread state in a local variable.
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000379 Release the global interpreter lock.
Antoine Pitrou3acd3e92011-01-15 14:19:53 +0000380 ... Do some blocking I/O operation ...
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000381 Reacquire the global interpreter lock.
Georg Brandl116aa622007-08-15 14:28:22 +0000382 Restore the thread state from the local variable.
383
384This is so common that a pair of macros exists to simplify it::
385
386 Py_BEGIN_ALLOW_THREADS
Antoine Pitrou3acd3e92011-01-15 14:19:53 +0000387 ... Do some blocking I/O operation ...
Georg Brandl116aa622007-08-15 14:28:22 +0000388 Py_END_ALLOW_THREADS
389
390.. index::
391 single: Py_BEGIN_ALLOW_THREADS
392 single: Py_END_ALLOW_THREADS
393
394The :cmacro:`Py_BEGIN_ALLOW_THREADS` macro opens a new block and declares a
395hidden local variable; the :cmacro:`Py_END_ALLOW_THREADS` macro closes the
Antoine Pitrou3acd3e92011-01-15 14:19:53 +0000396block. These two macros are still available when Python is compiled without
397thread support (they simply have an empty expansion).
Georg Brandl116aa622007-08-15 14:28:22 +0000398
399When thread support is enabled, the block above expands to the following code::
400
401 PyThreadState *_save;
402
403 _save = PyEval_SaveThread();
404 ...Do some blocking I/O operation...
405 PyEval_RestoreThread(_save);
406
Georg Brandl116aa622007-08-15 14:28:22 +0000407.. index::
408 single: PyEval_RestoreThread()
Georg Brandl116aa622007-08-15 14:28:22 +0000409 single: PyEval_SaveThread()
Georg Brandl116aa622007-08-15 14:28:22 +0000410
Antoine Pitrou3acd3e92011-01-15 14:19:53 +0000411Here is how these functions work: the global interpreter lock is used to protect the pointer to the
412current thread state. When releasing the lock and saving the thread state,
413the current thread state pointer must be retrieved before the lock is released
414(since another thread could immediately acquire the lock and store its own thread
415state in the global variable). Conversely, when acquiring the lock and restoring
416the thread state, the lock must be acquired before storing the thread state
417pointer.
Georg Brandl116aa622007-08-15 14:28:22 +0000418
Antoine Pitrou3acd3e92011-01-15 14:19:53 +0000419.. note::
420 Calling system I/O functions is the most common use case for releasing
421 the GIL, but it can also be useful before calling long-running computations
422 which don't need access to Python objects, such as compression or
423 cryptographic functions operating over memory buffers. For example, the
424 standard :mod:`zlib` and :mod:`hashlib` modules release the GIL when
425 compressing or hashing data.
Georg Brandl116aa622007-08-15 14:28:22 +0000426
Antoine Pitrou3acd3e92011-01-15 14:19:53 +0000427Non-Python created threads
428--------------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000429
Antoine Pitrou3acd3e92011-01-15 14:19:53 +0000430When threads are created using the dedicated Python APIs (such as the
431:mod:`threading` module), a thread state is automatically associated to them
432and the code showed above is therefore correct. However, when threads are
433created from C (for example by a third-party library with its own thread
434management), they don't hold the GIL, nor is there a thread state structure
435for them.
436
437If you need to call Python code from these threads (often this will be part
438of a callback API provided by the aforementioned third-party library),
439you must first register these threads with the interpreter by
440creating a thread state data structure, then acquiring the GIL, and finally
441storing their thread state pointer, before you can start using the Python/C
442API. When you are done, you should reset the thread state pointer, release
443the GIL, and finally free the thread state data structure.
444
445The :cfunc:`PyGILState_Ensure` and :cfunc:`PyGILState_Release` functions do
446all of the above automatically. The typical idiom for calling into Python
447from a C thread is::
Georg Brandl116aa622007-08-15 14:28:22 +0000448
449 PyGILState_STATE gstate;
450 gstate = PyGILState_Ensure();
451
Antoine Pitrou3acd3e92011-01-15 14:19:53 +0000452 /* Perform Python actions here. */
Georg Brandl116aa622007-08-15 14:28:22 +0000453 result = CallSomeFunction();
Antoine Pitrou3acd3e92011-01-15 14:19:53 +0000454 /* evaluate result or handle exception */
Georg Brandl116aa622007-08-15 14:28:22 +0000455
456 /* Release the thread. No Python API allowed beyond this point. */
457 PyGILState_Release(gstate);
458
459Note that the :cfunc:`PyGILState_\*` functions assume there is only one global
Antoine Pitrou3acd3e92011-01-15 14:19:53 +0000460interpreter (created automatically by :cfunc:`Py_Initialize`). Python
Georg Brandl116aa622007-08-15 14:28:22 +0000461supports the creation of additional interpreters (using
462:cfunc:`Py_NewInterpreter`), but mixing multiple interpreters and the
463:cfunc:`PyGILState_\*` API is unsupported.
464
Benjamin Peterson51838562009-10-04 20:35:30 +0000465Another important thing to note about threads is their behaviour in the face
466of the C :cfunc:`fork` call. On most systems with :cfunc:`fork`, after a
467process forks only the thread that issued the fork will exist. That also
468means any locks held by other threads will never be released. Python solves
469this for :func:`os.fork` by acquiring the locks it uses internally before
470the fork, and releasing them afterwards. In addition, it resets any
471:ref:`lock-objects` in the child. When extending or embedding Python, there
472is no way to inform Python of additional (non-Python) locks that need to be
473acquired before or reset after a fork. OS facilities such as
474:cfunc:`posix_atfork` would need to be used to accomplish the same thing.
475Additionally, when extending or embedding Python, calling :cfunc:`fork`
476directly rather than through :func:`os.fork` (and returning to or calling
477into Python) may result in a deadlock by one of Python's internal locks
478being held by a thread that is defunct after the fork.
479:cfunc:`PyOS_AfterFork` tries to reset the necessary locks, but is not
480always able to.
Georg Brandl116aa622007-08-15 14:28:22 +0000481
Antoine Pitrou3acd3e92011-01-15 14:19:53 +0000482
483High-level API
484--------------
485
486These are the most commonly used types and functions when writing C extension
487code, or when embedding the Python interpreter:
488
Georg Brandl116aa622007-08-15 14:28:22 +0000489.. ctype:: PyInterpreterState
490
491 This data structure represents the state shared by a number of cooperating
492 threads. Threads belonging to the same interpreter share their module
493 administration and a few other internal items. There are no public members in
494 this structure.
495
496 Threads belonging to different interpreters initially share nothing, except
497 process state like available memory, open file descriptors and such. The global
498 interpreter lock is also shared by all threads, regardless of to which
499 interpreter they belong.
500
501
502.. ctype:: PyThreadState
503
504 This data structure represents the state of a single thread. The only public
505 data member is :ctype:`PyInterpreterState \*`:attr:`interp`, which points to
506 this thread's interpreter state.
507
508
509.. cfunction:: void PyEval_InitThreads()
510
511 .. index::
512 single: PyEval_ReleaseLock()
513 single: PyEval_ReleaseThread()
514 single: PyEval_SaveThread()
515 single: PyEval_RestoreThread()
516
517 Initialize and acquire the global interpreter lock. It should be called in the
518 main thread before creating a second thread or engaging in any other thread
519 operations such as :cfunc:`PyEval_ReleaseLock` or
520 ``PyEval_ReleaseThread(tstate)``. It is not needed before calling
521 :cfunc:`PyEval_SaveThread` or :cfunc:`PyEval_RestoreThread`.
522
523 .. index:: single: Py_Initialize()
524
525 This is a no-op when called for a second time. It is safe to call this function
526 before calling :cfunc:`Py_Initialize`.
527
Georg Brandl2067bfd2008-05-25 13:05:15 +0000528 .. index:: module: _thread
Georg Brandl116aa622007-08-15 14:28:22 +0000529
Antoine Pitrou3acd3e92011-01-15 14:19:53 +0000530 .. note::
531 When only the main thread exists, no GIL operations are needed. This is a
532 common situation (most Python programs do not use threads), and the lock
533 operations slow the interpreter down a bit. Therefore, the lock is not
534 created initially. This situation is equivalent to having acquired the lock:
535 when there is only a single thread, all object accesses are safe. Therefore,
536 when this function initializes the global interpreter lock, it also acquires
537 it. Before the Python :mod:`_thread` module creates a new thread, knowing
538 that either it has the lock or the lock hasn't been created yet, it calls
539 :cfunc:`PyEval_InitThreads`. When this call returns, it is guaranteed that
540 the lock has been created and that the calling thread has acquired it.
Georg Brandl116aa622007-08-15 14:28:22 +0000541
Antoine Pitrou3acd3e92011-01-15 14:19:53 +0000542 It is **not** safe to call this function when it is unknown which thread (if
543 any) currently has the global interpreter lock.
Georg Brandl116aa622007-08-15 14:28:22 +0000544
Antoine Pitrou3acd3e92011-01-15 14:19:53 +0000545 This function is not available when thread support is disabled at compile time.
Georg Brandl116aa622007-08-15 14:28:22 +0000546
547
548.. cfunction:: int PyEval_ThreadsInitialized()
549
550 Returns a non-zero value if :cfunc:`PyEval_InitThreads` has been called. This
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000551 function can be called without holding the GIL, and therefore can be used to
Georg Brandl116aa622007-08-15 14:28:22 +0000552 avoid calls to the locking API when running single-threaded. This function is
553 not available when thread support is disabled at compile time.
554
Georg Brandl116aa622007-08-15 14:28:22 +0000555
Georg Brandl116aa622007-08-15 14:28:22 +0000556.. cfunction:: PyThreadState* PyEval_SaveThread()
557
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000558 Release the global interpreter lock (if it has been created and thread
559 support is enabled) and reset the thread state to *NULL*, returning the
560 previous thread state (which is not *NULL*). If the lock has been created,
561 the current thread must have acquired it. (This function is available even
562 when thread support is disabled at compile time.)
Georg Brandl116aa622007-08-15 14:28:22 +0000563
564
565.. cfunction:: void PyEval_RestoreThread(PyThreadState *tstate)
566
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000567 Acquire the global interpreter lock (if it has been created and thread
568 support is enabled) and set the thread state to *tstate*, which must not be
569 *NULL*. If the lock has been created, the current thread must not have
570 acquired it, otherwise deadlock ensues. (This function is available even
571 when thread support is disabled at compile time.)
Georg Brandl116aa622007-08-15 14:28:22 +0000572
Christian Heimesd8654cf2007-12-02 15:22:16 +0000573
Antoine Pitrou3acd3e92011-01-15 14:19:53 +0000574.. cfunction:: PyThreadState* PyThreadState_Get()
575
576 Return the current thread state. The global interpreter lock must be held.
577 When the current thread state is *NULL*, this issues a fatal error (so that
578 the caller needn't check for *NULL*).
579
580
581.. cfunction:: PyThreadState* PyThreadState_Swap(PyThreadState *tstate)
582
583 Swap the current thread state with the thread state given by the argument
584 *tstate*, which may be *NULL*. The global interpreter lock must be held
585 and is not released.
586
587
Christian Heimesd8654cf2007-12-02 15:22:16 +0000588.. cfunction:: void PyEval_ReInitThreads()
589
590 This function is called from :cfunc:`PyOS_AfterFork` to ensure that newly
591 created child processes don't hold locks referring to threads which
592 are not running in the child process.
593
594
Antoine Pitrou3acd3e92011-01-15 14:19:53 +0000595The following functions use thread-local storage, and are not compatible
596with sub-interpreters:
597
598.. cfunction:: PyGILState_STATE PyGILState_Ensure()
599
600 Ensure that the current thread is ready to call the Python C API regardless
601 of the current state of Python, or of the global interpreter lock. This may
602 be called as many times as desired by a thread as long as each call is
603 matched with a call to :cfunc:`PyGILState_Release`. In general, other
604 thread-related APIs may be used between :cfunc:`PyGILState_Ensure` and
605 :cfunc:`PyGILState_Release` calls as long as the thread state is restored to
606 its previous state before the Release(). For example, normal usage of the
607 :cmacro:`Py_BEGIN_ALLOW_THREADS` and :cmacro:`Py_END_ALLOW_THREADS` macros is
608 acceptable.
609
610 The return value is an opaque "handle" to the thread state when
611 :cfunc:`PyGILState_Ensure` was called, and must be passed to
612 :cfunc:`PyGILState_Release` to ensure Python is left in the same state. Even
613 though recursive calls are allowed, these handles *cannot* be shared - each
614 unique call to :cfunc:`PyGILState_Ensure` must save the handle for its call
615 to :cfunc:`PyGILState_Release`.
616
617 When the function returns, the current thread will hold the GIL and be able
618 to call arbitrary Python code. Failure is a fatal error.
619
620
621.. cfunction:: void PyGILState_Release(PyGILState_STATE)
622
623 Release any resources previously acquired. After this call, Python's state will
624 be the same as it was prior to the corresponding :cfunc:`PyGILState_Ensure` call
625 (but generally this state will be unknown to the caller, hence the use of the
626 GILState API).
627
628 Every call to :cfunc:`PyGILState_Ensure` must be matched by a call to
629 :cfunc:`PyGILState_Release` on the same thread.
630
631
Georg Brandl116aa622007-08-15 14:28:22 +0000632The following macros are normally used without a trailing semicolon; look for
633example usage in the Python source distribution.
634
635
636.. cmacro:: Py_BEGIN_ALLOW_THREADS
637
638 This macro expands to ``{ PyThreadState *_save; _save = PyEval_SaveThread();``.
639 Note that it contains an opening brace; it must be matched with a following
640 :cmacro:`Py_END_ALLOW_THREADS` macro. See above for further discussion of this
641 macro. It is a no-op when thread support is disabled at compile time.
642
643
644.. cmacro:: Py_END_ALLOW_THREADS
645
646 This macro expands to ``PyEval_RestoreThread(_save); }``. Note that it contains
647 a closing brace; it must be matched with an earlier
648 :cmacro:`Py_BEGIN_ALLOW_THREADS` macro. See above for further discussion of
649 this macro. It is a no-op when thread support is disabled at compile time.
650
651
652.. cmacro:: Py_BLOCK_THREADS
653
654 This macro expands to ``PyEval_RestoreThread(_save);``: it is equivalent to
655 :cmacro:`Py_END_ALLOW_THREADS` without the closing brace. It is a no-op when
656 thread support is disabled at compile time.
657
658
659.. cmacro:: Py_UNBLOCK_THREADS
660
661 This macro expands to ``_save = PyEval_SaveThread();``: it is equivalent to
662 :cmacro:`Py_BEGIN_ALLOW_THREADS` without the opening brace and variable
663 declaration. It is a no-op when thread support is disabled at compile time.
664
Antoine Pitrou3acd3e92011-01-15 14:19:53 +0000665
666Low-level API
667-------------
668
Georg Brandl116aa622007-08-15 14:28:22 +0000669All of the following functions are only available when thread support is enabled
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000670at compile time, and must be called only when the global interpreter lock has
671been created.
Georg Brandl116aa622007-08-15 14:28:22 +0000672
673
674.. cfunction:: PyInterpreterState* PyInterpreterState_New()
675
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000676 Create a new interpreter state object. The global interpreter lock need not
677 be held, but may be held if it is necessary to serialize calls to this
678 function.
Georg Brandl116aa622007-08-15 14:28:22 +0000679
680
681.. cfunction:: void PyInterpreterState_Clear(PyInterpreterState *interp)
682
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000683 Reset all information in an interpreter state object. The global interpreter
684 lock must be held.
Georg Brandl116aa622007-08-15 14:28:22 +0000685
686
687.. cfunction:: void PyInterpreterState_Delete(PyInterpreterState *interp)
688
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000689 Destroy an interpreter state object. The global interpreter lock need not be
690 held. The interpreter state must have been reset with a previous call to
Georg Brandl116aa622007-08-15 14:28:22 +0000691 :cfunc:`PyInterpreterState_Clear`.
692
693
694.. cfunction:: PyThreadState* PyThreadState_New(PyInterpreterState *interp)
695
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000696 Create a new thread state object belonging to the given interpreter object.
697 The global interpreter lock need not be held, but may be held if it is
698 necessary to serialize calls to this function.
Georg Brandl116aa622007-08-15 14:28:22 +0000699
700
701.. cfunction:: void PyThreadState_Clear(PyThreadState *tstate)
702
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000703 Reset all information in a thread state object. The global interpreter lock
704 must be held.
Georg Brandl116aa622007-08-15 14:28:22 +0000705
706
707.. cfunction:: void PyThreadState_Delete(PyThreadState *tstate)
708
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000709 Destroy a thread state object. The global interpreter lock need not be held.
710 The thread state must have been reset with a previous call to
Georg Brandl116aa622007-08-15 14:28:22 +0000711 :cfunc:`PyThreadState_Clear`.
712
713
Georg Brandl116aa622007-08-15 14:28:22 +0000714.. cfunction:: PyObject* PyThreadState_GetDict()
715
716 Return a dictionary in which extensions can store thread-specific state
717 information. Each extension should use a unique key to use to store state in
718 the dictionary. It is okay to call this function when no current thread state
719 is available. If this function returns *NULL*, no exception has been raised and
720 the caller should assume no current thread state is available.
721
Georg Brandl116aa622007-08-15 14:28:22 +0000722
723.. cfunction:: int PyThreadState_SetAsyncExc(long id, PyObject *exc)
724
725 Asynchronously raise an exception in a thread. The *id* argument is the thread
726 id of the target thread; *exc* is the exception object to be raised. This
727 function does not steal any references to *exc*. To prevent naive misuse, you
728 must write your own C extension to call this. Must be called with the GIL held.
729 Returns the number of thread states modified; this is normally one, but will be
730 zero if the thread id isn't found. If *exc* is :const:`NULL`, the pending
731 exception (if any) for the thread is cleared. This raises no exceptions.
732
Georg Brandl116aa622007-08-15 14:28:22 +0000733
Antoine Pitrou3acd3e92011-01-15 14:19:53 +0000734.. cfunction:: void PyEval_AcquireThread(PyThreadState *tstate)
Georg Brandl116aa622007-08-15 14:28:22 +0000735
Antoine Pitrou3acd3e92011-01-15 14:19:53 +0000736 Acquire the global interpreter lock and set the current thread state to
737 *tstate*, which should not be *NULL*. The lock must have been created earlier.
738 If this thread already has the lock, deadlock ensues.
Georg Brandl116aa622007-08-15 14:28:22 +0000739
Antoine Pitrou3acd3e92011-01-15 14:19:53 +0000740 :cfunc:`PyEval_RestoreThread` is a higher-level function which is always
741 available (even when thread support isn't enabled or when threads have
742 not been initialized).
Georg Brandl116aa622007-08-15 14:28:22 +0000743
Georg Brandl116aa622007-08-15 14:28:22 +0000744
Antoine Pitrou3acd3e92011-01-15 14:19:53 +0000745.. cfunction:: void PyEval_ReleaseThread(PyThreadState *tstate)
Georg Brandl116aa622007-08-15 14:28:22 +0000746
Antoine Pitrou3acd3e92011-01-15 14:19:53 +0000747 Reset the current thread state to *NULL* and release the global interpreter
748 lock. The lock must have been created earlier and must be held by the current
749 thread. The *tstate* argument, which must not be *NULL*, is only used to check
750 that it represents the current thread state --- if it isn't, a fatal error is
751 reported.
Georg Brandl116aa622007-08-15 14:28:22 +0000752
Antoine Pitrou3acd3e92011-01-15 14:19:53 +0000753 :cfunc:`PyEval_SaveThread` is a higher-level function which is always
754 available (even when thread support isn't enabled or when threads have
755 not been initialized).
Georg Brandl116aa622007-08-15 14:28:22 +0000756
Georg Brandl116aa622007-08-15 14:28:22 +0000757
Antoine Pitrou3acd3e92011-01-15 14:19:53 +0000758.. cfunction:: void PyEval_AcquireLock()
759
760 Acquire the global interpreter lock. The lock must have been created earlier.
761 If this thread already has the lock, a deadlock ensues.
762
763 .. warning::
764 This function does not change the current thread state. Please use
765 :cfunc:`PyEval_RestoreThread` or :cfunc:`PyEval_AcquireThread`
766 instead.
767
768
769.. cfunction:: void PyEval_ReleaseLock()
770
771 Release the global interpreter lock. The lock must have been created earlier.
772
773 .. warning::
774 This function does not change the current thread state. Please use
775 :cfunc:`PyEval_SaveThread` or :cfunc:`PyEval_ReleaseThread`
776 instead.
777
778
779Sub-interpreter support
780=======================
781
782While in most uses, you will only embed a single Python interpreter, there
783are cases where you need to create several independent interpreters in the
784same process and perhaps even in the same thread. Sub-interpreters allow
785you to do that. You can switch between sub-interpreters using the
786:cfunc:`PyThreadState_Swap` function. You can create and destroy them
787using the following functions:
788
789
790.. cfunction:: PyThreadState* Py_NewInterpreter()
791
792 .. index::
793 module: builtins
794 module: __main__
795 module: sys
796 single: stdout (in module sys)
797 single: stderr (in module sys)
798 single: stdin (in module sys)
799
800 Create a new sub-interpreter. This is an (almost) totally separate environment
801 for the execution of Python code. In particular, the new interpreter has
802 separate, independent versions of all imported modules, including the
803 fundamental modules :mod:`builtins`, :mod:`__main__` and :mod:`sys`. The
804 table of loaded modules (``sys.modules``) and the module search path
805 (``sys.path``) are also separate. The new environment has no ``sys.argv``
806 variable. It has new standard I/O stream file objects ``sys.stdin``,
807 ``sys.stdout`` and ``sys.stderr`` (however these refer to the same underlying
808 file descriptors).
809
810 The return value points to the first thread state created in the new
811 sub-interpreter. This thread state is made in the current thread state.
812 Note that no actual thread is created; see the discussion of thread states
813 below. If creation of the new interpreter is unsuccessful, *NULL* is
814 returned; no exception is set since the exception state is stored in the
815 current thread state and there may not be a current thread state. (Like all
816 other Python/C API functions, the global interpreter lock must be held before
817 calling this function and is still held when it returns; however, unlike most
818 other Python/C API functions, there needn't be a current thread state on
819 entry.)
820
821 .. index::
822 single: Py_Finalize()
823 single: Py_Initialize()
824
825 Extension modules are shared between (sub-)interpreters as follows: the first
826 time a particular extension is imported, it is initialized normally, and a
827 (shallow) copy of its module's dictionary is squirreled away. When the same
828 extension is imported by another (sub-)interpreter, a new module is initialized
829 and filled with the contents of this copy; the extension's ``init`` function is
830 not called. Note that this is different from what happens when an extension is
831 imported after the interpreter has been completely re-initialized by calling
832 :cfunc:`Py_Finalize` and :cfunc:`Py_Initialize`; in that case, the extension's
833 ``initmodule`` function *is* called again.
834
835 .. index:: single: close() (in module os)
836
837
838.. cfunction:: void Py_EndInterpreter(PyThreadState *tstate)
839
840 .. index:: single: Py_Finalize()
841
842 Destroy the (sub-)interpreter represented by the given thread state. The given
843 thread state must be the current thread state. See the discussion of thread
844 states below. When the call returns, the current thread state is *NULL*. All
845 thread states associated with this interpreter are destroyed. (The global
846 interpreter lock must be held before calling this function and is still held
847 when it returns.) :cfunc:`Py_Finalize` will destroy all sub-interpreters that
848 haven't been explicitly destroyed at that point.
849
850
851Bugs and caveats
852----------------
853
854Because sub-interpreters (and the main interpreter) are part of the same
855process, the insulation between them isn't perfect --- for example, using
856low-level file operations like :func:`os.close` they can
857(accidentally or maliciously) affect each other's open files. Because of the
858way extensions are shared between (sub-)interpreters, some extensions may not
859work properly; this is especially likely when the extension makes use of
860(static) global variables, or when the extension manipulates its module's
861dictionary after its initialization. It is possible to insert objects created
862in one sub-interpreter into a namespace of another sub-interpreter; this should
863be done with great care to avoid sharing user-defined functions, methods,
864instances or classes between sub-interpreters, since import operations executed
865by such objects may affect the wrong (sub-)interpreter's dictionary of loaded
866modules.
867
868Also note that combining this functionality with :cfunc:`PyGILState_\*` APIs
869is delicate, become these APIs assume a bijection between Python thread states
870and OS-level threads, an assumption broken by the presence of sub-interpreters.
871It is highly recommended that you don't switch sub-interpreters between a pair
872of matching :cfunc:`PyGILState_Ensure` and :cfunc:`PyGILState_Release` calls.
873Furthermore, extensions (such as :mod:`ctypes`) using these APIs to allow calling
874of Python code from non-Python created threads will probably be broken when using
875sub-interpreters.
876
Benjamin Petersona54c9092009-01-13 02:11:23 +0000877
878Asynchronous Notifications
879==========================
880
Benjamin Petersond23f8222009-04-05 19:13:16 +0000881A mechanism is provided to make asynchronous notifications to the main
Benjamin Petersona54c9092009-01-13 02:11:23 +0000882interpreter thread. These notifications take the form of a function
883pointer and a void argument.
884
885.. index:: single: setcheckinterval() (in module sys)
886
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000887Every check interval, when the global interpreter lock is released and
Ezio Melotti890c1932009-12-19 23:33:46 +0000888reacquired, Python will also call any such provided functions. This can be used
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000889for example by asynchronous IO handlers. The notification can be scheduled from
890a worker thread and the actual call than made at the earliest convenience by the
891main thread where it has possession of the global interpreter lock and can
892perform any Python API calls.
Benjamin Petersona54c9092009-01-13 02:11:23 +0000893
Benjamin Petersonb5479792009-01-18 22:10:38 +0000894.. cfunction:: void Py_AddPendingCall( int (*func)(void *, void *arg) )
Benjamin Petersona54c9092009-01-13 02:11:23 +0000895
896 .. index:: single: Py_AddPendingCall()
897
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000898 Post a notification to the Python main thread. If successful, *func* will be
899 called with the argument *arg* at the earliest convenience. *func* will be
900 called having the global interpreter lock held and can thus use the full
901 Python API and can take any action such as setting object attributes to
902 signal IO completion. It must return 0 on success, or -1 signalling an
903 exception. The notification function won't be interrupted to perform another
904 asynchronous notification recursively, but it can still be interrupted to
905 switch threads if the global interpreter lock is released, for example, if it
Ezio Melotti890c1932009-12-19 23:33:46 +0000906 calls back into Python code.
Benjamin Petersona54c9092009-01-13 02:11:23 +0000907
908 This function returns 0 on success in which case the notification has been
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000909 scheduled. Otherwise, for example if the notification buffer is full, it
910 returns -1 without setting any exception.
Benjamin Petersona54c9092009-01-13 02:11:23 +0000911
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000912 This function can be called on any thread, be it a Python thread or some
913 other system thread. If it is a Python thread, it doesn't matter if it holds
914 the global interpreter lock or not.
Benjamin Petersona54c9092009-01-13 02:11:23 +0000915
Georg Brandl705d9d52009-05-05 09:29:50 +0000916 .. versionadded:: 3.1
Benjamin Petersona54c9092009-01-13 02:11:23 +0000917
918
Georg Brandl116aa622007-08-15 14:28:22 +0000919.. _profiling:
920
921Profiling and Tracing
922=====================
923
924.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
925
926
927The Python interpreter provides some low-level support for attaching profiling
928and execution tracing facilities. These are used for profiling, debugging, and
929coverage analysis tools.
930
Georg Brandle6bcc912008-05-12 18:05:20 +0000931This C interface allows the profiling or tracing code to avoid the overhead of
932calling through Python-level callable objects, making a direct C function call
933instead. The essential attributes of the facility have not changed; the
934interface allows trace functions to be installed per-thread, and the basic
935events reported to the trace function are the same as had been reported to the
936Python-level trace functions in previous versions.
Georg Brandl116aa622007-08-15 14:28:22 +0000937
938
939.. ctype:: int (*Py_tracefunc)(PyObject *obj, PyFrameObject *frame, int what, PyObject *arg)
940
941 The type of the trace function registered using :cfunc:`PyEval_SetProfile` and
942 :cfunc:`PyEval_SetTrace`. The first parameter is the object passed to the
943 registration function as *obj*, *frame* is the frame object to which the event
944 pertains, *what* is one of the constants :const:`PyTrace_CALL`,
945 :const:`PyTrace_EXCEPTION`, :const:`PyTrace_LINE`, :const:`PyTrace_RETURN`,
946 :const:`PyTrace_C_CALL`, :const:`PyTrace_C_EXCEPTION`, or
947 :const:`PyTrace_C_RETURN`, and *arg* depends on the value of *what*:
948
949 +------------------------------+--------------------------------------+
950 | Value of *what* | Meaning of *arg* |
951 +==============================+======================================+
952 | :const:`PyTrace_CALL` | Always *NULL*. |
953 +------------------------------+--------------------------------------+
954 | :const:`PyTrace_EXCEPTION` | Exception information as returned by |
955 | | :func:`sys.exc_info`. |
956 +------------------------------+--------------------------------------+
957 | :const:`PyTrace_LINE` | Always *NULL*. |
958 +------------------------------+--------------------------------------+
Georg Brandlc524cff2010-11-26 08:42:45 +0000959 | :const:`PyTrace_RETURN` | Value being returned to the caller, |
960 | | or *NULL* if caused by an exception. |
Georg Brandl116aa622007-08-15 14:28:22 +0000961 +------------------------------+--------------------------------------+
Georg Brandlc524cff2010-11-26 08:42:45 +0000962 | :const:`PyTrace_C_CALL` | Function object being called. |
Georg Brandl116aa622007-08-15 14:28:22 +0000963 +------------------------------+--------------------------------------+
Georg Brandlc524cff2010-11-26 08:42:45 +0000964 | :const:`PyTrace_C_EXCEPTION` | Function object being called. |
Georg Brandl116aa622007-08-15 14:28:22 +0000965 +------------------------------+--------------------------------------+
Georg Brandlc524cff2010-11-26 08:42:45 +0000966 | :const:`PyTrace_C_RETURN` | Function object being called. |
Georg Brandl116aa622007-08-15 14:28:22 +0000967 +------------------------------+--------------------------------------+
968
969
970.. cvar:: int PyTrace_CALL
971
972 The value of the *what* parameter to a :ctype:`Py_tracefunc` function when a new
973 call to a function or method is being reported, or a new entry into a generator.
974 Note that the creation of the iterator for a generator function is not reported
975 as there is no control transfer to the Python bytecode in the corresponding
976 frame.
977
978
979.. cvar:: int PyTrace_EXCEPTION
980
981 The value of the *what* parameter to a :ctype:`Py_tracefunc` function when an
982 exception has been raised. The callback function is called with this value for
983 *what* when after any bytecode is processed after which the exception becomes
984 set within the frame being executed. The effect of this is that as exception
985 propagation causes the Python stack to unwind, the callback is called upon
986 return to each frame as the exception propagates. Only trace functions receives
987 these events; they are not needed by the profiler.
988
989
990.. cvar:: int PyTrace_LINE
991
992 The value passed as the *what* parameter to a trace function (but not a
993 profiling function) when a line-number event is being reported.
994
995
996.. cvar:: int PyTrace_RETURN
997
998 The value for the *what* parameter to :ctype:`Py_tracefunc` functions when a
999 call is returning without propagating an exception.
1000
1001
1002.. cvar:: int PyTrace_C_CALL
1003
1004 The value for the *what* parameter to :ctype:`Py_tracefunc` functions when a C
1005 function is about to be called.
1006
1007
1008.. cvar:: int PyTrace_C_EXCEPTION
1009
1010 The value for the *what* parameter to :ctype:`Py_tracefunc` functions when a C
Georg Brandl13f959b2010-10-06 08:35:38 +00001011 function has raised an exception.
Georg Brandl116aa622007-08-15 14:28:22 +00001012
1013
1014.. cvar:: int PyTrace_C_RETURN
1015
1016 The value for the *what* parameter to :ctype:`Py_tracefunc` functions when a C
1017 function has returned.
1018
1019
1020.. cfunction:: void PyEval_SetProfile(Py_tracefunc func, PyObject *obj)
1021
1022 Set the profiler function to *func*. The *obj* parameter is passed to the
1023 function as its first parameter, and may be any Python object, or *NULL*. If
1024 the profile function needs to maintain state, using a different value for *obj*
1025 for each thread provides a convenient and thread-safe place to store it. The
1026 profile function is called for all monitored events except the line-number
1027 events.
1028
1029
1030.. cfunction:: void PyEval_SetTrace(Py_tracefunc func, PyObject *obj)
1031
1032 Set the tracing function to *func*. This is similar to
1033 :cfunc:`PyEval_SetProfile`, except the tracing function does receive line-number
1034 events.
1035
Christian Heimesd8654cf2007-12-02 15:22:16 +00001036.. cfunction:: PyObject* PyEval_GetCallStats(PyObject *self)
1037
1038 Return a tuple of function call counts. There are constants defined for the
1039 positions within the tuple:
Georg Brandl48310cd2009-01-03 21:18:54 +00001040
Christian Heimesd8654cf2007-12-02 15:22:16 +00001041 +-------------------------------+-------+
1042 | Name | Value |
1043 +===============================+=======+
1044 | :const:`PCALL_ALL` | 0 |
1045 +-------------------------------+-------+
1046 | :const:`PCALL_FUNCTION` | 1 |
1047 +-------------------------------+-------+
1048 | :const:`PCALL_FAST_FUNCTION` | 2 |
1049 +-------------------------------+-------+
1050 | :const:`PCALL_FASTER_FUNCTION`| 3 |
1051 +-------------------------------+-------+
1052 | :const:`PCALL_METHOD` | 4 |
1053 +-------------------------------+-------+
1054 | :const:`PCALL_BOUND_METHOD` | 5 |
1055 +-------------------------------+-------+
1056 | :const:`PCALL_CFUNCTION` | 6 |
1057 +-------------------------------+-------+
1058 | :const:`PCALL_TYPE` | 7 |
1059 +-------------------------------+-------+
1060 | :const:`PCALL_GENERATOR` | 8 |
1061 +-------------------------------+-------+
1062 | :const:`PCALL_OTHER` | 9 |
1063 +-------------------------------+-------+
1064 | :const:`PCALL_POP` | 10 |
1065 +-------------------------------+-------+
Georg Brandl48310cd2009-01-03 21:18:54 +00001066
Christian Heimesd8654cf2007-12-02 15:22:16 +00001067 :const:`PCALL_FAST_FUNCTION` means no argument tuple needs to be created.
1068 :const:`PCALL_FASTER_FUNCTION` means that the fast-path frame setup code is used.
1069
1070 If there is a method call where the call can be optimized by changing
1071 the argument tuple and calling the function directly, it gets recorded
1072 twice.
1073
1074 This function is only present if Python is compiled with :const:`CALL_PROFILE`
1075 defined.
Georg Brandl116aa622007-08-15 14:28:22 +00001076
1077.. _advanced-debugging:
1078
1079Advanced Debugger Support
1080=========================
1081
1082.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
1083
1084
1085These functions are only intended to be used by advanced debugging tools.
1086
1087
1088.. cfunction:: PyInterpreterState* PyInterpreterState_Head()
1089
1090 Return the interpreter state object at the head of the list of all such objects.
1091
Georg Brandl116aa622007-08-15 14:28:22 +00001092
1093.. cfunction:: PyInterpreterState* PyInterpreterState_Next(PyInterpreterState *interp)
1094
1095 Return the next interpreter state object after *interp* from the list of all
1096 such objects.
1097
Georg Brandl116aa622007-08-15 14:28:22 +00001098
1099.. cfunction:: PyThreadState * PyInterpreterState_ThreadHead(PyInterpreterState *interp)
1100
1101 Return the a pointer to the first :ctype:`PyThreadState` object in the list of
1102 threads associated with the interpreter *interp*.
1103
Georg Brandl116aa622007-08-15 14:28:22 +00001104
1105.. cfunction:: PyThreadState* PyThreadState_Next(PyThreadState *tstate)
1106
1107 Return the next thread state object after *tstate* from the list of all such
1108 objects belonging to the same :ctype:`PyInterpreterState` object.
1109