blob: 305d477fbf27214c2bb7f06c68e62dbde22983e8 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001
2:mod:`sys` --- System-specific parameters and functions
3=======================================================
4
5.. module:: sys
6 :synopsis: Access system-specific parameters and functions.
7
8
9This module provides access to some variables used or maintained by the
10interpreter and to functions that interact strongly with the interpreter. It is
11always available.
12
13
14.. data:: argv
15
16 The list of command line arguments passed to a Python script. ``argv[0]`` is the
17 script name (it is operating system dependent whether this is a full pathname or
18 not). If the command was executed using the :option:`-c` command line option to
19 the interpreter, ``argv[0]`` is set to the string ``'-c'``. If no script name
20 was passed to the Python interpreter, ``argv[0]`` is the empty string.
21
22 To loop over the standard input, or the list of files given on the
23 command line, see the :mod:`fileinput` module.
24
25
26.. data:: byteorder
27
28 An indicator of the native byte order. This will have the value ``'big'`` on
29 big-endian (most-significant byte first) platforms, and ``'little'`` on
30 little-endian (least-significant byte first) platforms.
31
32 .. versionadded:: 2.0
33
34
35.. data:: subversion
36
37 A triple (repo, branch, version) representing the Subversion information of the
38 Python interpreter. *repo* is the name of the repository, ``'CPython'``.
39 *branch* is a string of one of the forms ``'trunk'``, ``'branches/name'`` or
40 ``'tags/name'``. *version* is the output of ``svnversion``, if the interpreter
41 was built from a Subversion checkout; it contains the revision number (range)
42 and possibly a trailing 'M' if there were local modifications. If the tree was
43 exported (or svnversion was not available), it is the revision of
44 ``Include/patchlevel.h`` if the branch is a tag. Otherwise, it is ``None``.
45
46 .. versionadded:: 2.5
47
48
49.. data:: builtin_module_names
50
51 A tuple of strings giving the names of all modules that are compiled into this
52 Python interpreter. (This information is not available in any other way ---
53 ``modules.keys()`` only lists the imported modules.)
54
55
Georg Brandlb8d0e362010-11-26 07:53:50 +000056.. function:: call_tracing(func, args)
57
58 Call ``func(*args)``, while tracing is enabled. The tracing state is saved,
59 and restored afterwards. This is intended to be called from a debugger from
60 a checkpoint, to recursively debug some other code.
61
62
Georg Brandl8ec7f652007-08-15 14:28:01 +000063.. data:: copyright
64
65 A string containing the copyright pertaining to the Python interpreter.
66
67
Christian Heimes422051a2008-02-04 18:00:12 +000068.. function:: _clear_type_cache()
69
70 Clear the internal type cache. The type cache is used to speed up attribute
71 and method lookups. Use the function *only* to drop unnecessary references
72 during reference leak debugging.
73
74 This function should be used for internal and specialized purposes only.
Christian Heimes908caac2008-01-27 23:34:59 +000075
76 .. versionadded:: 2.6
77
78
Georg Brandl8ec7f652007-08-15 14:28:01 +000079.. function:: _current_frames()
80
81 Return a dictionary mapping each thread's identifier to the topmost stack frame
82 currently active in that thread at the time the function is called. Note that
83 functions in the :mod:`traceback` module can build the call stack given such a
84 frame.
85
86 This is most useful for debugging deadlock: this function does not require the
87 deadlocked threads' cooperation, and such threads' call stacks are frozen for as
88 long as they remain deadlocked. The frame returned for a non-deadlocked thread
89 may bear no relationship to that thread's current activity by the time calling
90 code examines the frame.
91
92 This function should be used for internal and specialized purposes only.
93
94 .. versionadded:: 2.5
95
96
97.. data:: dllhandle
98
99 Integer specifying the handle of the Python DLL. Availability: Windows.
100
101
102.. function:: displayhook(value)
103
104 If *value* is not ``None``, this function prints it to ``sys.stdout``, and saves
105 it in ``__builtin__._``.
106
Georg Brandl584265b2007-12-02 14:58:50 +0000107 ``sys.displayhook`` is called on the result of evaluating an :term:`expression`
108 entered in an interactive Python session. The display of these values can be
109 customized by assigning another one-argument function to ``sys.displayhook``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000110
111
112.. function:: excepthook(type, value, traceback)
113
114 This function prints out a given traceback and exception to ``sys.stderr``.
115
116 When an exception is raised and uncaught, the interpreter calls
117 ``sys.excepthook`` with three arguments, the exception class, exception
118 instance, and a traceback object. In an interactive session this happens just
119 before control is returned to the prompt; in a Python program this happens just
120 before the program exits. The handling of such top-level exceptions can be
121 customized by assigning another three-argument function to ``sys.excepthook``.
122
123
124.. data:: __displayhook__
125 __excepthook__
126
127 These objects contain the original values of ``displayhook`` and ``excepthook``
128 at the start of the program. They are saved so that ``displayhook`` and
129 ``excepthook`` can be restored in case they happen to get replaced with broken
130 objects.
131
132
133.. function:: exc_info()
134
135 This function returns a tuple of three values that give information about the
136 exception that is currently being handled. The information returned is specific
137 both to the current thread and to the current stack frame. If the current stack
138 frame is not handling an exception, the information is taken from the calling
139 stack frame, or its caller, and so on until a stack frame is found that is
140 handling an exception. Here, "handling an exception" is defined as "executing
141 or having executed an except clause." For any stack frame, only information
142 about the most recently handled exception is accessible.
143
144 .. index:: object: traceback
145
146 If no exception is being handled anywhere on the stack, a tuple containing three
147 ``None`` values is returned. Otherwise, the values returned are ``(type, value,
148 traceback)``. Their meaning is: *type* gets the exception type of the exception
149 being handled (a class object); *value* gets the exception parameter (its
150 :dfn:`associated value` or the second argument to :keyword:`raise`, which is
151 always a class instance if the exception type is a class object); *traceback*
152 gets a traceback object (see the Reference Manual) which encapsulates the call
153 stack at the point where the exception originally occurred.
154
155 If :func:`exc_clear` is called, this function will return three ``None`` values
156 until either another exception is raised in the current thread or the execution
157 stack returns to a frame where another exception is being handled.
158
159 .. warning::
160
161 Assigning the *traceback* return value to a local variable in a function that is
162 handling an exception will cause a circular reference. This will prevent
163 anything referenced by a local variable in the same function or by the traceback
164 from being garbage collected. Since most functions don't need access to the
165 traceback, the best solution is to use something like ``exctype, value =
166 sys.exc_info()[:2]`` to extract only the exception type and value. If you do
167 need the traceback, make sure to delete it after use (best done with a
168 :keyword:`try` ... :keyword:`finally` statement) or to call :func:`exc_info` in
169 a function that does not itself handle an exception.
170
171 .. note::
172
173 Beginning with Python 2.2, such cycles are automatically reclaimed when garbage
174 collection is enabled and they become unreachable, but it remains more efficient
175 to avoid creating cycles.
176
177
178.. function:: exc_clear()
179
180 This function clears all information relating to the current or last exception
181 that occurred in the current thread. After calling this function,
182 :func:`exc_info` will return three ``None`` values until another exception is
183 raised in the current thread or the execution stack returns to a frame where
184 another exception is being handled.
185
186 This function is only needed in only a few obscure situations. These include
187 logging and error handling systems that report information on the last or
188 current exception. This function can also be used to try to free resources and
189 trigger object finalization, though no guarantee is made as to what objects will
190 be freed, if any.
191
192 .. versionadded:: 2.3
193
194
195.. data:: exc_type
196 exc_value
197 exc_traceback
198
199 .. deprecated:: 1.5
200 Use :func:`exc_info` instead.
201
202 Since they are global variables, they are not specific to the current thread, so
203 their use is not safe in a multi-threaded program. When no exception is being
204 handled, ``exc_type`` is set to ``None`` and the other two are undefined.
205
206
207.. data:: exec_prefix
208
209 A string giving the site-specific directory prefix where the platform-dependent
210 Python files are installed; by default, this is also ``'/usr/local'``. This can
Éric Araujoa8132ec2010-12-16 03:53:53 +0000211 be set at build time with the ``--exec-prefix`` argument to the
Georg Brandl8ec7f652007-08-15 14:28:01 +0000212 :program:`configure` script. Specifically, all configuration files (e.g. the
213 :file:`pyconfig.h` header file) are installed in the directory ``exec_prefix +
214 '/lib/pythonversion/config'``, and shared library modules are installed in
215 ``exec_prefix + '/lib/pythonversion/lib-dynload'``, where *version* is equal to
216 ``version[:3]``.
217
218
219.. data:: executable
220
221 A string giving the name of the executable binary for the Python interpreter, on
222 systems where this makes sense.
223
224
225.. function:: exit([arg])
226
227 Exit from Python. This is implemented by raising the :exc:`SystemExit`
228 exception, so cleanup actions specified by finally clauses of :keyword:`try`
Georg Brandlb8d0e362010-11-26 07:53:50 +0000229 statements are honored, and it is possible to intercept the exit attempt at
230 an outer level.
231
232 The optional argument *arg* can be an integer giving the exit status
233 (defaulting to zero), or another type of object. If it is an integer, zero
234 is considered "successful termination" and any nonzero value is considered
235 "abnormal termination" by shells and the like. Most systems require it to be
236 in the range 0-127, and produce undefined results otherwise. Some systems
237 have a convention for assigning specific meanings to specific exit codes, but
238 these are generally underdeveloped; Unix programs generally use 2 for command
239 line syntax errors and 1 for all other kind of errors. If another type of
240 object is passed, ``None`` is equivalent to passing zero, and any other
241 object is printed to :data:`stderr` and results in an exit code of 1. In
242 particular, ``sys.exit("some error message")`` is a quick way to exit a
243 program when an error occurs.
244
245 Since :func:`exit` ultimately "only" raises an exception, it will only exit
246 the process when called from the main thread, and the exception is not
247 intercepted.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000248
249
250.. data:: exitfunc
251
252 This value is not actually defined by the module, but can be set by the user (or
253 by a program) to specify a clean-up action at program exit. When set, it should
254 be a parameterless function. This function will be called when the interpreter
255 exits. Only one function may be installed in this way; to allow multiple
256 functions which will be called at termination, use the :mod:`atexit` module.
257
258 .. note::
259
260 The exit function is not called when the program is killed by a signal, when a
261 Python fatal internal error is detected, or when ``os._exit()`` is called.
262
263 .. deprecated:: 2.4
264 Use :mod:`atexit` instead.
265
266
Christian Heimesf31b69f2008-01-14 03:42:48 +0000267.. data:: flags
268
269 The struct sequence *flags* exposes the status of command line flags. The
270 attributes are read only.
271
Éric Araujo254d4b82011-03-26 02:09:14 +0100272 ============================= ===================================
273 attribute flag
274 ============================= ===================================
275 :const:`debug` :option:`-d`
276 :const:`py3k_warning` :option:`-3`
277 :const:`division_warning` :option:`-Q`
278 :const:`division_new` :option:`-Qnew <-Q>`
279 :const:`inspect` :option:`-i`
280 :const:`interactive` :option:`-i`
281 :const:`optimize` :option:`-O` or :option:`-OO`
282 :const:`dont_write_bytecode` :option:`-B`
283 :const:`no_user_site` :option:`-s`
284 :const:`no_site` :option:`-S`
285 :const:`ignore_environment` :option:`-E`
286 :const:`tabcheck` :option:`-t` or :option:`-tt <-t>`
287 :const:`verbose` :option:`-v`
288 :const:`unicode` :option:`-U`
289 :const:`bytes_warning` :option:`-b`
290 ============================= ===================================
Christian Heimesf31b69f2008-01-14 03:42:48 +0000291
292 .. versionadded:: 2.6
293
294
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000295.. data:: float_info
296
Christian Heimesc94e2b52008-01-14 04:13:37 +0000297 A structseq holding information about the float type. It contains low level
Mark Dickinson2547ce72010-07-02 18:06:52 +0000298 information about the precision and internal representation. The values
299 correspond to the various floating-point constants defined in the standard
300 header file :file:`float.h` for the 'C' programming language; see section
301 5.2.4.2.2 of the 1999 ISO/IEC C standard [C99]_, 'Characteristics of
302 floating types', for details.
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000303
Mark Dickinson2547ce72010-07-02 18:06:52 +0000304 +---------------------+----------------+--------------------------------------------------+
305 | attribute | float.h macro | explanation |
306 +=====================+================+==================================================+
Mark Dickinson91a63342010-07-03 09:15:09 +0000307 | :const:`epsilon` | DBL_EPSILON | difference between 1 and the least value greater |
Mark Dickinson2547ce72010-07-02 18:06:52 +0000308 | | | than 1 that is representable as a float |
309 +---------------------+----------------+--------------------------------------------------+
310 | :const:`dig` | DBL_DIG | maximum number of decimal digits that can be |
311 | | | faithfully represented in a float; see below |
312 +---------------------+----------------+--------------------------------------------------+
313 | :const:`mant_dig` | DBL_MANT_DIG | float precision: the number of base-``radix`` |
314 | | | digits in the significand of a float |
315 +---------------------+----------------+--------------------------------------------------+
316 | :const:`max` | DBL_MAX | maximum representable finite float |
317 +---------------------+----------------+--------------------------------------------------+
318 | :const:`max_exp` | DBL_MAX_EXP | maximum integer e such that ``radix**(e-1)`` is |
319 | | | a representable finite float |
320 +---------------------+----------------+--------------------------------------------------+
321 | :const:`max_10_exp` | DBL_MAX_10_EXP | maximum integer e such that ``10**e`` is in the |
322 | | | range of representable finite floats |
323 +---------------------+----------------+--------------------------------------------------+
324 | :const:`min` | DBL_MIN | minimum positive normalized float |
325 +---------------------+----------------+--------------------------------------------------+
326 | :const:`min_exp` | DBL_MIN_EXP | minimum integer e such that ``radix**(e-1)`` is |
327 | | | a normalized float |
328 +---------------------+----------------+--------------------------------------------------+
329 | :const:`min_10_exp` | DBL_MIN_10_EXP | minimum integer e such that ``10**e`` is a |
330 | | | normalized float |
331 +---------------------+----------------+--------------------------------------------------+
332 | :const:`radix` | FLT_RADIX | radix of exponent representation |
333 +---------------------+----------------+--------------------------------------------------+
334 | :const:`rounds` | FLT_ROUNDS | constant representing rounding mode |
335 | | | used for arithmetic operations |
336 +---------------------+----------------+--------------------------------------------------+
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000337
Mark Dickinson2547ce72010-07-02 18:06:52 +0000338 The attribute :attr:`sys.float_info.dig` needs further explanation. If
339 ``s`` is any string representing a decimal number with at most
340 :attr:`sys.float_info.dig` significant digits, then converting ``s`` to a
341 float and back again will recover a string representing the same decimal
342 value::
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000343
Mark Dickinson2547ce72010-07-02 18:06:52 +0000344 >>> import sys
345 >>> sys.float_info.dig
346 15
347 >>> s = '3.14159265358979' # decimal string with 15 significant digits
348 >>> format(float(s), '.15g') # convert to float and back -> same value
349 '3.14159265358979'
350
351 But for strings with more than :attr:`sys.float_info.dig` significant digits,
352 this isn't always true::
353
354 >>> s = '9876543211234567' # 16 significant digits is too many!
355 >>> format(float(s), '.16g') # conversion changes value
356 '9876543211234568'
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000357
Christian Heimes3e76d932007-12-01 15:40:22 +0000358 .. versionadded:: 2.6
359
Mark Dickinsonda8652d92009-10-24 14:01:08 +0000360.. data:: float_repr_style
361
362 A string indicating how the :func:`repr` function behaves for
363 floats. If the string has value ``'short'`` then for a finite
364 float ``x``, ``repr(x)`` aims to produce a short string with the
365 property that ``float(repr(x)) == x``. This is the usual behaviour
366 in Python 2.7 and later. Otherwise, ``float_repr_style`` has value
367 ``'legacy'`` and ``repr(x)`` behaves in the same way as it did in
368 versions of Python prior to 2.7.
369
370 .. versionadded:: 2.7
371
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000372
Georg Brandl8ec7f652007-08-15 14:28:01 +0000373.. function:: getcheckinterval()
374
375 Return the interpreter's "check interval"; see :func:`setcheckinterval`.
376
377 .. versionadded:: 2.3
378
379
380.. function:: getdefaultencoding()
381
382 Return the name of the current default string encoding used by the Unicode
383 implementation.
384
385 .. versionadded:: 2.0
386
387
388.. function:: getdlopenflags()
389
390 Return the current value of the flags that are used for :cfunc:`dlopen` calls.
391 The flag constants are defined in the :mod:`dl` and :mod:`DLFCN` modules.
392 Availability: Unix.
393
394 .. versionadded:: 2.2
395
396
397.. function:: getfilesystemencoding()
398
399 Return the name of the encoding used to convert Unicode filenames into system
400 file names, or ``None`` if the system default encoding is used. The result value
401 depends on the operating system:
402
Ezio Melottiab9149d2010-04-29 16:07:20 +0000403 * On Mac OS X, the encoding is ``'utf-8'``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000404
405 * On Unix, the encoding is the user's preference according to the result of
Ezio Melottiab9149d2010-04-29 16:07:20 +0000406 nl_langinfo(CODESET), or ``None`` if the ``nl_langinfo(CODESET)``
407 failed.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000408
409 * On Windows NT+, file names are Unicode natively, so no conversion is
Ezio Melottiab9149d2010-04-29 16:07:20 +0000410 performed. :func:`getfilesystemencoding` still returns ``'mbcs'``, as
411 this is the encoding that applications should use when they explicitly
412 want to convert Unicode strings to byte strings that are equivalent when
413 used as file names.
414
415 * On Windows 9x, the encoding is ``'mbcs'``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000416
417 .. versionadded:: 2.3
418
419
420.. function:: getrefcount(object)
421
422 Return the reference count of the *object*. The count returned is generally one
423 higher than you might expect, because it includes the (temporary) reference as
424 an argument to :func:`getrefcount`.
425
426
427.. function:: getrecursionlimit()
428
429 Return the current value of the recursion limit, the maximum depth of the Python
430 interpreter stack. This limit prevents infinite recursion from causing an
431 overflow of the C stack and crashing Python. It can be set by
432 :func:`setrecursionlimit`.
433
434
Robert Schuppenies47629022008-07-10 17:13:55 +0000435.. function:: getsizeof(object[, default])
Robert Schuppenies51df0642008-06-01 16:16:17 +0000436
437 Return the size of an object in bytes. The object can be any type of
438 object. All built-in objects will return correct results, but this
Robert Schuppenies47629022008-07-10 17:13:55 +0000439 does not have to hold true for third-party extensions as it is implementation
Robert Schuppenies51df0642008-06-01 16:16:17 +0000440 specific.
441
Benjamin Petersonca66cb52009-09-22 22:15:28 +0000442 If given, *default* will be returned if the object does not provide means to
Georg Brandlf6d367452010-03-12 10:02:03 +0000443 retrieve the size. Otherwise a :exc:`TypeError` will be raised.
Robert Schuppenies47629022008-07-10 17:13:55 +0000444
Benjamin Petersonca66cb52009-09-22 22:15:28 +0000445 :func:`getsizeof` calls the object's ``__sizeof__`` method and adds an
446 additional garbage collector overhead if the object is managed by the garbage
447 collector.
Robert Schuppenies47629022008-07-10 17:13:55 +0000448
Robert Schuppenies51df0642008-06-01 16:16:17 +0000449 .. versionadded:: 2.6
450
451
Georg Brandl8ec7f652007-08-15 14:28:01 +0000452.. function:: _getframe([depth])
453
454 Return a frame object from the call stack. If optional integer *depth* is
455 given, return the frame object that many calls below the top of the stack. If
456 that is deeper than the call stack, :exc:`ValueError` is raised. The default
457 for *depth* is zero, returning the frame at the top of the call stack.
458
Georg Brandl6c14e582009-10-22 11:48:10 +0000459 .. impl-detail::
460
461 This function should be used for internal and specialized purposes only.
462 It is not guaranteed to exist in all implementations of Python.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000463
464
Georg Brandl56112892008-01-20 13:59:46 +0000465.. function:: getprofile()
466
467 .. index::
468 single: profile function
469 single: profiler
470
471 Get the profiler function as set by :func:`setprofile`.
472
473 .. versionadded:: 2.6
474
475
476.. function:: gettrace()
477
478 .. index::
479 single: trace function
480 single: debugger
481
482 Get the trace function as set by :func:`settrace`.
483
Georg Brandl6c14e582009-10-22 11:48:10 +0000484 .. impl-detail::
Georg Brandl56112892008-01-20 13:59:46 +0000485
486 The :func:`gettrace` function is intended only for implementing debuggers,
Georg Brandl6c14e582009-10-22 11:48:10 +0000487 profilers, coverage tools and the like. Its behavior is part of the
488 implementation platform, rather than part of the language definition, and
489 thus may not be available in all Python implementations.
Georg Brandl56112892008-01-20 13:59:46 +0000490
491 .. versionadded:: 2.6
492
493
Georg Brandl8ec7f652007-08-15 14:28:01 +0000494.. function:: getwindowsversion()
495
Eric Smith096d0bf2010-01-27 00:55:16 +0000496 Return a named tuple describing the Windows version
Eric Smithee931b72010-01-27 00:28:29 +0000497 currently running. The named elements are *major*, *minor*,
498 *build*, *platform*, *service_pack*, *service_pack_minor*,
499 *service_pack_major*, *suite_mask*, and *product_type*.
500 *service_pack* contains a string while all other values are
501 integers. The components can also be accessed by name, so
502 ``sys.getwindowsversion()[0]`` is equivalent to
503 ``sys.getwindowsversion().major``. For compatibility with prior
504 versions, only the first 5 elements are retrievable by indexing.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000505
506 *platform* may be one of the following values:
507
Jeroen Ruigrok van der Wervenaa3cadb2008-04-21 20:15:39 +0000508 +-----------------------------------------+-------------------------+
509 | Constant | Platform |
510 +=========================================+=========================+
511 | :const:`0 (VER_PLATFORM_WIN32s)` | Win32s on Windows 3.1 |
512 +-----------------------------------------+-------------------------+
513 | :const:`1 (VER_PLATFORM_WIN32_WINDOWS)` | Windows 95/98/ME |
514 +-----------------------------------------+-------------------------+
515 | :const:`2 (VER_PLATFORM_WIN32_NT)` | Windows NT/2000/XP/x64 |
516 +-----------------------------------------+-------------------------+
517 | :const:`3 (VER_PLATFORM_WIN32_CE)` | Windows CE |
518 +-----------------------------------------+-------------------------+
Georg Brandl8ec7f652007-08-15 14:28:01 +0000519
Eric Smithee931b72010-01-27 00:28:29 +0000520 *product_type* may be one of the following values:
521
522 +---------------------------------------+---------------------------------+
523 | Constant | Meaning |
524 +=======================================+=================================+
525 | :const:`1 (VER_NT_WORKSTATION)` | The system is a workstation. |
526 +---------------------------------------+---------------------------------+
527 | :const:`2 (VER_NT_DOMAIN_CONTROLLER)` | The system is a domain |
528 | | controller. |
529 +---------------------------------------+---------------------------------+
530 | :const:`3 (VER_NT_SERVER)` | The system is a server, but not |
531 | | a domain controller. |
532 +---------------------------------------+---------------------------------+
533
534
535 This function wraps the Win32 :cfunc:`GetVersionEx` function; see the
536 Microsoft documentation on :cfunc:`OSVERSIONINFOEX` for more information
537 about these fields.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000538
539 Availability: Windows.
540
541 .. versionadded:: 2.3
Eric Smithee931b72010-01-27 00:28:29 +0000542 .. versionchanged:: 2.7
543 Changed to a named tuple and added *service_pack_minor*,
544 *service_pack_major*, *suite_mask*, and *product_type*.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000545
546
547.. data:: hexversion
548
549 The version number encoded as a single integer. This is guaranteed to increase
550 with each version, including proper support for non-production releases. For
551 example, to test that the Python interpreter is at least version 1.5.2, use::
552
553 if sys.hexversion >= 0x010502F0:
554 # use some advanced feature
555 ...
556 else:
557 # use an alternative implementation or warn the user
558 ...
559
560 This is called ``hexversion`` since it only really looks meaningful when viewed
561 as the result of passing it to the built-in :func:`hex` function. The
562 ``version_info`` value may be used for a more human-friendly encoding of the
563 same information.
564
R David Murraydcaacbf2011-04-30 16:34:35 -0400565 The ``hexversion`` is a 32-bit number with the following layout:
R David Murraya0895db2011-04-25 16:10:18 -0400566
567 +-------------------------+------------------------------------------------+
R David Murraydcaacbf2011-04-30 16:34:35 -0400568 | Bits (big endian order) | Meaning |
R David Murraya0895db2011-04-25 16:10:18 -0400569 +=========================+================================================+
570 | :const:`1-8` | ``PY_MAJOR_VERSION`` (the ``2`` in |
571 | | ``2.1.0a3``) |
572 +-------------------------+------------------------------------------------+
573 | :const:`9-16` | ``PY_MINOR_VERSION`` (the ``1`` in |
574 | | ``2.1.0a3``) |
575 +-------------------------+------------------------------------------------+
576 | :const:`17-24` | ``PY_MICRO_VERSION`` (the ``0`` in |
577 | | ``2.1.0a3``) |
578 +-------------------------+------------------------------------------------+
579 | :const:`25-28` | ``PY_RELEASE_LEVEL`` (``0xA`` for alpha, |
R David Murraydcaacbf2011-04-30 16:34:35 -0400580 | | ``0xB`` for beta, ``0xC`` for release |
581 | | candidate and ``0xF`` for final) |
R David Murraya0895db2011-04-25 16:10:18 -0400582 +-------------------------+------------------------------------------------+
583 | :const:`29-32` | ``PY_RELEASE_SERIAL`` (the ``3`` in |
R David Murraydcaacbf2011-04-30 16:34:35 -0400584 | | ``2.1.0a3``, zero for final releases) |
R David Murraya0895db2011-04-25 16:10:18 -0400585 +-------------------------+------------------------------------------------+
586
R David Murraydcaacbf2011-04-30 16:34:35 -0400587 Thus ``2.1.0a3`` is hexversion ``0x020100a3``.
R David Murraya0895db2011-04-25 16:10:18 -0400588
Georg Brandl8ec7f652007-08-15 14:28:01 +0000589 .. versionadded:: 1.5.2
590
591
Mark Dickinsonefc82f72009-03-20 15:51:55 +0000592.. data:: long_info
593
594 A struct sequence that holds information about Python's
595 internal representation of integers. The attributes are read only.
596
597 +-------------------------+----------------------------------------------+
R David Murraydcaacbf2011-04-30 16:34:35 -0400598 | Attribute | Explanation |
Mark Dickinsonefc82f72009-03-20 15:51:55 +0000599 +=========================+==============================================+
600 | :const:`bits_per_digit` | number of bits held in each digit. Python |
601 | | integers are stored internally in base |
602 | | ``2**long_info.bits_per_digit`` |
603 +-------------------------+----------------------------------------------+
604 | :const:`sizeof_digit` | size in bytes of the C type used to |
605 | | represent a digit |
606 +-------------------------+----------------------------------------------+
607
608 .. versionadded:: 2.7
609
610
Georg Brandl8ec7f652007-08-15 14:28:01 +0000611.. data:: last_type
612 last_value
613 last_traceback
614
615 These three variables are not always defined; they are set when an exception is
616 not handled and the interpreter prints an error message and a stack traceback.
617 Their intended use is to allow an interactive user to import a debugger module
618 and engage in post-mortem debugging without having to re-execute the command
619 that caused the error. (Typical use is ``import pdb; pdb.pm()`` to enter the
620 post-mortem debugger; see chapter :ref:`debugger` for
621 more information.)
622
623 The meaning of the variables is the same as that of the return values from
624 :func:`exc_info` above. (Since there is only one interactive thread,
625 thread-safety is not a concern for these variables, unlike for ``exc_type``
626 etc.)
627
628
629.. data:: maxint
630
631 The largest positive integer supported by Python's regular integer type. This
632 is at least 2\*\*31-1. The largest negative integer is ``-maxint-1`` --- the
633 asymmetry results from the use of 2's complement binary arithmetic.
634
Martin v. Löwis4dd019f2008-05-20 08:11:19 +0000635.. data:: maxsize
636
637 The largest positive integer supported by the platform's Py_ssize_t type,
638 and thus the maximum size lists, strings, dicts, and many other containers
639 can have.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000640
641.. data:: maxunicode
642
643 An integer giving the largest supported code point for a Unicode character. The
644 value of this depends on the configuration option that specifies whether Unicode
645 characters are stored as UCS-2 or UCS-4.
646
647
Georg Brandl624f3372009-03-31 16:11:45 +0000648.. data:: meta_path
649
650 A list of :term:`finder` objects that have their :meth:`find_module`
651 methods called to see if one of the objects can find the module to be
652 imported. The :meth:`find_module` method is called at least with the
653 absolute name of the module being imported. If the module to be imported is
654 contained in package then the parent package's :attr:`__path__` attribute
655 is passed in as a second argument. The method returns :keyword:`None` if
656 the module cannot be found, else returns a :term:`loader`.
657
658 :data:`sys.meta_path` is searched before any implicit default finders or
659 :data:`sys.path`.
660
661 See :pep:`302` for the original specification.
662
663
Georg Brandl8ec7f652007-08-15 14:28:01 +0000664.. data:: modules
665
666 .. index:: builtin: reload
667
668 This is a dictionary that maps module names to modules which have already been
669 loaded. This can be manipulated to force reloading of modules and other tricks.
670 Note that removing a module from this dictionary is *not* the same as calling
671 :func:`reload` on the corresponding module object.
672
673
674.. data:: path
675
676 .. index:: triple: module; search; path
677
678 A list of strings that specifies the search path for modules. Initialized from
679 the environment variable :envvar:`PYTHONPATH`, plus an installation-dependent
680 default.
681
682 As initialized upon program startup, the first item of this list, ``path[0]``,
683 is the directory containing the script that was used to invoke the Python
684 interpreter. If the script directory is not available (e.g. if the interpreter
685 is invoked interactively or if the script is read from standard input),
686 ``path[0]`` is the empty string, which directs Python to search modules in the
687 current directory first. Notice that the script directory is inserted *before*
688 the entries inserted as a result of :envvar:`PYTHONPATH`.
689
690 A program is free to modify this list for its own purposes.
691
692 .. versionchanged:: 2.3
693 Unicode strings are no longer ignored.
694
Benjamin Peterson4db53b22009-01-10 23:41:59 +0000695 .. seealso::
696 Module :mod:`site` This describes how to use .pth files to extend
697 :data:`sys.path`.
698
Georg Brandl8ec7f652007-08-15 14:28:01 +0000699
Georg Brandl624f3372009-03-31 16:11:45 +0000700.. data:: path_hooks
701
702 A list of callables that take a path argument to try to create a
703 :term:`finder` for the path. If a finder can be created, it is to be
704 returned by the callable, else raise :exc:`ImportError`.
705
706 Originally specified in :pep:`302`.
707
708
709.. data:: path_importer_cache
710
711 A dictionary acting as a cache for :term:`finder` objects. The keys are
712 paths that have been passed to :data:`sys.path_hooks` and the values are
713 the finders that are found. If a path is a valid file system path but no
714 explicit finder is found on :data:`sys.path_hooks` then :keyword:`None` is
715 stored to represent the implicit default finder should be used. If the path
716 is not an existing path then :class:`imp.NullImporter` is set.
717
718 Originally specified in :pep:`302`.
719
720
Georg Brandl8ec7f652007-08-15 14:28:01 +0000721.. data:: platform
722
Georg Brandl440f2ff2008-01-20 12:57:47 +0000723 This string contains a platform identifier that can be used to append
724 platform-specific components to :data:`sys.path`, for instance.
725
726 For Unix systems, this is the lowercased OS name as returned by ``uname -s``
727 with the first part of the version as returned by ``uname -r`` appended,
728 e.g. ``'sunos5'`` or ``'linux2'``, *at the time when Python was built*.
729 For other systems, the values are:
730
731 ================ ===========================
732 System :data:`platform` value
733 ================ ===========================
734 Windows ``'win32'``
735 Windows/Cygwin ``'cygwin'``
Georg Brandl9af94982008-09-13 17:41:16 +0000736 Mac OS X ``'darwin'``
Georg Brandl440f2ff2008-01-20 12:57:47 +0000737 OS/2 ``'os2'``
738 OS/2 EMX ``'os2emx'``
739 RiscOS ``'riscos'``
740 AtheOS ``'atheos'``
741 ================ ===========================
Georg Brandl8ec7f652007-08-15 14:28:01 +0000742
743
744.. data:: prefix
745
746 A string giving the site-specific directory prefix where the platform
747 independent Python files are installed; by default, this is the string
Éric Araujoa8132ec2010-12-16 03:53:53 +0000748 ``'/usr/local'``. This can be set at build time with the ``--prefix``
Georg Brandl8ec7f652007-08-15 14:28:01 +0000749 argument to the :program:`configure` script. The main collection of Python
750 library modules is installed in the directory ``prefix + '/lib/pythonversion'``
751 while the platform independent header files (all except :file:`pyconfig.h`) are
752 stored in ``prefix + '/include/pythonversion'``, where *version* is equal to
753 ``version[:3]``.
754
755
756.. data:: ps1
757 ps2
758
759 .. index::
760 single: interpreter prompts
761 single: prompts, interpreter
762
763 Strings specifying the primary and secondary prompt of the interpreter. These
764 are only defined if the interpreter is in interactive mode. Their initial
765 values in this case are ``'>>> '`` and ``'... '``. If a non-string object is
766 assigned to either variable, its :func:`str` is re-evaluated each time the
767 interpreter prepares to read a new interactive command; this can be used to
768 implement a dynamic prompt.
769
770
Christian Heimesd7b33372007-11-28 08:02:36 +0000771.. data:: py3kwarning
772
773 Bool containing the status of the Python 3.0 warning flag. It's ``True``
Georg Brandl13813f72009-02-26 17:36:26 +0000774 when Python is started with the -3 option. (This should be considered
775 read-only; setting it to a different value doesn't have an effect on
776 Python 3.0 warnings.)
Christian Heimesd7b33372007-11-28 08:02:36 +0000777
Georg Brandl5f794462008-03-21 21:05:03 +0000778 .. versionadded:: 2.6
779
Christian Heimesd7b33372007-11-28 08:02:36 +0000780
Georg Brandl2da0fce2008-01-07 17:09:35 +0000781.. data:: dont_write_bytecode
782
783 If this is true, Python won't try to write ``.pyc`` or ``.pyo`` files on the
784 import of source modules. This value is initially set to ``True`` or ``False``
785 depending on the ``-B`` command line option and the ``PYTHONDONTWRITEBYTECODE``
786 environment variable, but you can set it yourself to control bytecode file
787 generation.
788
789 .. versionadded:: 2.6
790
791
Georg Brandl8ec7f652007-08-15 14:28:01 +0000792.. function:: setcheckinterval(interval)
793
794 Set the interpreter's "check interval". This integer value determines how often
795 the interpreter checks for periodic things such as thread switches and signal
796 handlers. The default is ``100``, meaning the check is performed every 100
797 Python virtual instructions. Setting it to a larger value may increase
798 performance for programs using threads. Setting it to a value ``<=`` 0 checks
799 every virtual instruction, maximizing responsiveness as well as overhead.
800
801
802.. function:: setdefaultencoding(name)
803
804 Set the current default string encoding used by the Unicode implementation. If
805 *name* does not match any available encoding, :exc:`LookupError` is raised.
806 This function is only intended to be used by the :mod:`site` module
807 implementation and, where needed, by :mod:`sitecustomize`. Once used by the
808 :mod:`site` module, it is removed from the :mod:`sys` module's namespace.
809
Georg Brandlb19be572007-12-29 10:57:00 +0000810 .. Note that :mod:`site` is not imported if the :option:`-S` option is passed
811 to the interpreter, in which case this function will remain available.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000812
813 .. versionadded:: 2.0
814
815
816.. function:: setdlopenflags(n)
817
818 Set the flags used by the interpreter for :cfunc:`dlopen` calls, such as when
819 the interpreter loads extension modules. Among other things, this will enable a
820 lazy resolving of symbols when importing a module, if called as
821 ``sys.setdlopenflags(0)``. To share symbols across extension modules, call as
822 ``sys.setdlopenflags(dl.RTLD_NOW | dl.RTLD_GLOBAL)``. Symbolic names for the
823 flag modules can be either found in the :mod:`dl` module, or in the :mod:`DLFCN`
824 module. If :mod:`DLFCN` is not available, it can be generated from
825 :file:`/usr/include/dlfcn.h` using the :program:`h2py` script. Availability:
826 Unix.
827
828 .. versionadded:: 2.2
829
830
831.. function:: setprofile(profilefunc)
832
833 .. index::
834 single: profile function
835 single: profiler
836
837 Set the system's profile function, which allows you to implement a Python source
838 code profiler in Python. See chapter :ref:`profile` for more information on the
839 Python profiler. The system's profile function is called similarly to the
840 system's trace function (see :func:`settrace`), but it isn't called for each
841 executed line of code (only on call and return, but the return event is reported
842 even when an exception has been set). The function is thread-specific, but
843 there is no way for the profiler to know about context switches between threads,
844 so it does not make sense to use this in the presence of multiple threads. Also,
845 its return value is not used, so it can simply return ``None``.
846
847
848.. function:: setrecursionlimit(limit)
849
850 Set the maximum depth of the Python interpreter stack to *limit*. This limit
851 prevents infinite recursion from causing an overflow of the C stack and crashing
852 Python.
853
854 The highest possible limit is platform-dependent. A user may need to set the
855 limit higher when she has a program that requires deep recursion and a platform
856 that supports a higher limit. This should be done with care, because a too-high
857 limit can lead to a crash.
858
859
860.. function:: settrace(tracefunc)
861
862 .. index::
863 single: trace function
864 single: debugger
865
866 Set the system's trace function, which allows you to implement a Python
Benjamin Peterson050f4ad2008-11-20 21:25:31 +0000867 source code debugger in Python. The function is thread-specific; for a
Georg Brandl8ec7f652007-08-15 14:28:01 +0000868 debugger to support multiple threads, it must be registered using
869 :func:`settrace` for each thread being debugged.
870
Benjamin Peterson5ab9c3b2008-11-20 04:05:12 +0000871 Trace functions should have three arguments: *frame*, *event*, and
872 *arg*. *frame* is the current stack frame. *event* is a string: ``'call'``,
873 ``'line'``, ``'return'``, ``'exception'``, ``'c_call'``, ``'c_return'``, or
874 ``'c_exception'``. *arg* depends on the event type.
875
876 The trace function is invoked (with *event* set to ``'call'``) whenever a new
877 local scope is entered; it should return a reference to a local trace
878 function to be used that scope, or ``None`` if the scope shouldn't be traced.
879
880 The local trace function should return a reference to itself (or to another
881 function for further tracing in that scope), or ``None`` to turn off tracing
882 in that scope.
883
884 The events have the following meaning:
885
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000886 ``'call'``
Benjamin Peterson5ab9c3b2008-11-20 04:05:12 +0000887 A function is called (or some other code block entered). The
888 global trace function is called; *arg* is ``None``; the return value
889 specifies the local trace function.
890
891 ``'line'``
Jeffrey Yasskin655d8352009-05-23 23:23:01 +0000892 The interpreter is about to execute a new line of code or re-execute the
893 condition of a loop. The local trace function is called; *arg* is
894 ``None``; the return value specifies the new local trace function. See
895 :file:`Objects/lnotab_notes.txt` for a detailed explanation of how this
896 works.
Benjamin Peterson5ab9c3b2008-11-20 04:05:12 +0000897
898 ``'return'``
899 A function (or other code block) is about to return. The local trace
Georg Brandl78f11ed2010-11-26 07:34:20 +0000900 function is called; *arg* is the value that will be returned, or ``None``
901 if the event is caused by an exception being raised. The trace function's
902 return value is ignored.
Benjamin Peterson5ab9c3b2008-11-20 04:05:12 +0000903
904 ``'exception'``
905 An exception has occurred. The local trace function is called; *arg* is a
906 tuple ``(exception, value, traceback)``; the return value specifies the
907 new local trace function.
908
909 ``'c_call'``
910 A C function is about to be called. This may be an extension function or
Georg Brandld7d4fd72009-07-26 14:37:28 +0000911 a built-in. *arg* is the C function object.
Benjamin Peterson5ab9c3b2008-11-20 04:05:12 +0000912
913 ``'c_return'``
Georg Brandl78f11ed2010-11-26 07:34:20 +0000914 A C function has returned. *arg* is the C function object.
Benjamin Peterson5ab9c3b2008-11-20 04:05:12 +0000915
916 ``'c_exception'``
Georg Brandl78f11ed2010-11-26 07:34:20 +0000917 A C function has raised an exception. *arg* is the C function object.
Benjamin Peterson5ab9c3b2008-11-20 04:05:12 +0000918
Benjamin Peterson050f4ad2008-11-20 21:25:31 +0000919 Note that as an exception is propagated down the chain of callers, an
920 ``'exception'`` event is generated at each level.
Benjamin Peterson5ab9c3b2008-11-20 04:05:12 +0000921
Benjamin Peterson050f4ad2008-11-20 21:25:31 +0000922 For more information on code and frame objects, refer to :ref:`types`.
Benjamin Peterson5ab9c3b2008-11-20 04:05:12 +0000923
Georg Brandl6c14e582009-10-22 11:48:10 +0000924 .. impl-detail::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000925
926 The :func:`settrace` function is intended only for implementing debuggers,
Georg Brandl6c14e582009-10-22 11:48:10 +0000927 profilers, coverage tools and the like. Its behavior is part of the
928 implementation platform, rather than part of the language definition, and
929 thus may not be available in all Python implementations.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000930
931
932.. function:: settscdump(on_flag)
933
934 Activate dumping of VM measurements using the Pentium timestamp counter, if
935 *on_flag* is true. Deactivate these dumps if *on_flag* is off. The function is
Éric Araujoa8132ec2010-12-16 03:53:53 +0000936 available only if Python was compiled with ``--with-tsc``. To understand
Georg Brandl8ec7f652007-08-15 14:28:01 +0000937 the output of this dump, read :file:`Python/ceval.c` in the Python sources.
938
939 .. versionadded:: 2.4
940
Benjamin Petersona7fa0322010-03-06 03:13:33 +0000941 .. impl-detail::
942
943 This function is intimately bound to CPython implementation details and
944 thus not likely to be implemented elsewhere.
945
Georg Brandl8ec7f652007-08-15 14:28:01 +0000946
947.. data:: stdin
948 stdout
949 stderr
950
951 .. index::
952 builtin: input
953 builtin: raw_input
954
955 File objects corresponding to the interpreter's standard input, output and error
956 streams. ``stdin`` is used for all interpreter input except for scripts but
957 including calls to :func:`input` and :func:`raw_input`. ``stdout`` is used for
Georg Brandl584265b2007-12-02 14:58:50 +0000958 the output of :keyword:`print` and :term:`expression` statements and for the
959 prompts of :func:`input` and :func:`raw_input`. The interpreter's own prompts
960 and (almost all of) its error messages go to ``stderr``. ``stdout`` and
961 ``stderr`` needn't be built-in file objects: any object is acceptable as long
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000962 as it has a :meth:`write` method that takes a string argument. (Changing these
Georg Brandl584265b2007-12-02 14:58:50 +0000963 objects doesn't affect the standard I/O streams of processes executed by
Georg Brandl8ec7f652007-08-15 14:28:01 +0000964 :func:`os.popen`, :func:`os.system` or the :func:`exec\*` family of functions in
965 the :mod:`os` module.)
966
967
968.. data:: __stdin__
969 __stdout__
970 __stderr__
971
972 These objects contain the original values of ``stdin``, ``stderr`` and
Georg Brandlb48adec2009-03-31 19:10:35 +0000973 ``stdout`` at the start of the program. They are used during finalization,
974 and could be useful to print to the actual standard stream no matter if the
975 ``sys.std*`` object has been redirected.
976
977 It can also be used to restore the actual files to known working file objects
978 in case they have been overwritten with a broken object. However, the
979 preferred way to do this is to explicitly save the previous stream before
980 replacing it, and restore the saved object.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000981
982
983.. data:: tracebacklimit
984
985 When this variable is set to an integer value, it determines the maximum number
986 of levels of traceback information printed when an unhandled exception occurs.
987 The default is ``1000``. When set to ``0`` or less, all traceback information
988 is suppressed and only the exception type and value are printed.
989
990
991.. data:: version
992
993 A string containing the version number of the Python interpreter plus additional
Georg Brandle2773252010-08-01 19:14:56 +0000994 information on the build number and compiler used. This string is displayed
995 when the interactive interpreter is started. Do not extract version information
996 out of it, rather, use :data:`version_info` and the functions provided by the
997 :mod:`platform` module.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000998
999
1000.. data:: api_version
1001
1002 The C API version for this interpreter. Programmers may find this useful when
1003 debugging version conflicts between Python and extension modules.
1004
1005 .. versionadded:: 2.3
1006
1007
1008.. data:: version_info
1009
1010 A tuple containing the five components of the version number: *major*, *minor*,
1011 *micro*, *releaselevel*, and *serial*. All values except *releaselevel* are
1012 integers; the release level is ``'alpha'``, ``'beta'``, ``'candidate'``, or
1013 ``'final'``. The ``version_info`` value corresponding to the Python version 2.0
Eric Smith81fe0932009-02-06 00:48:26 +00001014 is ``(2, 0, 0, 'final', 0)``. The components can also be accessed by name,
1015 so ``sys.version_info[0]`` is equivalent to ``sys.version_info.major``
1016 and so on.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001017
1018 .. versionadded:: 2.0
Eric Smith81fe0932009-02-06 00:48:26 +00001019 .. versionchanged:: 2.7
1020 Added named component attributes
Georg Brandl8ec7f652007-08-15 14:28:01 +00001021
1022
1023.. data:: warnoptions
1024
1025 This is an implementation detail of the warnings framework; do not modify this
1026 value. Refer to the :mod:`warnings` module for more information on the warnings
1027 framework.
1028
1029
1030.. data:: winver
1031
1032 The version number used to form registry keys on Windows platforms. This is
1033 stored as string resource 1000 in the Python DLL. The value is normally the
1034 first three characters of :const:`version`. It is provided in the :mod:`sys`
1035 module for informational purposes; modifying this value has no effect on the
1036 registry keys used by Python. Availability: Windows.
Mark Dickinson2547ce72010-07-02 18:06:52 +00001037
1038.. rubric:: Citations
1039
1040.. [C99] ISO/IEC 9899:1999. "Programming languages -- C." A public draft of this standard is available at http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf .
1041