blob: c15e55b29e51f156a951ba3ea53e52cf140a4b55 [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
56.. data:: copyright
57
58 A string containing the copyright pertaining to the Python interpreter.
59
60
Christian Heimes422051a2008-02-04 18:00:12 +000061.. function:: _clear_type_cache()
62
63 Clear the internal type cache. The type cache is used to speed up attribute
64 and method lookups. Use the function *only* to drop unnecessary references
65 during reference leak debugging.
66
67 This function should be used for internal and specialized purposes only.
Christian Heimes908caac2008-01-27 23:34:59 +000068
69 .. versionadded:: 2.6
70
71
Georg Brandl8ec7f652007-08-15 14:28:01 +000072.. function:: _current_frames()
73
74 Return a dictionary mapping each thread's identifier to the topmost stack frame
75 currently active in that thread at the time the function is called. Note that
76 functions in the :mod:`traceback` module can build the call stack given such a
77 frame.
78
79 This is most useful for debugging deadlock: this function does not require the
80 deadlocked threads' cooperation, and such threads' call stacks are frozen for as
81 long as they remain deadlocked. The frame returned for a non-deadlocked thread
82 may bear no relationship to that thread's current activity by the time calling
83 code examines the frame.
84
85 This function should be used for internal and specialized purposes only.
86
87 .. versionadded:: 2.5
88
89
90.. data:: dllhandle
91
92 Integer specifying the handle of the Python DLL. Availability: Windows.
93
94
95.. function:: displayhook(value)
96
97 If *value* is not ``None``, this function prints it to ``sys.stdout``, and saves
98 it in ``__builtin__._``.
99
Georg Brandl584265b2007-12-02 14:58:50 +0000100 ``sys.displayhook`` is called on the result of evaluating an :term:`expression`
101 entered in an interactive Python session. The display of these values can be
102 customized by assigning another one-argument function to ``sys.displayhook``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000103
104
105.. function:: excepthook(type, value, traceback)
106
107 This function prints out a given traceback and exception to ``sys.stderr``.
108
109 When an exception is raised and uncaught, the interpreter calls
110 ``sys.excepthook`` with three arguments, the exception class, exception
111 instance, and a traceback object. In an interactive session this happens just
112 before control is returned to the prompt; in a Python program this happens just
113 before the program exits. The handling of such top-level exceptions can be
114 customized by assigning another three-argument function to ``sys.excepthook``.
115
116
117.. data:: __displayhook__
118 __excepthook__
119
120 These objects contain the original values of ``displayhook`` and ``excepthook``
121 at the start of the program. They are saved so that ``displayhook`` and
122 ``excepthook`` can be restored in case they happen to get replaced with broken
123 objects.
124
125
126.. function:: exc_info()
127
128 This function returns a tuple of three values that give information about the
129 exception that is currently being handled. The information returned is specific
130 both to the current thread and to the current stack frame. If the current stack
131 frame is not handling an exception, the information is taken from the calling
132 stack frame, or its caller, and so on until a stack frame is found that is
133 handling an exception. Here, "handling an exception" is defined as "executing
134 or having executed an except clause." For any stack frame, only information
135 about the most recently handled exception is accessible.
136
137 .. index:: object: traceback
138
139 If no exception is being handled anywhere on the stack, a tuple containing three
140 ``None`` values is returned. Otherwise, the values returned are ``(type, value,
141 traceback)``. Their meaning is: *type* gets the exception type of the exception
142 being handled (a class object); *value* gets the exception parameter (its
143 :dfn:`associated value` or the second argument to :keyword:`raise`, which is
144 always a class instance if the exception type is a class object); *traceback*
145 gets a traceback object (see the Reference Manual) which encapsulates the call
146 stack at the point where the exception originally occurred.
147
148 If :func:`exc_clear` is called, this function will return three ``None`` values
149 until either another exception is raised in the current thread or the execution
150 stack returns to a frame where another exception is being handled.
151
152 .. warning::
153
154 Assigning the *traceback* return value to a local variable in a function that is
155 handling an exception will cause a circular reference. This will prevent
156 anything referenced by a local variable in the same function or by the traceback
157 from being garbage collected. Since most functions don't need access to the
158 traceback, the best solution is to use something like ``exctype, value =
159 sys.exc_info()[:2]`` to extract only the exception type and value. If you do
160 need the traceback, make sure to delete it after use (best done with a
161 :keyword:`try` ... :keyword:`finally` statement) or to call :func:`exc_info` in
162 a function that does not itself handle an exception.
163
164 .. note::
165
166 Beginning with Python 2.2, such cycles are automatically reclaimed when garbage
167 collection is enabled and they become unreachable, but it remains more efficient
168 to avoid creating cycles.
169
170
171.. function:: exc_clear()
172
173 This function clears all information relating to the current or last exception
174 that occurred in the current thread. After calling this function,
175 :func:`exc_info` will return three ``None`` values until another exception is
176 raised in the current thread or the execution stack returns to a frame where
177 another exception is being handled.
178
179 This function is only needed in only a few obscure situations. These include
180 logging and error handling systems that report information on the last or
181 current exception. This function can also be used to try to free resources and
182 trigger object finalization, though no guarantee is made as to what objects will
183 be freed, if any.
184
185 .. versionadded:: 2.3
186
187
188.. data:: exc_type
189 exc_value
190 exc_traceback
191
192 .. deprecated:: 1.5
193 Use :func:`exc_info` instead.
194
195 Since they are global variables, they are not specific to the current thread, so
196 their use is not safe in a multi-threaded program. When no exception is being
197 handled, ``exc_type`` is set to ``None`` and the other two are undefined.
198
199
200.. data:: exec_prefix
201
202 A string giving the site-specific directory prefix where the platform-dependent
203 Python files are installed; by default, this is also ``'/usr/local'``. This can
204 be set at build time with the :option:`--exec-prefix` argument to the
205 :program:`configure` script. Specifically, all configuration files (e.g. the
206 :file:`pyconfig.h` header file) are installed in the directory ``exec_prefix +
207 '/lib/pythonversion/config'``, and shared library modules are installed in
208 ``exec_prefix + '/lib/pythonversion/lib-dynload'``, where *version* is equal to
209 ``version[:3]``.
210
211
212.. data:: executable
213
214 A string giving the name of the executable binary for the Python interpreter, on
215 systems where this makes sense.
216
217
218.. function:: exit([arg])
219
220 Exit from Python. This is implemented by raising the :exc:`SystemExit`
221 exception, so cleanup actions specified by finally clauses of :keyword:`try`
222 statements are honored, and it is possible to intercept the exit attempt at an
223 outer level. The optional argument *arg* can be an integer giving the exit
224 status (defaulting to zero), or another type of object. If it is an integer,
225 zero is considered "successful termination" and any nonzero value is considered
226 "abnormal termination" by shells and the like. Most systems require it to be in
227 the range 0-127, and produce undefined results otherwise. Some systems have a
228 convention for assigning specific meanings to specific exit codes, but these are
229 generally underdeveloped; Unix programs generally use 2 for command line syntax
230 errors and 1 for all other kind of errors. If another type of object is passed,
231 ``None`` is equivalent to passing zero, and any other object is printed to
232 ``sys.stderr`` and results in an exit code of 1. In particular,
233 ``sys.exit("some error message")`` is a quick way to exit a program when an
234 error occurs.
235
236
237.. data:: exitfunc
238
239 This value is not actually defined by the module, but can be set by the user (or
240 by a program) to specify a clean-up action at program exit. When set, it should
241 be a parameterless function. This function will be called when the interpreter
242 exits. Only one function may be installed in this way; to allow multiple
243 functions which will be called at termination, use the :mod:`atexit` module.
244
245 .. note::
246
247 The exit function is not called when the program is killed by a signal, when a
248 Python fatal internal error is detected, or when ``os._exit()`` is called.
249
250 .. deprecated:: 2.4
251 Use :mod:`atexit` instead.
252
253
Christian Heimesf31b69f2008-01-14 03:42:48 +0000254.. data:: flags
255
256 The struct sequence *flags* exposes the status of command line flags. The
257 attributes are read only.
258
259 +------------------------------+------------------------------------------+
260 | attribute | flag |
261 +==============================+==========================================+
262 | :const:`debug` | -d |
263 +------------------------------+------------------------------------------+
264 | :const:`py3k_warning` | -3 |
265 +------------------------------+------------------------------------------+
266 | :const:`division_warning` | -Q |
267 +------------------------------+------------------------------------------+
268 | :const:`division_new` | -Qnew |
269 +------------------------------+------------------------------------------+
270 | :const:`inspect` | -i |
271 +------------------------------+------------------------------------------+
272 | :const:`interactive` | -i |
273 +------------------------------+------------------------------------------+
274 | :const:`optimize` | -O or -OO |
275 +------------------------------+------------------------------------------+
276 | :const:`dont_write_bytecode` | -B |
277 +------------------------------+------------------------------------------+
Ezio Melotti1ac1c392009-12-25 02:12:01 +0000278 | :const:`no_user_site` | -s |
279 +------------------------------+------------------------------------------+
Christian Heimesf31b69f2008-01-14 03:42:48 +0000280 | :const:`no_site` | -S |
281 +------------------------------+------------------------------------------+
Andrew M. Kuchling7ce9b182008-01-15 01:29:16 +0000282 | :const:`ignore_environment` | -E |
Christian Heimesf31b69f2008-01-14 03:42:48 +0000283 +------------------------------+------------------------------------------+
284 | :const:`tabcheck` | -t or -tt |
285 +------------------------------+------------------------------------------+
286 | :const:`verbose` | -v |
287 +------------------------------+------------------------------------------+
288 | :const:`unicode` | -U |
289 +------------------------------+------------------------------------------+
Ezio Melotti1ac1c392009-12-25 02:12:01 +0000290 | :const:`bytes_warning` | -b |
291 +------------------------------+------------------------------------------+
Christian Heimesf31b69f2008-01-14 03:42:48 +0000292
293 .. versionadded:: 2.6
294
295
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000296.. data:: float_info
297
Christian Heimesc94e2b52008-01-14 04:13:37 +0000298 A structseq holding information about the float type. It contains low level
Mark Dickinson2547ce72010-07-02 18:06:52 +0000299 information about the precision and internal representation. The values
300 correspond to the various floating-point constants defined in the standard
301 header file :file:`float.h` for the 'C' programming language; see section
302 5.2.4.2.2 of the 1999 ISO/IEC C standard [C99]_, 'Characteristics of
303 floating types', for details.
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000304
Mark Dickinson2547ce72010-07-02 18:06:52 +0000305 +---------------------+----------------+--------------------------------------------------+
306 | attribute | float.h macro | explanation |
307 +=====================+================+==================================================+
Mark Dickinson91a63342010-07-03 09:15:09 +0000308 | :const:`epsilon` | DBL_EPSILON | difference between 1 and the least value greater |
Mark Dickinson2547ce72010-07-02 18:06:52 +0000309 | | | than 1 that is representable as a float |
310 +---------------------+----------------+--------------------------------------------------+
311 | :const:`dig` | DBL_DIG | maximum number of decimal digits that can be |
312 | | | faithfully represented in a float; see below |
313 +---------------------+----------------+--------------------------------------------------+
314 | :const:`mant_dig` | DBL_MANT_DIG | float precision: the number of base-``radix`` |
315 | | | digits in the significand of a float |
316 +---------------------+----------------+--------------------------------------------------+
317 | :const:`max` | DBL_MAX | maximum representable finite float |
318 +---------------------+----------------+--------------------------------------------------+
319 | :const:`max_exp` | DBL_MAX_EXP | maximum integer e such that ``radix**(e-1)`` is |
320 | | | a representable finite float |
321 +---------------------+----------------+--------------------------------------------------+
322 | :const:`max_10_exp` | DBL_MAX_10_EXP | maximum integer e such that ``10**e`` is in the |
323 | | | range of representable finite floats |
324 +---------------------+----------------+--------------------------------------------------+
325 | :const:`min` | DBL_MIN | minimum positive normalized float |
326 +---------------------+----------------+--------------------------------------------------+
327 | :const:`min_exp` | DBL_MIN_EXP | minimum integer e such that ``radix**(e-1)`` is |
328 | | | a normalized float |
329 +---------------------+----------------+--------------------------------------------------+
330 | :const:`min_10_exp` | DBL_MIN_10_EXP | minimum integer e such that ``10**e`` is a |
331 | | | normalized float |
332 +---------------------+----------------+--------------------------------------------------+
333 | :const:`radix` | FLT_RADIX | radix of exponent representation |
334 +---------------------+----------------+--------------------------------------------------+
335 | :const:`rounds` | FLT_ROUNDS | constant representing rounding mode |
336 | | | used for arithmetic operations |
337 +---------------------+----------------+--------------------------------------------------+
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000338
Mark Dickinson2547ce72010-07-02 18:06:52 +0000339 The attribute :attr:`sys.float_info.dig` needs further explanation. If
340 ``s`` is any string representing a decimal number with at most
341 :attr:`sys.float_info.dig` significant digits, then converting ``s`` to a
342 float and back again will recover a string representing the same decimal
343 value::
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000344
Mark Dickinson2547ce72010-07-02 18:06:52 +0000345 >>> import sys
346 >>> sys.float_info.dig
347 15
348 >>> s = '3.14159265358979' # decimal string with 15 significant digits
349 >>> format(float(s), '.15g') # convert to float and back -> same value
350 '3.14159265358979'
351
352 But for strings with more than :attr:`sys.float_info.dig` significant digits,
353 this isn't always true::
354
355 >>> s = '9876543211234567' # 16 significant digits is too many!
356 >>> format(float(s), '.16g') # conversion changes value
357 '9876543211234568'
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000358
Christian Heimes3e76d932007-12-01 15:40:22 +0000359 .. versionadded:: 2.6
360
Mark Dickinsonda8652d92009-10-24 14:01:08 +0000361.. data:: float_repr_style
362
363 A string indicating how the :func:`repr` function behaves for
364 floats. If the string has value ``'short'`` then for a finite
365 float ``x``, ``repr(x)`` aims to produce a short string with the
366 property that ``float(repr(x)) == x``. This is the usual behaviour
367 in Python 2.7 and later. Otherwise, ``float_repr_style`` has value
368 ``'legacy'`` and ``repr(x)`` behaves in the same way as it did in
369 versions of Python prior to 2.7.
370
371 .. versionadded:: 2.7
372
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000373
Georg Brandl8ec7f652007-08-15 14:28:01 +0000374.. function:: getcheckinterval()
375
376 Return the interpreter's "check interval"; see :func:`setcheckinterval`.
377
378 .. versionadded:: 2.3
379
380
381.. function:: getdefaultencoding()
382
383 Return the name of the current default string encoding used by the Unicode
384 implementation.
385
386 .. versionadded:: 2.0
387
388
389.. function:: getdlopenflags()
390
391 Return the current value of the flags that are used for :cfunc:`dlopen` calls.
392 The flag constants are defined in the :mod:`dl` and :mod:`DLFCN` modules.
393 Availability: Unix.
394
395 .. versionadded:: 2.2
396
397
398.. function:: getfilesystemencoding()
399
400 Return the name of the encoding used to convert Unicode filenames into system
401 file names, or ``None`` if the system default encoding is used. The result value
402 depends on the operating system:
403
Ezio Melottiab9149d2010-04-29 16:07:20 +0000404 * On Mac OS X, the encoding is ``'utf-8'``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000405
406 * On Unix, the encoding is the user's preference according to the result of
Ezio Melottiab9149d2010-04-29 16:07:20 +0000407 nl_langinfo(CODESET), or ``None`` if the ``nl_langinfo(CODESET)``
408 failed.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000409
410 * On Windows NT+, file names are Unicode natively, so no conversion is
Ezio Melottiab9149d2010-04-29 16:07:20 +0000411 performed. :func:`getfilesystemencoding` still returns ``'mbcs'``, as
412 this is the encoding that applications should use when they explicitly
413 want to convert Unicode strings to byte strings that are equivalent when
414 used as file names.
415
416 * On Windows 9x, the encoding is ``'mbcs'``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000417
418 .. versionadded:: 2.3
419
420
421.. function:: getrefcount(object)
422
423 Return the reference count of the *object*. The count returned is generally one
424 higher than you might expect, because it includes the (temporary) reference as
425 an argument to :func:`getrefcount`.
426
427
428.. function:: getrecursionlimit()
429
430 Return the current value of the recursion limit, the maximum depth of the Python
431 interpreter stack. This limit prevents infinite recursion from causing an
432 overflow of the C stack and crashing Python. It can be set by
433 :func:`setrecursionlimit`.
434
435
Robert Schuppenies47629022008-07-10 17:13:55 +0000436.. function:: getsizeof(object[, default])
Robert Schuppenies51df0642008-06-01 16:16:17 +0000437
438 Return the size of an object in bytes. The object can be any type of
439 object. All built-in objects will return correct results, but this
Robert Schuppenies47629022008-07-10 17:13:55 +0000440 does not have to hold true for third-party extensions as it is implementation
Robert Schuppenies51df0642008-06-01 16:16:17 +0000441 specific.
442
Benjamin Petersonca66cb52009-09-22 22:15:28 +0000443 If given, *default* will be returned if the object does not provide means to
Georg Brandlf6d367452010-03-12 10:02:03 +0000444 retrieve the size. Otherwise a :exc:`TypeError` will be raised.
Robert Schuppenies47629022008-07-10 17:13:55 +0000445
Benjamin Petersonca66cb52009-09-22 22:15:28 +0000446 :func:`getsizeof` calls the object's ``__sizeof__`` method and adds an
447 additional garbage collector overhead if the object is managed by the garbage
448 collector.
Robert Schuppenies47629022008-07-10 17:13:55 +0000449
Robert Schuppenies51df0642008-06-01 16:16:17 +0000450 .. versionadded:: 2.6
451
452
Georg Brandl8ec7f652007-08-15 14:28:01 +0000453.. function:: _getframe([depth])
454
455 Return a frame object from the call stack. If optional integer *depth* is
456 given, return the frame object that many calls below the top of the stack. If
457 that is deeper than the call stack, :exc:`ValueError` is raised. The default
458 for *depth* is zero, returning the frame at the top of the call stack.
459
Georg Brandl6c14e582009-10-22 11:48:10 +0000460 .. impl-detail::
461
462 This function should be used for internal and specialized purposes only.
463 It is not guaranteed to exist in all implementations of Python.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000464
465
Georg Brandl56112892008-01-20 13:59:46 +0000466.. function:: getprofile()
467
468 .. index::
469 single: profile function
470 single: profiler
471
472 Get the profiler function as set by :func:`setprofile`.
473
474 .. versionadded:: 2.6
475
476
477.. function:: gettrace()
478
479 .. index::
480 single: trace function
481 single: debugger
482
483 Get the trace function as set by :func:`settrace`.
484
Georg Brandl6c14e582009-10-22 11:48:10 +0000485 .. impl-detail::
Georg Brandl56112892008-01-20 13:59:46 +0000486
487 The :func:`gettrace` function is intended only for implementing debuggers,
Georg Brandl6c14e582009-10-22 11:48:10 +0000488 profilers, coverage tools and the like. Its behavior is part of the
489 implementation platform, rather than part of the language definition, and
490 thus may not be available in all Python implementations.
Georg Brandl56112892008-01-20 13:59:46 +0000491
492 .. versionadded:: 2.6
493
494
Georg Brandl8ec7f652007-08-15 14:28:01 +0000495.. function:: getwindowsversion()
496
Eric Smith096d0bf2010-01-27 00:55:16 +0000497 Return a named tuple describing the Windows version
Eric Smithee931b72010-01-27 00:28:29 +0000498 currently running. The named elements are *major*, *minor*,
499 *build*, *platform*, *service_pack*, *service_pack_minor*,
500 *service_pack_major*, *suite_mask*, and *product_type*.
501 *service_pack* contains a string while all other values are
502 integers. The components can also be accessed by name, so
503 ``sys.getwindowsversion()[0]`` is equivalent to
504 ``sys.getwindowsversion().major``. For compatibility with prior
505 versions, only the first 5 elements are retrievable by indexing.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000506
507 *platform* may be one of the following values:
508
Jeroen Ruigrok van der Wervenaa3cadb2008-04-21 20:15:39 +0000509 +-----------------------------------------+-------------------------+
510 | Constant | Platform |
511 +=========================================+=========================+
512 | :const:`0 (VER_PLATFORM_WIN32s)` | Win32s on Windows 3.1 |
513 +-----------------------------------------+-------------------------+
514 | :const:`1 (VER_PLATFORM_WIN32_WINDOWS)` | Windows 95/98/ME |
515 +-----------------------------------------+-------------------------+
516 | :const:`2 (VER_PLATFORM_WIN32_NT)` | Windows NT/2000/XP/x64 |
517 +-----------------------------------------+-------------------------+
518 | :const:`3 (VER_PLATFORM_WIN32_CE)` | Windows CE |
519 +-----------------------------------------+-------------------------+
Georg Brandl8ec7f652007-08-15 14:28:01 +0000520
Eric Smithee931b72010-01-27 00:28:29 +0000521 *product_type* may be one of the following values:
522
523 +---------------------------------------+---------------------------------+
524 | Constant | Meaning |
525 +=======================================+=================================+
526 | :const:`1 (VER_NT_WORKSTATION)` | The system is a workstation. |
527 +---------------------------------------+---------------------------------+
528 | :const:`2 (VER_NT_DOMAIN_CONTROLLER)` | The system is a domain |
529 | | controller. |
530 +---------------------------------------+---------------------------------+
531 | :const:`3 (VER_NT_SERVER)` | The system is a server, but not |
532 | | a domain controller. |
533 +---------------------------------------+---------------------------------+
534
535
536 This function wraps the Win32 :cfunc:`GetVersionEx` function; see the
537 Microsoft documentation on :cfunc:`OSVERSIONINFOEX` for more information
538 about these fields.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000539
540 Availability: Windows.
541
542 .. versionadded:: 2.3
Eric Smithee931b72010-01-27 00:28:29 +0000543 .. versionchanged:: 2.7
544 Changed to a named tuple and added *service_pack_minor*,
545 *service_pack_major*, *suite_mask*, and *product_type*.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000546
547
548.. data:: hexversion
549
550 The version number encoded as a single integer. This is guaranteed to increase
551 with each version, including proper support for non-production releases. For
552 example, to test that the Python interpreter is at least version 1.5.2, use::
553
554 if sys.hexversion >= 0x010502F0:
555 # use some advanced feature
556 ...
557 else:
558 # use an alternative implementation or warn the user
559 ...
560
561 This is called ``hexversion`` since it only really looks meaningful when viewed
562 as the result of passing it to the built-in :func:`hex` function. The
563 ``version_info`` value may be used for a more human-friendly encoding of the
564 same information.
565
566 .. versionadded:: 1.5.2
567
568
Mark Dickinsonefc82f72009-03-20 15:51:55 +0000569.. data:: long_info
570
571 A struct sequence that holds information about Python's
572 internal representation of integers. The attributes are read only.
573
574 +-------------------------+----------------------------------------------+
575 | attribute | explanation |
576 +=========================+==============================================+
577 | :const:`bits_per_digit` | number of bits held in each digit. Python |
578 | | integers are stored internally in base |
579 | | ``2**long_info.bits_per_digit`` |
580 +-------------------------+----------------------------------------------+
581 | :const:`sizeof_digit` | size in bytes of the C type used to |
582 | | represent a digit |
583 +-------------------------+----------------------------------------------+
584
585 .. versionadded:: 2.7
586
587
Georg Brandl8ec7f652007-08-15 14:28:01 +0000588.. data:: last_type
589 last_value
590 last_traceback
591
592 These three variables are not always defined; they are set when an exception is
593 not handled and the interpreter prints an error message and a stack traceback.
594 Their intended use is to allow an interactive user to import a debugger module
595 and engage in post-mortem debugging without having to re-execute the command
596 that caused the error. (Typical use is ``import pdb; pdb.pm()`` to enter the
597 post-mortem debugger; see chapter :ref:`debugger` for
598 more information.)
599
600 The meaning of the variables is the same as that of the return values from
601 :func:`exc_info` above. (Since there is only one interactive thread,
602 thread-safety is not a concern for these variables, unlike for ``exc_type``
603 etc.)
604
605
606.. data:: maxint
607
608 The largest positive integer supported by Python's regular integer type. This
609 is at least 2\*\*31-1. The largest negative integer is ``-maxint-1`` --- the
610 asymmetry results from the use of 2's complement binary arithmetic.
611
Martin v. Löwis4dd019f2008-05-20 08:11:19 +0000612.. data:: maxsize
613
614 The largest positive integer supported by the platform's Py_ssize_t type,
615 and thus the maximum size lists, strings, dicts, and many other containers
616 can have.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000617
618.. data:: maxunicode
619
620 An integer giving the largest supported code point for a Unicode character. The
621 value of this depends on the configuration option that specifies whether Unicode
622 characters are stored as UCS-2 or UCS-4.
623
624
Georg Brandl624f3372009-03-31 16:11:45 +0000625.. data:: meta_path
626
627 A list of :term:`finder` objects that have their :meth:`find_module`
628 methods called to see if one of the objects can find the module to be
629 imported. The :meth:`find_module` method is called at least with the
630 absolute name of the module being imported. If the module to be imported is
631 contained in package then the parent package's :attr:`__path__` attribute
632 is passed in as a second argument. The method returns :keyword:`None` if
633 the module cannot be found, else returns a :term:`loader`.
634
635 :data:`sys.meta_path` is searched before any implicit default finders or
636 :data:`sys.path`.
637
638 See :pep:`302` for the original specification.
639
640
Georg Brandl8ec7f652007-08-15 14:28:01 +0000641.. data:: modules
642
643 .. index:: builtin: reload
644
645 This is a dictionary that maps module names to modules which have already been
646 loaded. This can be manipulated to force reloading of modules and other tricks.
647 Note that removing a module from this dictionary is *not* the same as calling
648 :func:`reload` on the corresponding module object.
649
650
651.. data:: path
652
653 .. index:: triple: module; search; path
654
655 A list of strings that specifies the search path for modules. Initialized from
656 the environment variable :envvar:`PYTHONPATH`, plus an installation-dependent
657 default.
658
659 As initialized upon program startup, the first item of this list, ``path[0]``,
660 is the directory containing the script that was used to invoke the Python
661 interpreter. If the script directory is not available (e.g. if the interpreter
662 is invoked interactively or if the script is read from standard input),
663 ``path[0]`` is the empty string, which directs Python to search modules in the
664 current directory first. Notice that the script directory is inserted *before*
665 the entries inserted as a result of :envvar:`PYTHONPATH`.
666
667 A program is free to modify this list for its own purposes.
668
669 .. versionchanged:: 2.3
670 Unicode strings are no longer ignored.
671
Benjamin Peterson4db53b22009-01-10 23:41:59 +0000672 .. seealso::
673 Module :mod:`site` This describes how to use .pth files to extend
674 :data:`sys.path`.
675
Georg Brandl8ec7f652007-08-15 14:28:01 +0000676
Georg Brandl624f3372009-03-31 16:11:45 +0000677.. data:: path_hooks
678
679 A list of callables that take a path argument to try to create a
680 :term:`finder` for the path. If a finder can be created, it is to be
681 returned by the callable, else raise :exc:`ImportError`.
682
683 Originally specified in :pep:`302`.
684
685
686.. data:: path_importer_cache
687
688 A dictionary acting as a cache for :term:`finder` objects. The keys are
689 paths that have been passed to :data:`sys.path_hooks` and the values are
690 the finders that are found. If a path is a valid file system path but no
691 explicit finder is found on :data:`sys.path_hooks` then :keyword:`None` is
692 stored to represent the implicit default finder should be used. If the path
693 is not an existing path then :class:`imp.NullImporter` is set.
694
695 Originally specified in :pep:`302`.
696
697
Georg Brandl8ec7f652007-08-15 14:28:01 +0000698.. data:: platform
699
Georg Brandl440f2ff2008-01-20 12:57:47 +0000700 This string contains a platform identifier that can be used to append
701 platform-specific components to :data:`sys.path`, for instance.
702
703 For Unix systems, this is the lowercased OS name as returned by ``uname -s``
704 with the first part of the version as returned by ``uname -r`` appended,
705 e.g. ``'sunos5'`` or ``'linux2'``, *at the time when Python was built*.
706 For other systems, the values are:
707
708 ================ ===========================
709 System :data:`platform` value
710 ================ ===========================
711 Windows ``'win32'``
712 Windows/Cygwin ``'cygwin'``
Georg Brandl9af94982008-09-13 17:41:16 +0000713 Mac OS X ``'darwin'``
Georg Brandl440f2ff2008-01-20 12:57:47 +0000714 OS/2 ``'os2'``
715 OS/2 EMX ``'os2emx'``
716 RiscOS ``'riscos'``
717 AtheOS ``'atheos'``
718 ================ ===========================
Georg Brandl8ec7f652007-08-15 14:28:01 +0000719
720
721.. data:: prefix
722
723 A string giving the site-specific directory prefix where the platform
724 independent Python files are installed; by default, this is the string
725 ``'/usr/local'``. This can be set at build time with the :option:`--prefix`
726 argument to the :program:`configure` script. The main collection of Python
727 library modules is installed in the directory ``prefix + '/lib/pythonversion'``
728 while the platform independent header files (all except :file:`pyconfig.h`) are
729 stored in ``prefix + '/include/pythonversion'``, where *version* is equal to
730 ``version[:3]``.
731
732
733.. data:: ps1
734 ps2
735
736 .. index::
737 single: interpreter prompts
738 single: prompts, interpreter
739
740 Strings specifying the primary and secondary prompt of the interpreter. These
741 are only defined if the interpreter is in interactive mode. Their initial
742 values in this case are ``'>>> '`` and ``'... '``. If a non-string object is
743 assigned to either variable, its :func:`str` is re-evaluated each time the
744 interpreter prepares to read a new interactive command; this can be used to
745 implement a dynamic prompt.
746
747
Christian Heimesd7b33372007-11-28 08:02:36 +0000748.. data:: py3kwarning
749
750 Bool containing the status of the Python 3.0 warning flag. It's ``True``
Georg Brandl13813f72009-02-26 17:36:26 +0000751 when Python is started with the -3 option. (This should be considered
752 read-only; setting it to a different value doesn't have an effect on
753 Python 3.0 warnings.)
Christian Heimesd7b33372007-11-28 08:02:36 +0000754
Georg Brandl5f794462008-03-21 21:05:03 +0000755 .. versionadded:: 2.6
756
Christian Heimesd7b33372007-11-28 08:02:36 +0000757
Georg Brandl2da0fce2008-01-07 17:09:35 +0000758.. data:: dont_write_bytecode
759
760 If this is true, Python won't try to write ``.pyc`` or ``.pyo`` files on the
761 import of source modules. This value is initially set to ``True`` or ``False``
762 depending on the ``-B`` command line option and the ``PYTHONDONTWRITEBYTECODE``
763 environment variable, but you can set it yourself to control bytecode file
764 generation.
765
766 .. versionadded:: 2.6
767
768
Georg Brandl8ec7f652007-08-15 14:28:01 +0000769.. function:: setcheckinterval(interval)
770
771 Set the interpreter's "check interval". This integer value determines how often
772 the interpreter checks for periodic things such as thread switches and signal
773 handlers. The default is ``100``, meaning the check is performed every 100
774 Python virtual instructions. Setting it to a larger value may increase
775 performance for programs using threads. Setting it to a value ``<=`` 0 checks
776 every virtual instruction, maximizing responsiveness as well as overhead.
777
778
779.. function:: setdefaultencoding(name)
780
781 Set the current default string encoding used by the Unicode implementation. If
782 *name* does not match any available encoding, :exc:`LookupError` is raised.
783 This function is only intended to be used by the :mod:`site` module
784 implementation and, where needed, by :mod:`sitecustomize`. Once used by the
785 :mod:`site` module, it is removed from the :mod:`sys` module's namespace.
786
Georg Brandlb19be572007-12-29 10:57:00 +0000787 .. Note that :mod:`site` is not imported if the :option:`-S` option is passed
788 to the interpreter, in which case this function will remain available.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000789
790 .. versionadded:: 2.0
791
792
793.. function:: setdlopenflags(n)
794
795 Set the flags used by the interpreter for :cfunc:`dlopen` calls, such as when
796 the interpreter loads extension modules. Among other things, this will enable a
797 lazy resolving of symbols when importing a module, if called as
798 ``sys.setdlopenflags(0)``. To share symbols across extension modules, call as
799 ``sys.setdlopenflags(dl.RTLD_NOW | dl.RTLD_GLOBAL)``. Symbolic names for the
800 flag modules can be either found in the :mod:`dl` module, or in the :mod:`DLFCN`
801 module. If :mod:`DLFCN` is not available, it can be generated from
802 :file:`/usr/include/dlfcn.h` using the :program:`h2py` script. Availability:
803 Unix.
804
805 .. versionadded:: 2.2
806
807
808.. function:: setprofile(profilefunc)
809
810 .. index::
811 single: profile function
812 single: profiler
813
814 Set the system's profile function, which allows you to implement a Python source
815 code profiler in Python. See chapter :ref:`profile` for more information on the
816 Python profiler. The system's profile function is called similarly to the
817 system's trace function (see :func:`settrace`), but it isn't called for each
818 executed line of code (only on call and return, but the return event is reported
819 even when an exception has been set). The function is thread-specific, but
820 there is no way for the profiler to know about context switches between threads,
821 so it does not make sense to use this in the presence of multiple threads. Also,
822 its return value is not used, so it can simply return ``None``.
823
824
825.. function:: setrecursionlimit(limit)
826
827 Set the maximum depth of the Python interpreter stack to *limit*. This limit
828 prevents infinite recursion from causing an overflow of the C stack and crashing
829 Python.
830
831 The highest possible limit is platform-dependent. A user may need to set the
832 limit higher when she has a program that requires deep recursion and a platform
833 that supports a higher limit. This should be done with care, because a too-high
834 limit can lead to a crash.
835
836
837.. function:: settrace(tracefunc)
838
839 .. index::
840 single: trace function
841 single: debugger
842
843 Set the system's trace function, which allows you to implement a Python
Benjamin Peterson050f4ad2008-11-20 21:25:31 +0000844 source code debugger in Python. The function is thread-specific; for a
Georg Brandl8ec7f652007-08-15 14:28:01 +0000845 debugger to support multiple threads, it must be registered using
846 :func:`settrace` for each thread being debugged.
847
Benjamin Peterson5ab9c3b2008-11-20 04:05:12 +0000848 Trace functions should have three arguments: *frame*, *event*, and
849 *arg*. *frame* is the current stack frame. *event* is a string: ``'call'``,
850 ``'line'``, ``'return'``, ``'exception'``, ``'c_call'``, ``'c_return'``, or
851 ``'c_exception'``. *arg* depends on the event type.
852
853 The trace function is invoked (with *event* set to ``'call'``) whenever a new
854 local scope is entered; it should return a reference to a local trace
855 function to be used that scope, or ``None`` if the scope shouldn't be traced.
856
857 The local trace function should return a reference to itself (or to another
858 function for further tracing in that scope), or ``None`` to turn off tracing
859 in that scope.
860
861 The events have the following meaning:
862
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000863 ``'call'``
Benjamin Peterson5ab9c3b2008-11-20 04:05:12 +0000864 A function is called (or some other code block entered). The
865 global trace function is called; *arg* is ``None``; the return value
866 specifies the local trace function.
867
868 ``'line'``
Jeffrey Yasskin655d8352009-05-23 23:23:01 +0000869 The interpreter is about to execute a new line of code or re-execute the
870 condition of a loop. The local trace function is called; *arg* is
871 ``None``; the return value specifies the new local trace function. See
872 :file:`Objects/lnotab_notes.txt` for a detailed explanation of how this
873 works.
Benjamin Peterson5ab9c3b2008-11-20 04:05:12 +0000874
875 ``'return'``
876 A function (or other code block) is about to return. The local trace
877 function is called; *arg* is the value that will be returned. The trace
878 function's return value is ignored.
879
880 ``'exception'``
881 An exception has occurred. The local trace function is called; *arg* is a
882 tuple ``(exception, value, traceback)``; the return value specifies the
883 new local trace function.
884
885 ``'c_call'``
886 A C function is about to be called. This may be an extension function or
Georg Brandld7d4fd72009-07-26 14:37:28 +0000887 a built-in. *arg* is the C function object.
Benjamin Peterson5ab9c3b2008-11-20 04:05:12 +0000888
889 ``'c_return'``
890 A C function has returned. *arg* is ``None``.
891
892 ``'c_exception'``
893 A C function has thrown an exception. *arg* is ``None``.
894
Benjamin Peterson050f4ad2008-11-20 21:25:31 +0000895 Note that as an exception is propagated down the chain of callers, an
896 ``'exception'`` event is generated at each level.
Benjamin Peterson5ab9c3b2008-11-20 04:05:12 +0000897
Benjamin Peterson050f4ad2008-11-20 21:25:31 +0000898 For more information on code and frame objects, refer to :ref:`types`.
Benjamin Peterson5ab9c3b2008-11-20 04:05:12 +0000899
Georg Brandl6c14e582009-10-22 11:48:10 +0000900 .. impl-detail::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000901
902 The :func:`settrace` function is intended only for implementing debuggers,
Georg Brandl6c14e582009-10-22 11:48:10 +0000903 profilers, coverage tools and the like. Its behavior is part of the
904 implementation platform, rather than part of the language definition, and
905 thus may not be available in all Python implementations.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000906
907
908.. function:: settscdump(on_flag)
909
910 Activate dumping of VM measurements using the Pentium timestamp counter, if
911 *on_flag* is true. Deactivate these dumps if *on_flag* is off. The function is
912 available only if Python was compiled with :option:`--with-tsc`. To understand
913 the output of this dump, read :file:`Python/ceval.c` in the Python sources.
914
915 .. versionadded:: 2.4
916
Benjamin Petersona7fa0322010-03-06 03:13:33 +0000917 .. impl-detail::
918
919 This function is intimately bound to CPython implementation details and
920 thus not likely to be implemented elsewhere.
921
Georg Brandl8ec7f652007-08-15 14:28:01 +0000922
923.. data:: stdin
924 stdout
925 stderr
926
927 .. index::
928 builtin: input
929 builtin: raw_input
930
931 File objects corresponding to the interpreter's standard input, output and error
932 streams. ``stdin`` is used for all interpreter input except for scripts but
933 including calls to :func:`input` and :func:`raw_input`. ``stdout`` is used for
Georg Brandl584265b2007-12-02 14:58:50 +0000934 the output of :keyword:`print` and :term:`expression` statements and for the
935 prompts of :func:`input` and :func:`raw_input`. The interpreter's own prompts
936 and (almost all of) its error messages go to ``stderr``. ``stdout`` and
937 ``stderr`` needn't be built-in file objects: any object is acceptable as long
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000938 as it has a :meth:`write` method that takes a string argument. (Changing these
Georg Brandl584265b2007-12-02 14:58:50 +0000939 objects doesn't affect the standard I/O streams of processes executed by
Georg Brandl8ec7f652007-08-15 14:28:01 +0000940 :func:`os.popen`, :func:`os.system` or the :func:`exec\*` family of functions in
941 the :mod:`os` module.)
942
943
944.. data:: __stdin__
945 __stdout__
946 __stderr__
947
948 These objects contain the original values of ``stdin``, ``stderr`` and
Georg Brandlb48adec2009-03-31 19:10:35 +0000949 ``stdout`` at the start of the program. They are used during finalization,
950 and could be useful to print to the actual standard stream no matter if the
951 ``sys.std*`` object has been redirected.
952
953 It can also be used to restore the actual files to known working file objects
954 in case they have been overwritten with a broken object. However, the
955 preferred way to do this is to explicitly save the previous stream before
956 replacing it, and restore the saved object.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000957
958
959.. data:: tracebacklimit
960
961 When this variable is set to an integer value, it determines the maximum number
962 of levels of traceback information printed when an unhandled exception occurs.
963 The default is ``1000``. When set to ``0`` or less, all traceback information
964 is suppressed and only the exception type and value are printed.
965
966
967.. data:: version
968
969 A string containing the version number of the Python interpreter plus additional
Georg Brandle2773252010-08-01 19:14:56 +0000970 information on the build number and compiler used. This string is displayed
971 when the interactive interpreter is started. Do not extract version information
972 out of it, rather, use :data:`version_info` and the functions provided by the
973 :mod:`platform` module.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000974
975
976.. data:: api_version
977
978 The C API version for this interpreter. Programmers may find this useful when
979 debugging version conflicts between Python and extension modules.
980
981 .. versionadded:: 2.3
982
983
984.. data:: version_info
985
986 A tuple containing the five components of the version number: *major*, *minor*,
987 *micro*, *releaselevel*, and *serial*. All values except *releaselevel* are
988 integers; the release level is ``'alpha'``, ``'beta'``, ``'candidate'``, or
989 ``'final'``. The ``version_info`` value corresponding to the Python version 2.0
Eric Smith81fe0932009-02-06 00:48:26 +0000990 is ``(2, 0, 0, 'final', 0)``. The components can also be accessed by name,
991 so ``sys.version_info[0]`` is equivalent to ``sys.version_info.major``
992 and so on.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000993
994 .. versionadded:: 2.0
Eric Smith81fe0932009-02-06 00:48:26 +0000995 .. versionchanged:: 2.7
996 Added named component attributes
Georg Brandl8ec7f652007-08-15 14:28:01 +0000997
998
999.. data:: warnoptions
1000
1001 This is an implementation detail of the warnings framework; do not modify this
1002 value. Refer to the :mod:`warnings` module for more information on the warnings
1003 framework.
1004
1005
1006.. data:: winver
1007
1008 The version number used to form registry keys on Windows platforms. This is
1009 stored as string resource 1000 in the Python DLL. The value is normally the
1010 first three characters of :const:`version`. It is provided in the :mod:`sys`
1011 module for informational purposes; modifying this value has no effect on the
1012 registry keys used by Python. Availability: Windows.
Mark Dickinson2547ce72010-07-02 18:06:52 +00001013
1014.. rubric:: Citations
1015
1016.. [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 .
1017