blob: 7f3d82757cd1c3ec6eb90b08dbd707c08f611310 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`sys` --- System-specific parameters and functions
2=======================================================
3
4.. module:: sys
5 :synopsis: Access system-specific parameters and functions.
6
7
8This module provides access to some variables used or maintained by the
9interpreter and to functions that interact strongly with the interpreter. It is
10always available.
11
12
Barry Warsawa40453d2010-10-16 14:17:50 +000013.. data:: abiflags
14
15 On POSIX systems where Python is build with the standard ``configure``
16 script, this contains the ABI flags as specified by :pep:`3149`.
17
18 .. versionadded:: 3.2
19
Georg Brandl116aa622007-08-15 14:28:22 +000020.. data:: argv
21
22 The list of command line arguments passed to a Python script. ``argv[0]`` is the
23 script name (it is operating system dependent whether this is a full pathname or
24 not). If the command was executed using the :option:`-c` command line option to
25 the interpreter, ``argv[0]`` is set to the string ``'-c'``. If no script name
26 was passed to the Python interpreter, ``argv[0]`` is the empty string.
27
28 To loop over the standard input, or the list of files given on the
29 command line, see the :mod:`fileinput` module.
30
31
32.. data:: byteorder
33
34 An indicator of the native byte order. This will have the value ``'big'`` on
35 big-endian (most-significant byte first) platforms, and ``'little'`` on
36 little-endian (least-significant byte first) platforms.
37
Georg Brandl116aa622007-08-15 14:28:22 +000038
Georg Brandl116aa622007-08-15 14:28:22 +000039.. data:: builtin_module_names
40
41 A tuple of strings giving the names of all modules that are compiled into this
42 Python interpreter. (This information is not available in any other way ---
43 ``modules.keys()`` only lists the imported modules.)
44
45
Georg Brandl85271262010-10-17 11:06:14 +000046.. function:: call_tracing(func, args)
47
48 Call ``func(*args)``, while tracing is enabled. The tracing state is saved,
49 and restored afterwards. This is intended to be called from a debugger from
50 a checkpoint, to recursively debug some other code.
51
52
Georg Brandl116aa622007-08-15 14:28:22 +000053.. data:: copyright
54
55 A string containing the copyright pertaining to the Python interpreter.
56
57
Christian Heimes15ebc882008-02-04 18:48:49 +000058.. function:: _clear_type_cache()
59
60 Clear the internal type cache. The type cache is used to speed up attribute
61 and method lookups. Use the function *only* to drop unnecessary references
62 during reference leak debugging.
63
64 This function should be used for internal and specialized purposes only.
Christian Heimes26855632008-01-27 23:50:43 +000065
Christian Heimes26855632008-01-27 23:50:43 +000066
Georg Brandl116aa622007-08-15 14:28:22 +000067.. function:: _current_frames()
68
69 Return a dictionary mapping each thread's identifier to the topmost stack frame
70 currently active in that thread at the time the function is called. Note that
71 functions in the :mod:`traceback` module can build the call stack given such a
72 frame.
73
74 This is most useful for debugging deadlock: this function does not require the
75 deadlocked threads' cooperation, and such threads' call stacks are frozen for as
76 long as they remain deadlocked. The frame returned for a non-deadlocked thread
77 may bear no relationship to that thread's current activity by the time calling
78 code examines the frame.
79
80 This function should be used for internal and specialized purposes only.
81
Georg Brandl116aa622007-08-15 14:28:22 +000082
83.. data:: dllhandle
84
85 Integer specifying the handle of the Python DLL. Availability: Windows.
86
87
88.. function:: displayhook(value)
89
Victor Stinner13d49ee2010-12-04 17:24:33 +000090 If *value* is not ``None``, this function prints ``repr(value)`` to
91 ``sys.stdout``, and saves *value* in ``builtins._``. If ``repr(value)`` is
92 not encodable to ``sys.stdout.encoding`` with ``sys.stdout.errors`` error
93 handler (which is probably ``'strict'``), encode it to
94 ``sys.stdout.encoding`` with ``'backslashreplace'`` error handler.
Georg Brandl116aa622007-08-15 14:28:22 +000095
Christian Heimesd8654cf2007-12-02 15:22:16 +000096 ``sys.displayhook`` is called on the result of evaluating an :term:`expression`
97 entered in an interactive Python session. The display of these values can be
98 customized by assigning another one-argument function to ``sys.displayhook``.
Georg Brandl116aa622007-08-15 14:28:22 +000099
Victor Stinner13d49ee2010-12-04 17:24:33 +0000100 Pseudo-code::
101
102 def displayhook(value):
103 if value is None:
104 return
105 # Set '_' to None to avoid recursion
106 builtins._ = None
107 text = repr(value)
108 try:
109 sys.stdout.write(text)
110 except UnicodeEncodeError:
111 bytes = text.encode(sys.stdout.encoding, 'backslashreplace')
112 if hasattr(sys.stdout, 'buffer'):
113 sys.stdout.buffer.write(bytes)
114 else:
115 text = bytes.decode(sys.stdout.encoding, 'strict')
116 sys.stdout.write(text)
117 sys.stdout.write("\n")
118 builtins._ = value
119
120 .. versionchanged:: 3.2
121 Use ``'backslashreplace'`` error handler on :exc:`UnicodeEncodeError`.
122
Georg Brandl116aa622007-08-15 14:28:22 +0000123
124.. function:: excepthook(type, value, traceback)
125
126 This function prints out a given traceback and exception to ``sys.stderr``.
127
128 When an exception is raised and uncaught, the interpreter calls
129 ``sys.excepthook`` with three arguments, the exception class, exception
130 instance, and a traceback object. In an interactive session this happens just
131 before control is returned to the prompt; in a Python program this happens just
132 before the program exits. The handling of such top-level exceptions can be
133 customized by assigning another three-argument function to ``sys.excepthook``.
134
135
136.. data:: __displayhook__
137 __excepthook__
138
139 These objects contain the original values of ``displayhook`` and ``excepthook``
140 at the start of the program. They are saved so that ``displayhook`` and
141 ``excepthook`` can be restored in case they happen to get replaced with broken
142 objects.
143
144
145.. function:: exc_info()
146
147 This function returns a tuple of three values that give information about the
148 exception that is currently being handled. The information returned is specific
149 both to the current thread and to the current stack frame. If the current stack
150 frame is not handling an exception, the information is taken from the calling
151 stack frame, or its caller, and so on until a stack frame is found that is
152 handling an exception. Here, "handling an exception" is defined as "executing
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000153 an except clause." For any stack frame, only information about the exception
154 being currently handled is accessible.
Georg Brandl116aa622007-08-15 14:28:22 +0000155
156 .. index:: object: traceback
157
Georg Brandl482b1512010-03-21 09:02:59 +0000158 If no exception is being handled anywhere on the stack, a tuple containing
159 three ``None`` values is returned. Otherwise, the values returned are
160 ``(type, value, traceback)``. Their meaning is: *type* gets the type of the
161 exception being handled (a subclass of :exc:`BaseException`); *value* gets
162 the exception instance (an instance of the exception type); *traceback* gets
163 a traceback object (see the Reference Manual) which encapsulates the call
Georg Brandl116aa622007-08-15 14:28:22 +0000164 stack at the point where the exception originally occurred.
165
166 .. warning::
167
Georg Brandle6bcc912008-05-12 18:05:20 +0000168 Assigning the *traceback* return value to a local variable in a function
169 that is handling an exception will cause a circular reference. Since most
170 functions don't need access to the traceback, the best solution is to use
171 something like ``exctype, value = sys.exc_info()[:2]`` to extract only the
172 exception type and value. If you do need the traceback, make sure to
173 delete it after use (best done with a :keyword:`try`
174 ... :keyword:`finally` statement) or to call :func:`exc_info` in a
175 function that does not itself handle an exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000176
Georg Brandle6bcc912008-05-12 18:05:20 +0000177 Such cycles are normally automatically reclaimed when garbage collection
178 is enabled and they become unreachable, but it remains more efficient to
179 avoid creating cycles.
Georg Brandl116aa622007-08-15 14:28:22 +0000180
181
182.. data:: exec_prefix
183
184 A string giving the site-specific directory prefix where the platform-dependent
185 Python files are installed; by default, this is also ``'/usr/local'``. This can
Éric Araujo713d3032010-11-18 16:38:46 +0000186 be set at build time with the ``--exec-prefix`` argument to the
Georg Brandl116aa622007-08-15 14:28:22 +0000187 :program:`configure` script. Specifically, all configuration files (e.g. the
188 :file:`pyconfig.h` header file) are installed in the directory ``exec_prefix +
189 '/lib/pythonversion/config'``, and shared library modules are installed in
190 ``exec_prefix + '/lib/pythonversion/lib-dynload'``, where *version* is equal to
191 ``version[:3]``.
192
193
194.. data:: executable
195
196 A string giving the name of the executable binary for the Python interpreter, on
197 systems where this makes sense.
198
199
200.. function:: exit([arg])
201
202 Exit from Python. This is implemented by raising the :exc:`SystemExit`
203 exception, so cleanup actions specified by finally clauses of :keyword:`try`
Georg Brandl6f4e68d2010-10-17 10:51:45 +0000204 statements are honored, and it is possible to intercept the exit attempt at
205 an outer level.
206
207 The optional argument *arg* can be an integer giving the exit status
208 (defaulting to zero), or another type of object. If it is an integer, zero
209 is considered "successful termination" and any nonzero value is considered
210 "abnormal termination" by shells and the like. Most systems require it to be
211 in the range 0-127, and produce undefined results otherwise. Some systems
212 have a convention for assigning specific meanings to specific exit codes, but
213 these are generally underdeveloped; Unix programs generally use 2 for command
214 line syntax errors and 1 for all other kind of errors. If another type of
215 object is passed, ``None`` is equivalent to passing zero, and any other
216 object is printed to :data:`stderr` and results in an exit code of 1. In
217 particular, ``sys.exit("some error message")`` is a quick way to exit a
218 program when an error occurs.
219
220 Since :func:`exit` ultimately "only" raises an exception, it will only exit
221 the process when called from the main thread, and the exception is not
222 intercepted.
Georg Brandl116aa622007-08-15 14:28:22 +0000223
224
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000225.. data:: flags
226
227 The struct sequence *flags* exposes the status of command line flags. The
228 attributes are read only.
229
Éric Araujo5ab47762011-03-26 00:47:04 +0100230 ============================= =============================
231 attribute flag
232 ============================= =============================
233 :const:`debug` :option:`-d`
234 :const:`division_warning` :option:`-Q`
235 :const:`inspect` :option:`-i`
236 :const:`interactive` :option:`-i`
237 :const:`optimize` :option:`-O` or :option:`-OO`
238 :const:`dont_write_bytecode` :option:`-B`
239 :const:`no_user_site` :option:`-s`
240 :const:`no_site` :option:`-S`
241 :const:`ignore_environment` :option:`-E`
242 :const:`verbose` :option:`-v`
243 :const:`bytes_warning` :option:`-b`
Éric Araujo722bec42011-03-26 01:59:47 +0100244 :const:`quiet` :option:`-q`
Éric Araujo5ab47762011-03-26 00:47:04 +0100245 ============================= =============================
Georg Brandl8aa7e992010-12-28 18:30:18 +0000246
247 .. versionchanged:: 3.2
248 Added ``quiet`` attribute for the new :option:`-q` flag.
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000249
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000250
Christian Heimes93852662007-12-01 12:22:32 +0000251.. data:: float_info
252
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000253 A structseq holding information about the float type. It contains low level
Mark Dickinsonbe5846b2010-07-02 20:26:07 +0000254 information about the precision and internal representation. The values
255 correspond to the various floating-point constants defined in the standard
256 header file :file:`float.h` for the 'C' programming language; see section
257 5.2.4.2.2 of the 1999 ISO/IEC C standard [C99]_, 'Characteristics of
258 floating types', for details.
Christian Heimes93852662007-12-01 12:22:32 +0000259
Mark Dickinsonbe5846b2010-07-02 20:26:07 +0000260 +---------------------+----------------+--------------------------------------------------+
261 | attribute | float.h macro | explanation |
262 +=====================+================+==================================================+
Mark Dickinson39af05f2010-07-03 09:17:16 +0000263 | :const:`epsilon` | DBL_EPSILON | difference between 1 and the least value greater |
Mark Dickinsonbe5846b2010-07-02 20:26:07 +0000264 | | | than 1 that is representable as a float |
265 +---------------------+----------------+--------------------------------------------------+
266 | :const:`dig` | DBL_DIG | maximum number of decimal digits that can be |
267 | | | faithfully represented in a float; see below |
268 +---------------------+----------------+--------------------------------------------------+
269 | :const:`mant_dig` | DBL_MANT_DIG | float precision: the number of base-``radix`` |
270 | | | digits in the significand of a float |
271 +---------------------+----------------+--------------------------------------------------+
272 | :const:`max` | DBL_MAX | maximum representable finite float |
273 +---------------------+----------------+--------------------------------------------------+
274 | :const:`max_exp` | DBL_MAX_EXP | maximum integer e such that ``radix**(e-1)`` is |
275 | | | a representable finite float |
276 +---------------------+----------------+--------------------------------------------------+
277 | :const:`max_10_exp` | DBL_MAX_10_EXP | maximum integer e such that ``10**e`` is in the |
278 | | | range of representable finite floats |
279 +---------------------+----------------+--------------------------------------------------+
280 | :const:`min` | DBL_MIN | minimum positive normalized float |
281 +---------------------+----------------+--------------------------------------------------+
282 | :const:`min_exp` | DBL_MIN_EXP | minimum integer e such that ``radix**(e-1)`` is |
283 | | | a normalized float |
284 +---------------------+----------------+--------------------------------------------------+
285 | :const:`min_10_exp` | DBL_MIN_10_EXP | minimum integer e such that ``10**e`` is a |
286 | | | normalized float |
287 +---------------------+----------------+--------------------------------------------------+
288 | :const:`radix` | FLT_RADIX | radix of exponent representation |
289 +---------------------+----------------+--------------------------------------------------+
290 | :const:`rounds` | FLT_ROUNDS | constant representing rounding mode |
291 | | | used for arithmetic operations |
292 +---------------------+----------------+--------------------------------------------------+
Christian Heimes93852662007-12-01 12:22:32 +0000293
Mark Dickinsonbe5846b2010-07-02 20:26:07 +0000294 The attribute :attr:`sys.float_info.dig` needs further explanation. If
295 ``s`` is any string representing a decimal number with at most
296 :attr:`sys.float_info.dig` significant digits, then converting ``s`` to a
297 float and back again will recover a string representing the same decimal
298 value::
Christian Heimes93852662007-12-01 12:22:32 +0000299
Mark Dickinsonbe5846b2010-07-02 20:26:07 +0000300 >>> import sys
301 >>> sys.float_info.dig
302 15
303 >>> s = '3.14159265358979' # decimal string with 15 significant digits
304 >>> format(float(s), '.15g') # convert to float and back -> same value
305 '3.14159265358979'
Christian Heimes93852662007-12-01 12:22:32 +0000306
Mark Dickinsonbe5846b2010-07-02 20:26:07 +0000307 But for strings with more than :attr:`sys.float_info.dig` significant digits,
308 this isn't always true::
309
310 >>> s = '9876543211234567' # 16 significant digits is too many!
311 >>> format(float(s), '.16g') # conversion changes value
312 '9876543211234568'
Christian Heimes93852662007-12-01 12:22:32 +0000313
Mark Dickinsonb08a53a2009-04-16 19:52:09 +0000314.. data:: float_repr_style
315
316 A string indicating how the :func:`repr` function behaves for
317 floats. If the string has value ``'short'`` then for a finite
318 float ``x``, ``repr(x)`` aims to produce a short string with the
319 property that ``float(repr(x)) == x``. This is the usual behaviour
320 in Python 3.1 and later. Otherwise, ``float_repr_style`` has value
321 ``'legacy'`` and ``repr(x)`` behaves in the same way as it did in
322 versions of Python prior to 3.1.
323
324 .. versionadded:: 3.1
325
326
Georg Brandl116aa622007-08-15 14:28:22 +0000327.. function:: getcheckinterval()
328
329 Return the interpreter's "check interval"; see :func:`setcheckinterval`.
330
Antoine Pitroud42bc512009-11-10 23:18:31 +0000331 .. deprecated:: 3.2
332 Use :func:`getswitchinterval` instead.
333
Georg Brandl116aa622007-08-15 14:28:22 +0000334
335.. function:: getdefaultencoding()
336
337 Return the name of the current default string encoding used by the Unicode
338 implementation.
339
Georg Brandl116aa622007-08-15 14:28:22 +0000340
341.. function:: getdlopenflags()
342
Georg Brandl60203b42010-10-06 10:11:56 +0000343 Return the current value of the flags that are used for :c:func:`dlopen` calls.
Neal Norwitz6cf49cf2008-03-24 06:22:57 +0000344 The flag constants are defined in the :mod:`ctypes` and :mod:`DLFCN` modules.
Georg Brandl116aa622007-08-15 14:28:22 +0000345 Availability: Unix.
346
Georg Brandl116aa622007-08-15 14:28:22 +0000347
348.. function:: getfilesystemencoding()
349
Victor Stinnerb744ba12010-05-15 12:27:16 +0000350 Return the name of the encoding used to convert Unicode filenames into
351 system file names. The result value depends on the operating system:
Georg Brandl116aa622007-08-15 14:28:22 +0000352
Ezio Melottid5334e12010-04-29 16:24:51 +0000353 * On Mac OS X, the encoding is ``'utf-8'``.
Georg Brandl116aa622007-08-15 14:28:22 +0000354
355 * On Unix, the encoding is the user's preference according to the result of
Victor Stinnerb744ba12010-05-15 12:27:16 +0000356 nl_langinfo(CODESET), or ``'utf-8'`` if ``nl_langinfo(CODESET)`` failed.
Georg Brandl116aa622007-08-15 14:28:22 +0000357
358 * On Windows NT+, file names are Unicode natively, so no conversion is
Ezio Melottid5334e12010-04-29 16:24:51 +0000359 performed. :func:`getfilesystemencoding` still returns ``'mbcs'``, as
360 this is the encoding that applications should use when they explicitly
361 want to convert Unicode strings to byte strings that are equivalent when
362 used as file names.
363
364 * On Windows 9x, the encoding is ``'mbcs'``.
Georg Brandl116aa622007-08-15 14:28:22 +0000365
Victor Stinnerb744ba12010-05-15 12:27:16 +0000366 .. versionchanged:: 3.2
367 On Unix, use ``'utf-8'`` instead of ``None`` if ``nl_langinfo(CODESET)``
368 failed. :func:`getfilesystemencoding` result cannot be ``None``.
369
Georg Brandl116aa622007-08-15 14:28:22 +0000370
371.. function:: getrefcount(object)
372
373 Return the reference count of the *object*. The count returned is generally one
374 higher than you might expect, because it includes the (temporary) reference as
375 an argument to :func:`getrefcount`.
376
377
378.. function:: getrecursionlimit()
379
380 Return the current value of the recursion limit, the maximum depth of the Python
381 interpreter stack. This limit prevents infinite recursion from causing an
382 overflow of the C stack and crashing Python. It can be set by
383 :func:`setrecursionlimit`.
384
385
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000386.. function:: getsizeof(object[, default])
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000387
388 Return the size of an object in bytes. The object can be any type of
389 object. All built-in objects will return correct results, but this
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000390 does not have to hold true for third-party extensions as it is implementation
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000391 specific.
392
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000393 If given, *default* will be returned if the object does not provide means to
Georg Brandlef871f62010-03-12 10:06:40 +0000394 retrieve the size. Otherwise a :exc:`TypeError` will be raised.
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000395
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000396 :func:`getsizeof` calls the object's ``__sizeof__`` method and adds an
397 additional garbage collector overhead if the object is managed by the garbage
398 collector.
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000399
Raymond Hettingerc539a2a2010-12-17 23:31:30 +0000400 See `recursive sizeof recipe <http://code.activestate.com/recipes/577504>`_
401 for an example of using :func:`getsizeof` recursively to find the size of
402 containers and all their contents.
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000403
Antoine Pitroud42bc512009-11-10 23:18:31 +0000404.. function:: getswitchinterval()
405
406 Return the interpreter's "thread switch interval"; see
407 :func:`setswitchinterval`.
408
Antoine Pitrou79707ca2009-11-11 22:03:32 +0000409 .. versionadded:: 3.2
410
Antoine Pitroud42bc512009-11-10 23:18:31 +0000411
Georg Brandl116aa622007-08-15 14:28:22 +0000412.. function:: _getframe([depth])
413
414 Return a frame object from the call stack. If optional integer *depth* is
415 given, return the frame object that many calls below the top of the stack. If
416 that is deeper than the call stack, :exc:`ValueError` is raised. The default
417 for *depth* is zero, returning the frame at the top of the call stack.
418
Georg Brandl495f7b52009-10-27 15:28:25 +0000419 .. impl-detail::
420
421 This function should be used for internal and specialized purposes only.
422 It is not guaranteed to exist in all implementations of Python.
Georg Brandl116aa622007-08-15 14:28:22 +0000423
424
Christian Heimes9bd667a2008-01-20 15:14:11 +0000425.. function:: getprofile()
426
427 .. index::
428 single: profile function
429 single: profiler
430
431 Get the profiler function as set by :func:`setprofile`.
432
Christian Heimes9bd667a2008-01-20 15:14:11 +0000433
434.. function:: gettrace()
435
436 .. index::
437 single: trace function
438 single: debugger
439
440 Get the trace function as set by :func:`settrace`.
441
Georg Brandl495f7b52009-10-27 15:28:25 +0000442 .. impl-detail::
Christian Heimes9bd667a2008-01-20 15:14:11 +0000443
444 The :func:`gettrace` function is intended only for implementing debuggers,
Georg Brandl495f7b52009-10-27 15:28:25 +0000445 profilers, coverage tools and the like. Its behavior is part of the
446 implementation platform, rather than part of the language definition, and
447 thus may not be available in all Python implementations.
Christian Heimes9bd667a2008-01-20 15:14:11 +0000448
Christian Heimes9bd667a2008-01-20 15:14:11 +0000449
Georg Brandl116aa622007-08-15 14:28:22 +0000450.. function:: getwindowsversion()
451
Eric Smith7338a392010-01-27 00:56:30 +0000452 Return a named tuple describing the Windows version
Eric Smithf7bb5782010-01-27 00:44:57 +0000453 currently running. The named elements are *major*, *minor*,
454 *build*, *platform*, *service_pack*, *service_pack_minor*,
455 *service_pack_major*, *suite_mask*, and *product_type*.
456 *service_pack* contains a string while all other values are
457 integers. The components can also be accessed by name, so
458 ``sys.getwindowsversion()[0]`` is equivalent to
459 ``sys.getwindowsversion().major``. For compatibility with prior
460 versions, only the first 5 elements are retrievable by indexing.
Georg Brandl116aa622007-08-15 14:28:22 +0000461
462 *platform* may be one of the following values:
463
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000464 +-----------------------------------------+-------------------------+
465 | Constant | Platform |
466 +=========================================+=========================+
467 | :const:`0 (VER_PLATFORM_WIN32s)` | Win32s on Windows 3.1 |
468 +-----------------------------------------+-------------------------+
469 | :const:`1 (VER_PLATFORM_WIN32_WINDOWS)` | Windows 95/98/ME |
470 +-----------------------------------------+-------------------------+
471 | :const:`2 (VER_PLATFORM_WIN32_NT)` | Windows NT/2000/XP/x64 |
472 +-----------------------------------------+-------------------------+
473 | :const:`3 (VER_PLATFORM_WIN32_CE)` | Windows CE |
474 +-----------------------------------------+-------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000475
Eric Smithf7bb5782010-01-27 00:44:57 +0000476 *product_type* may be one of the following values:
477
478 +---------------------------------------+---------------------------------+
479 | Constant | Meaning |
480 +=======================================+=================================+
481 | :const:`1 (VER_NT_WORKSTATION)` | The system is a workstation. |
482 +---------------------------------------+---------------------------------+
483 | :const:`2 (VER_NT_DOMAIN_CONTROLLER)` | The system is a domain |
484 | | controller. |
485 +---------------------------------------+---------------------------------+
486 | :const:`3 (VER_NT_SERVER)` | The system is a server, but not |
487 | | a domain controller. |
488 +---------------------------------------+---------------------------------+
489
490
Georg Brandl60203b42010-10-06 10:11:56 +0000491 This function wraps the Win32 :c:func:`GetVersionEx` function; see the
492 Microsoft documentation on :c:func:`OSVERSIONINFOEX` for more information
Eric Smithf7bb5782010-01-27 00:44:57 +0000493 about these fields.
Georg Brandl116aa622007-08-15 14:28:22 +0000494
495 Availability: Windows.
496
Ezio Melotti83fc6dd2010-01-27 22:44:03 +0000497 .. versionchanged:: 3.2
Eric Smithf7bb5782010-01-27 00:44:57 +0000498 Changed to a named tuple and added *service_pack_minor*,
499 *service_pack_major*, *suite_mask*, and *product_type*.
Georg Brandl116aa622007-08-15 14:28:22 +0000500
Mark Dickinsondc787d22010-05-23 13:33:13 +0000501
502.. data:: hash_info
503
504 A structseq giving parameters of the numeric hash implementation. For
505 more details about hashing of numeric types, see :ref:`numeric-hash`.
506
507 +---------------------+--------------------------------------------------+
508 | attribute | explanation |
509 +=====================+==================================================+
510 | :const:`width` | width in bits used for hash values |
511 +---------------------+--------------------------------------------------+
512 | :const:`modulus` | prime modulus P used for numeric hash scheme |
513 +---------------------+--------------------------------------------------+
514 | :const:`inf` | hash value returned for a positive infinity |
515 +---------------------+--------------------------------------------------+
516 | :const:`nan` | hash value returned for a nan |
517 +---------------------+--------------------------------------------------+
518 | :const:`imag` | multiplier used for the imaginary part of a |
519 | | complex number |
520 +---------------------+--------------------------------------------------+
521
522 .. versionadded:: 3.2
523
524
Georg Brandl116aa622007-08-15 14:28:22 +0000525.. data:: hexversion
526
527 The version number encoded as a single integer. This is guaranteed to increase
528 with each version, including proper support for non-production releases. For
529 example, to test that the Python interpreter is at least version 1.5.2, use::
530
531 if sys.hexversion >= 0x010502F0:
532 # use some advanced feature
533 ...
534 else:
535 # use an alternative implementation or warn the user
536 ...
537
538 This is called ``hexversion`` since it only really looks meaningful when viewed
539 as the result of passing it to the built-in :func:`hex` function. The
Éric Araujo10f3d7a2011-04-27 16:22:32 +0200540 struct sequence :data:`sys.version_info` may be used for a more human-friendly
541 encoding of the same information.
Georg Brandl116aa622007-08-15 14:28:22 +0000542
R David Murray9beb34e2011-04-30 16:35:29 -0400543 The ``hexversion`` is a 32-bit number with the following layout:
R David Murray2043f9c2011-04-25 16:12:26 -0400544
545 +-------------------------+------------------------------------------------+
R David Murray9beb34e2011-04-30 16:35:29 -0400546 | Bits (big endian order) | Meaning |
R David Murray2043f9c2011-04-25 16:12:26 -0400547 +=========================+================================================+
548 | :const:`1-8` | ``PY_MAJOR_VERSION`` (the ``2`` in |
549 | | ``2.1.0a3``) |
550 +-------------------------+------------------------------------------------+
551 | :const:`9-16` | ``PY_MINOR_VERSION`` (the ``1`` in |
552 | | ``2.1.0a3``) |
553 +-------------------------+------------------------------------------------+
554 | :const:`17-24` | ``PY_MICRO_VERSION`` (the ``0`` in |
555 | | ``2.1.0a3``) |
556 +-------------------------+------------------------------------------------+
557 | :const:`25-28` | ``PY_RELEASE_LEVEL`` (``0xA`` for alpha, |
R David Murray9beb34e2011-04-30 16:35:29 -0400558 | | ``0xB`` for beta, ``0xC`` for release |
559 | | candidate and ``0xF`` for final) |
R David Murray2043f9c2011-04-25 16:12:26 -0400560 +-------------------------+------------------------------------------------+
561 | :const:`29-32` | ``PY_RELEASE_SERIAL`` (the ``3`` in |
R David Murray9beb34e2011-04-30 16:35:29 -0400562 | | ``2.1.0a3``, zero for final releases) |
R David Murray2043f9c2011-04-25 16:12:26 -0400563 +-------------------------+------------------------------------------------+
564
R David Murray9beb34e2011-04-30 16:35:29 -0400565 Thus ``2.1.0a3`` is hexversion ``0x020100a3``.
Georg Brandl116aa622007-08-15 14:28:22 +0000566
Mark Dickinsonbd792642009-03-18 20:06:12 +0000567.. data:: int_info
568
569 A struct sequence that holds information about Python's
570 internal representation of integers. The attributes are read only.
571
572 +-------------------------+----------------------------------------------+
R David Murray9beb34e2011-04-30 16:35:29 -0400573 | Attribute | Explanation |
Mark Dickinsonbd792642009-03-18 20:06:12 +0000574 +=========================+==============================================+
575 | :const:`bits_per_digit` | number of bits held in each digit. Python |
576 | | integers are stored internally in base |
577 | | ``2**int_info.bits_per_digit`` |
578 +-------------------------+----------------------------------------------+
579 | :const:`sizeof_digit` | size in bytes of the C type used to |
580 | | represent a digit |
581 +-------------------------+----------------------------------------------+
582
Mark Dickinsond72c7b62009-03-20 16:00:49 +0000583 .. versionadded:: 3.1
584
Mark Dickinsonbd792642009-03-18 20:06:12 +0000585
Georg Brandl116aa622007-08-15 14:28:22 +0000586.. function:: intern(string)
587
588 Enter *string* in the table of "interned" strings and return the interned string
589 -- which is *string* itself or a copy. Interning strings is useful to gain a
590 little performance on dictionary lookup -- if the keys in a dictionary are
591 interned, and the lookup key is interned, the key comparisons (after hashing)
592 can be done by a pointer compare instead of a string compare. Normally, the
593 names used in Python programs are automatically interned, and the dictionaries
594 used to hold module, class or instance attributes have interned keys.
595
Georg Brandl55ac8f02007-09-01 13:51:09 +0000596 Interned strings are not immortal; you must keep a reference to the return
597 value of :func:`intern` around to benefit from it.
Georg Brandl116aa622007-08-15 14:28:22 +0000598
599
600.. data:: last_type
601 last_value
602 last_traceback
603
604 These three variables are not always defined; they are set when an exception is
605 not handled and the interpreter prints an error message and a stack traceback.
606 Their intended use is to allow an interactive user to import a debugger module
607 and engage in post-mortem debugging without having to re-execute the command
608 that caused the error. (Typical use is ``import pdb; pdb.pm()`` to enter the
Alexander Belopolskyf0a0d142010-10-27 03:06:43 +0000609 post-mortem debugger; see :mod:`pdb` module for
Georg Brandl116aa622007-08-15 14:28:22 +0000610 more information.)
611
612 The meaning of the variables is the same as that of the return values from
Georg Brandl482b1512010-03-21 09:02:59 +0000613 :func:`exc_info` above.
Georg Brandl116aa622007-08-15 14:28:22 +0000614
615
Christian Heimesa37d4c62007-12-04 23:02:19 +0000616.. data:: maxsize
Georg Brandl116aa622007-08-15 14:28:22 +0000617
Georg Brandl60203b42010-10-06 10:11:56 +0000618 An integer giving the maximum value a variable of type :c:type:`Py_ssize_t` can
Georg Brandl33770552007-12-15 09:55:35 +0000619 take. It's usually ``2**31 - 1`` on a 32-bit platform and ``2**63 - 1`` on a
620 64-bit platform.
Christian Heimesa37d4c62007-12-04 23:02:19 +0000621
Georg Brandl116aa622007-08-15 14:28:22 +0000622
623.. data:: maxunicode
624
625 An integer giving the largest supported code point for a Unicode character. The
626 value of this depends on the configuration option that specifies whether Unicode
627 characters are stored as UCS-2 or UCS-4.
628
629
Brett Cannone43b0602009-03-21 03:11:16 +0000630.. data:: meta_path
631
632 A list of :term:`finder` objects that have their :meth:`find_module`
633 methods called to see if one of the objects can find the module to be
634 imported. The :meth:`find_module` method is called at least with the
635 absolute name of the module being imported. If the module to be imported is
636 contained in package then the parent package's :attr:`__path__` attribute
Georg Brandl375aec22011-01-15 17:03:02 +0000637 is passed in as a second argument. The method returns ``None`` if
Brett Cannone43b0602009-03-21 03:11:16 +0000638 the module cannot be found, else returns a :term:`loader`.
639
640 :data:`sys.meta_path` is searched before any implicit default finders or
641 :data:`sys.path`.
642
643 See :pep:`302` for the original specification.
644
645
Georg Brandl116aa622007-08-15 14:28:22 +0000646.. data:: modules
647
648 This is a dictionary that maps module names to modules which have already been
649 loaded. This can be manipulated to force reloading of modules and other tricks.
650
651
652.. data:: path
653
654 .. index:: triple: module; search; path
655
656 A list of strings that specifies the search path for modules. Initialized from
657 the environment variable :envvar:`PYTHONPATH`, plus an installation-dependent
658 default.
659
660 As initialized upon program startup, the first item of this list, ``path[0]``,
661 is the directory containing the script that was used to invoke the Python
662 interpreter. If the script directory is not available (e.g. if the interpreter
663 is invoked interactively or if the script is read from standard input),
664 ``path[0]`` is the empty string, which directs Python to search modules in the
665 current directory first. Notice that the script directory is inserted *before*
666 the entries inserted as a result of :envvar:`PYTHONPATH`.
667
668 A program is free to modify this list for its own purposes.
669
Georg Brandl116aa622007-08-15 14:28:22 +0000670
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000671 .. seealso::
672 Module :mod:`site` This describes how to use .pth files to extend
673 :data:`sys.path`.
674
675
Brett Cannone43b0602009-03-21 03:11:16 +0000676.. data:: path_hooks
677
678 A list of callables that take a path argument to try to create a
679 :term:`finder` for the path. If a finder can be created, it is to be
680 returned by the callable, else raise :exc:`ImportError`.
681
682 Originally specified in :pep:`302`.
683
684
685.. data:: path_importer_cache
686
687 A dictionary acting as a cache for :term:`finder` objects. The keys are
688 paths that have been passed to :data:`sys.path_hooks` and the values are
689 the finders that are found. If a path is a valid file system path but no
Georg Brandl375aec22011-01-15 17:03:02 +0000690 explicit finder is found on :data:`sys.path_hooks` then ``None`` is
Brett Cannone43b0602009-03-21 03:11:16 +0000691 stored to represent the implicit default finder should be used. If the path
692 is not an existing path then :class:`imp.NullImporter` is set.
693
694 Originally specified in :pep:`302`.
695
696
Georg Brandl116aa622007-08-15 14:28:22 +0000697.. data:: platform
698
Christian Heimes9bd667a2008-01-20 15:14:11 +0000699 This string contains a platform identifier that can be used to append
700 platform-specific components to :data:`sys.path`, for instance.
701
Georg Brandla47e53e2011-09-03 09:26:09 +0200702 For most Unix systems, this is the lowercased OS name as returned by ``uname
703 -s`` with the first part of the version as returned by ``uname -r`` appended,
704 e.g. ``'sunos5'``, *at the time when Python was built*. Unless you want to
705 test for a specific system version, it is therefore recommended to use the
706 following idiom::
Antoine Pitroua83cdaa2011-07-09 15:54:23 +0200707
Georg Brandla47e53e2011-09-03 09:26:09 +0200708 if sys.platform.startswith('freebsd'):
709 # FreeBSD-specific code here...
710 elif sys.platform.startswith('linux'):
Antoine Pitroua83cdaa2011-07-09 15:54:23 +0200711 # Linux-specific code here...
712
Georg Brandla47e53e2011-09-03 09:26:09 +0200713 .. versionchanged:: 3.2.2
714 Since lots of code check for ``sys.platform == 'linux2'``, and there is
715 no essential change between Linux 2.x and 3.x, ``sys.platform`` is always
716 set to ``'linux2'``, even on Linux 3.x. In Python 3.3 and later, the
717 value will always be set to ``'linux'``, so it is recommended to always
718 use the ``startswith`` idiom presented above.
719
Christian Heimes9bd667a2008-01-20 15:14:11 +0000720 For other systems, the values are:
721
Georg Brandla47e53e2011-09-03 09:26:09 +0200722 ====================== ===========================
723 System :data:`platform` value
724 ====================== ===========================
725 Linux (2.x *and* 3.x) ``'linux2'``
726 Windows ``'win32'``
727 Windows/Cygwin ``'cygwin'``
728 Mac OS X ``'darwin'``
729 OS/2 ``'os2'``
730 OS/2 EMX ``'os2emx'``
731 ====================== ===========================
Georg Brandl116aa622007-08-15 14:28:22 +0000732
Antoine Pitroua83cdaa2011-07-09 15:54:23 +0200733 .. seealso::
734 :attr:`os.name` has a coarser granularity. :func:`os.uname` gives
735 system-dependent version information.
736
737 The :mod:`platform` module provides detailed checks for the
738 system's identity.
Georg Brandl116aa622007-08-15 14:28:22 +0000739
740.. data:: prefix
741
742 A string giving the site-specific directory prefix where the platform
743 independent Python files are installed; by default, this is the string
Éric Araujo713d3032010-11-18 16:38:46 +0000744 ``'/usr/local'``. This can be set at build time with the ``--prefix``
Georg Brandl116aa622007-08-15 14:28:22 +0000745 argument to the :program:`configure` script. The main collection of Python
746 library modules is installed in the directory ``prefix + '/lib/pythonversion'``
747 while the platform independent header files (all except :file:`pyconfig.h`) are
748 stored in ``prefix + '/include/pythonversion'``, where *version* is equal to
749 ``version[:3]``.
750
751
752.. data:: ps1
753 ps2
754
755 .. index::
756 single: interpreter prompts
757 single: prompts, interpreter
758
759 Strings specifying the primary and secondary prompt of the interpreter. These
760 are only defined if the interpreter is in interactive mode. Their initial
761 values in this case are ``'>>> '`` and ``'... '``. If a non-string object is
762 assigned to either variable, its :func:`str` is re-evaluated each time the
763 interpreter prepares to read a new interactive command; this can be used to
764 implement a dynamic prompt.
765
766
Christian Heimes790c8232008-01-07 21:14:23 +0000767.. data:: dont_write_bytecode
768
769 If this is true, Python won't try to write ``.pyc`` or ``.pyo`` files on the
770 import of source modules. This value is initially set to ``True`` or ``False``
771 depending on the ``-B`` command line option and the ``PYTHONDONTWRITEBYTECODE``
772 environment variable, but you can set it yourself to control bytecode file
773 generation.
774
Christian Heimes790c8232008-01-07 21:14:23 +0000775
Georg Brandl116aa622007-08-15 14:28:22 +0000776.. function:: setcheckinterval(interval)
777
778 Set the interpreter's "check interval". This integer value determines how often
779 the interpreter checks for periodic things such as thread switches and signal
780 handlers. The default is ``100``, meaning the check is performed every 100
781 Python virtual instructions. Setting it to a larger value may increase
782 performance for programs using threads. Setting it to a value ``<=`` 0 checks
783 every virtual instruction, maximizing responsiveness as well as overhead.
784
Antoine Pitroud42bc512009-11-10 23:18:31 +0000785 .. deprecated:: 3.2
Georg Brandl67b21b72010-08-17 15:07:14 +0000786 This function doesn't have an effect anymore, as the internal logic for
787 thread switching and asynchronous tasks has been rewritten. Use
788 :func:`setswitchinterval` instead.
Antoine Pitroud42bc512009-11-10 23:18:31 +0000789
Georg Brandl116aa622007-08-15 14:28:22 +0000790
Georg Brandl116aa622007-08-15 14:28:22 +0000791.. function:: setdlopenflags(n)
792
Georg Brandl60203b42010-10-06 10:11:56 +0000793 Set the flags used by the interpreter for :c:func:`dlopen` calls, such as when
Georg Brandl116aa622007-08-15 14:28:22 +0000794 the interpreter loads extension modules. Among other things, this will enable a
795 lazy resolving of symbols when importing a module, if called as
796 ``sys.setdlopenflags(0)``. To share symbols across extension modules, call as
Neal Norwitz6cf49cf2008-03-24 06:22:57 +0000797 ``sys.setdlopenflags(ctypes.RTLD_GLOBAL)``. Symbolic names for the
798 flag modules can be either found in the :mod:`ctypes` module, or in the :mod:`DLFCN`
Georg Brandl116aa622007-08-15 14:28:22 +0000799 module. If :mod:`DLFCN` is not available, it can be generated from
800 :file:`/usr/include/dlfcn.h` using the :program:`h2py` script. Availability:
801 Unix.
802
Georg Brandl116aa622007-08-15 14:28:22 +0000803.. function:: setprofile(profilefunc)
804
805 .. index::
806 single: profile function
807 single: profiler
808
809 Set the system's profile function, which allows you to implement a Python source
810 code profiler in Python. See chapter :ref:`profile` for more information on the
811 Python profiler. The system's profile function is called similarly to the
812 system's trace function (see :func:`settrace`), but it isn't called for each
813 executed line of code (only on call and return, but the return event is reported
814 even when an exception has been set). The function is thread-specific, but
815 there is no way for the profiler to know about context switches between threads,
816 so it does not make sense to use this in the presence of multiple threads. Also,
817 its return value is not used, so it can simply return ``None``.
818
819
820.. function:: setrecursionlimit(limit)
821
822 Set the maximum depth of the Python interpreter stack to *limit*. This limit
823 prevents infinite recursion from causing an overflow of the C stack and crashing
824 Python.
825
826 The highest possible limit is platform-dependent. A user may need to set the
Georg Brandl51663752011-05-13 06:55:28 +0200827 limit higher when they have a program that requires deep recursion and a platform
Georg Brandl116aa622007-08-15 14:28:22 +0000828 that supports a higher limit. This should be done with care, because a too-high
829 limit can lead to a crash.
830
831
Antoine Pitroud42bc512009-11-10 23:18:31 +0000832.. function:: setswitchinterval(interval)
833
834 Set the interpreter's thread switch interval (in seconds). This floating-point
835 value determines the ideal duration of the "timeslices" allocated to
836 concurrently running Python threads. Please note that the actual value
837 can be higher, especially if long-running internal functions or methods
838 are used. Also, which thread becomes scheduled at the end of the interval
839 is the operating system's decision. The interpreter doesn't have its
840 own scheduler.
841
Antoine Pitrou79707ca2009-11-11 22:03:32 +0000842 .. versionadded:: 3.2
843
Antoine Pitroud42bc512009-11-10 23:18:31 +0000844
Georg Brandl116aa622007-08-15 14:28:22 +0000845.. function:: settrace(tracefunc)
846
847 .. index::
848 single: trace function
849 single: debugger
850
851 Set the system's trace function, which allows you to implement a Python
Amaury Forgeot d'Arcb0c29162008-11-22 22:18:04 +0000852 source code debugger in Python. The function is thread-specific; for a
Georg Brandl116aa622007-08-15 14:28:22 +0000853 debugger to support multiple threads, it must be registered using
854 :func:`settrace` for each thread being debugged.
855
Amaury Forgeot d'Arcb0c29162008-11-22 22:18:04 +0000856 Trace functions should have three arguments: *frame*, *event*, and
857 *arg*. *frame* is the current stack frame. *event* is a string: ``'call'``,
858 ``'line'``, ``'return'``, ``'exception'``, ``'c_call'``, ``'c_return'``, or
859 ``'c_exception'``. *arg* depends on the event type.
860
861 The trace function is invoked (with *event* set to ``'call'``) whenever a new
862 local scope is entered; it should return a reference to a local trace
863 function to be used that scope, or ``None`` if the scope shouldn't be traced.
864
865 The local trace function should return a reference to itself (or to another
866 function for further tracing in that scope), or ``None`` to turn off tracing
867 in that scope.
868
869 The events have the following meaning:
870
Georg Brandl48310cd2009-01-03 21:18:54 +0000871 ``'call'``
Amaury Forgeot d'Arcb0c29162008-11-22 22:18:04 +0000872 A function is called (or some other code block entered). The
873 global trace function is called; *arg* is ``None``; the return value
874 specifies the local trace function.
875
876 ``'line'``
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000877 The interpreter is about to execute a new line of code or re-execute the
878 condition of a loop. The local trace function is called; *arg* is
879 ``None``; the return value specifies the new local trace function. See
880 :file:`Objects/lnotab_notes.txt` for a detailed explanation of how this
881 works.
Amaury Forgeot d'Arcb0c29162008-11-22 22:18:04 +0000882
883 ``'return'``
884 A function (or other code block) is about to return. The local trace
Georg Brandld0b0e1d2010-10-15 16:42:37 +0000885 function is called; *arg* is the value that will be returned, or ``None``
886 if the event is caused by an exception being raised. The trace function's
887 return value is ignored.
Amaury Forgeot d'Arcb0c29162008-11-22 22:18:04 +0000888
889 ``'exception'``
890 An exception has occurred. The local trace function is called; *arg* is a
891 tuple ``(exception, value, traceback)``; the return value specifies the
892 new local trace function.
893
894 ``'c_call'``
895 A C function is about to be called. This may be an extension function or
Georg Brandl22b34312009-07-26 14:54:51 +0000896 a built-in. *arg* is the C function object.
Amaury Forgeot d'Arcb0c29162008-11-22 22:18:04 +0000897
898 ``'c_return'``
Georg Brandld0b0e1d2010-10-15 16:42:37 +0000899 A C function has returned. *arg* is the C function object.
Amaury Forgeot d'Arcb0c29162008-11-22 22:18:04 +0000900
901 ``'c_exception'``
Georg Brandld0b0e1d2010-10-15 16:42:37 +0000902 A C function has raised an exception. *arg* is the C function object.
Amaury Forgeot d'Arcb0c29162008-11-22 22:18:04 +0000903
904 Note that as an exception is propagated down the chain of callers, an
905 ``'exception'`` event is generated at each level.
906
907 For more information on code and frame objects, refer to :ref:`types`.
908
Georg Brandl495f7b52009-10-27 15:28:25 +0000909 .. impl-detail::
Georg Brandl116aa622007-08-15 14:28:22 +0000910
911 The :func:`settrace` function is intended only for implementing debuggers,
Georg Brandl495f7b52009-10-27 15:28:25 +0000912 profilers, coverage tools and the like. Its behavior is part of the
913 implementation platform, rather than part of the language definition, and
914 thus may not be available in all Python implementations.
Georg Brandl116aa622007-08-15 14:28:22 +0000915
916
917.. function:: settscdump(on_flag)
918
919 Activate dumping of VM measurements using the Pentium timestamp counter, if
920 *on_flag* is true. Deactivate these dumps if *on_flag* is off. The function is
Éric Araujo713d3032010-11-18 16:38:46 +0000921 available only if Python was compiled with ``--with-tsc``. To understand
Georg Brandl116aa622007-08-15 14:28:22 +0000922 the output of this dump, read :file:`Python/ceval.c` in the Python sources.
923
Benjamin Peterson21896a32010-03-21 22:03:03 +0000924 .. impl-detail::
925 This function is intimately bound to CPython implementation details and
926 thus not likely to be implemented elsewhere.
927
Georg Brandl116aa622007-08-15 14:28:22 +0000928
929.. data:: stdin
930 stdout
931 stderr
932
Antoine Pitrou11cb9612010-09-15 11:11:28 +0000933 :term:`File objects <file object>` corresponding to the interpreter's standard
934 input, output and error streams. ``stdin`` is used for all interpreter input
935 except for scripts but including calls to :func:`input`. ``stdout`` is used
936 for the output of :func:`print` and :term:`expression` statements and for the
Christian Heimesd8654cf2007-12-02 15:22:16 +0000937 prompts of :func:`input`. The interpreter's own prompts
938 and (almost all of) its error messages go to ``stderr``. ``stdout`` and
939 ``stderr`` needn't be built-in file objects: any object is acceptable as long
Georg Brandl48310cd2009-01-03 21:18:54 +0000940 as it has a :meth:`write` method that takes a string argument. (Changing these
Christian Heimesd8654cf2007-12-02 15:22:16 +0000941 objects doesn't affect the standard I/O streams of processes executed by
942 :func:`os.popen`, :func:`os.system` or the :func:`exec\*` family of functions in
943 the :mod:`os` module.)
Georg Brandl116aa622007-08-15 14:28:22 +0000944
Benjamin Peterson3261fa52009-05-12 03:01:51 +0000945 The standard streams are in text mode by default. To write or read binary
946 data to these, use the underlying binary buffer. For example, to write bytes
947 to :data:`stdout`, use ``sys.stdout.buffer.write(b'abc')``. Using
Benjamin Peterson995bb472009-06-14 18:41:18 +0000948 :meth:`io.TextIOBase.detach` streams can be made binary by default. This
949 function sets :data:`stdin` and :data:`stdout` to binary::
Benjamin Peterson4199d602009-05-12 20:47:57 +0000950
951 def make_streams_binary():
952 sys.stdin = sys.stdin.detach()
Benjamin Peterson4487f532009-05-13 21:15:03 +0000953 sys.stdout = sys.stdout.detach()
Benjamin Peterson995bb472009-06-14 18:41:18 +0000954
955 Note that the streams can be replaced with objects (like
956 :class:`io.StringIO`) that do not support the
957 :attr:`~io.BufferedIOBase.buffer` attribute or the
958 :meth:`~io.BufferedIOBase.detach` method and can raise :exc:`AttributeError`
959 or :exc:`io.UnsupportedOperation`.
Benjamin Petersoneb9fc522008-12-07 14:58:03 +0000960
Georg Brandl116aa622007-08-15 14:28:22 +0000961
962.. data:: __stdin__
963 __stdout__
964 __stderr__
965
966 These objects contain the original values of ``stdin``, ``stderr`` and
Benjamin Petersond23f8222009-04-05 19:13:16 +0000967 ``stdout`` at the start of the program. They are used during finalization,
968 and could be useful to print to the actual standard stream no matter if the
969 ``sys.std*`` object has been redirected.
Georg Brandl116aa622007-08-15 14:28:22 +0000970
Benjamin Petersond23f8222009-04-05 19:13:16 +0000971 It can also be used to restore the actual files to known working file objects
972 in case they have been overwritten with a broken object. However, the
973 preferred way to do this is to explicitly save the previous stream before
974 replacing it, and restore the saved object.
Christian Heimes58cb1b82007-11-13 02:19:40 +0000975
Benjamin Petersond23f8222009-04-05 19:13:16 +0000976 .. note::
977 Under some conditions ``stdin``, ``stdout`` and ``stderr`` as well as the
978 original values ``__stdin__``, ``__stdout__`` and ``__stderr__`` can be
979 None. It is usually the case for Windows GUI apps that aren't connected
980 to a console and Python apps started with :program:`pythonw`.
Christian Heimes58cb1b82007-11-13 02:19:40 +0000981
Georg Brandl116aa622007-08-15 14:28:22 +0000982
Antoine Pitrou462d1b32011-07-09 16:02:19 +0200983.. data:: subversion
984
985 A triple (repo, branch, version) representing the Subversion information of the
986 Python interpreter. *repo* is the name of the repository, ``'CPython'``.
987 *branch* is a string of one of the forms ``'trunk'``, ``'branches/name'`` or
988 ``'tags/name'``. *version* is the output of ``svnversion``, if the interpreter
989 was built from a Subversion checkout; it contains the revision number (range)
990 and possibly a trailing 'M' if there were local modifications. If the tree was
991 exported (or svnversion was not available), it is the revision of
992 ``Include/patchlevel.h`` if the branch is a tag. Otherwise, it is ``None``.
993
994 .. deprecated:: 3.2.1
995 Python is now `developed <http://docs.python.org/devguide/>`_ using
996 Mercurial. In recent Python 3.2 bugfix releases, :data:`subversion`
997 therefore contains placeholder information. It is removed in Python
998 3.3.
999
1000
Georg Brandl116aa622007-08-15 14:28:22 +00001001.. data:: tracebacklimit
1002
1003 When this variable is set to an integer value, it determines the maximum number
1004 of levels of traceback information printed when an unhandled exception occurs.
1005 The default is ``1000``. When set to ``0`` or less, all traceback information
1006 is suppressed and only the exception type and value are printed.
1007
1008
1009.. data:: version
1010
1011 A string containing the version number of the Python interpreter plus additional
Georg Brandle42a59d2010-07-31 20:05:31 +00001012 information on the build number and compiler used. This string is displayed
1013 when the interactive interpreter is started. Do not extract version information
1014 out of it, rather, use :data:`version_info` and the functions provided by the
1015 :mod:`platform` module.
Georg Brandl116aa622007-08-15 14:28:22 +00001016
1017
1018.. data:: api_version
1019
1020 The C API version for this interpreter. Programmers may find this useful when
1021 debugging version conflicts between Python and extension modules.
1022
Georg Brandl116aa622007-08-15 14:28:22 +00001023
1024.. data:: version_info
1025
1026 A tuple containing the five components of the version number: *major*, *minor*,
1027 *micro*, *releaselevel*, and *serial*. All values except *releaselevel* are
1028 integers; the release level is ``'alpha'``, ``'beta'``, ``'candidate'``, or
1029 ``'final'``. The ``version_info`` value corresponding to the Python version 2.0
Eric Smith0e5b5622009-02-06 01:32:42 +00001030 is ``(2, 0, 0, 'final', 0)``. The components can also be accessed by name,
1031 so ``sys.version_info[0]`` is equivalent to ``sys.version_info.major``
1032 and so on.
Georg Brandl116aa622007-08-15 14:28:22 +00001033
Raymond Hettinger35a88362009-04-09 00:08:24 +00001034 .. versionchanged:: 3.1
Georg Brandl67b21b72010-08-17 15:07:14 +00001035 Added named component attributes.
Georg Brandl116aa622007-08-15 14:28:22 +00001036
1037.. data:: warnoptions
1038
1039 This is an implementation detail of the warnings framework; do not modify this
1040 value. Refer to the :mod:`warnings` module for more information on the warnings
1041 framework.
1042
1043
1044.. data:: winver
1045
1046 The version number used to form registry keys on Windows platforms. This is
1047 stored as string resource 1000 in the Python DLL. The value is normally the
1048 first three characters of :const:`version`. It is provided in the :mod:`sys`
1049 module for informational purposes; modifying this value has no effect on the
1050 registry keys used by Python. Availability: Windows.
Mark Dickinsonbe5846b2010-07-02 20:26:07 +00001051
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001052
1053.. data:: _xoptions
1054
1055 A dictionary of the various implementation-specific flags passed through
1056 the :option:`-X` command-line option. Option names are either mapped to
1057 their values, if given explicitly, or to :const:`True`. Example::
1058
1059 $ ./python -Xa=b -Xc
1060 Python 3.2a3+ (py3k, Oct 16 2010, 20:14:50)
1061 [GCC 4.4.3] on linux2
1062 Type "help", "copyright", "credits" or "license" for more information.
1063 >>> import sys
1064 >>> sys._xoptions
1065 {'a': 'b', 'c': True}
1066
1067 .. impl-detail::
1068
1069 This is a CPython-specific way of accessing options passed through
1070 :option:`-X`. Other implementations may export them through other
1071 means, or not at all.
1072
1073 .. versionadded:: 3.2
1074
1075
Mark Dickinsonbe5846b2010-07-02 20:26:07 +00001076.. rubric:: Citations
1077
1078.. [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 .
1079