blob: f7a0a5dbe0358ac26142a6c1f6b0ccd72cf21b64 [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 Melottid7729332009-12-25 02:13:25 +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 Melottid7729332009-12-25 02:13:25 +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 Dickinson64f91282010-07-02 20:24:32 +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 Dickinson64f91282010-07-02 20:24:32 +0000305 +---------------------+----------------+--------------------------------------------------+
306 | attribute | float.h macro | explanation |
307 +=====================+================+==================================================+
Mark Dickinson6e079312010-07-03 09:16:01 +0000308 | :const:`epsilon` | DBL_EPSILON | difference between 1 and the least value greater |
Mark Dickinson64f91282010-07-02 20:24:32 +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 Dickinson64f91282010-07-02 20:24:32 +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 Dickinson64f91282010-07-02 20:24:32 +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
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000361
Georg Brandl8ec7f652007-08-15 14:28:01 +0000362.. function:: getcheckinterval()
363
364 Return the interpreter's "check interval"; see :func:`setcheckinterval`.
365
366 .. versionadded:: 2.3
367
368
369.. function:: getdefaultencoding()
370
371 Return the name of the current default string encoding used by the Unicode
372 implementation.
373
374 .. versionadded:: 2.0
375
376
377.. function:: getdlopenflags()
378
379 Return the current value of the flags that are used for :cfunc:`dlopen` calls.
380 The flag constants are defined in the :mod:`dl` and :mod:`DLFCN` modules.
381 Availability: Unix.
382
383 .. versionadded:: 2.2
384
385
386.. function:: getfilesystemencoding()
387
388 Return the name of the encoding used to convert Unicode filenames into system
389 file names, or ``None`` if the system default encoding is used. The result value
390 depends on the operating system:
391
Ezio Melotti9c061292010-04-29 16:21:53 +0000392 * On Mac OS X, the encoding is ``'utf-8'``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000393
394 * On Unix, the encoding is the user's preference according to the result of
Ezio Melotti9c061292010-04-29 16:21:53 +0000395 nl_langinfo(CODESET), or ``None`` if the ``nl_langinfo(CODESET)``
396 failed.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000397
398 * On Windows NT+, file names are Unicode natively, so no conversion is
Ezio Melotti9c061292010-04-29 16:21:53 +0000399 performed. :func:`getfilesystemencoding` still returns ``'mbcs'``, as
400 this is the encoding that applications should use when they explicitly
401 want to convert Unicode strings to byte strings that are equivalent when
402 used as file names.
403
404 * On Windows 9x, the encoding is ``'mbcs'``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000405
406 .. versionadded:: 2.3
407
408
409.. function:: getrefcount(object)
410
411 Return the reference count of the *object*. The count returned is generally one
412 higher than you might expect, because it includes the (temporary) reference as
413 an argument to :func:`getrefcount`.
414
415
416.. function:: getrecursionlimit()
417
418 Return the current value of the recursion limit, the maximum depth of the Python
419 interpreter stack. This limit prevents infinite recursion from causing an
420 overflow of the C stack and crashing Python. It can be set by
421 :func:`setrecursionlimit`.
422
423
Robert Schuppenies47629022008-07-10 17:13:55 +0000424.. function:: getsizeof(object[, default])
Robert Schuppenies51df0642008-06-01 16:16:17 +0000425
426 Return the size of an object in bytes. The object can be any type of
427 object. All built-in objects will return correct results, but this
Robert Schuppenies47629022008-07-10 17:13:55 +0000428 does not have to hold true for third-party extensions as it is implementation
Robert Schuppenies51df0642008-06-01 16:16:17 +0000429 specific.
430
Benjamin Peterson751c2032009-09-22 22:30:03 +0000431 If given, *default* will be returned if the object does not provide means to
Georg Brandl4c86cb32010-03-21 19:34:26 +0000432 retrieve the size. Otherwise a :exc:`TypeError` will be raised.
Robert Schuppenies47629022008-07-10 17:13:55 +0000433
Benjamin Peterson751c2032009-09-22 22:30:03 +0000434 :func:`getsizeof` calls the object's ``__sizeof__`` method and adds an
435 additional garbage collector overhead if the object is managed by the garbage
436 collector.
Robert Schuppenies47629022008-07-10 17:13:55 +0000437
Robert Schuppenies51df0642008-06-01 16:16:17 +0000438 .. versionadded:: 2.6
439
440
Georg Brandl8ec7f652007-08-15 14:28:01 +0000441.. function:: _getframe([depth])
442
443 Return a frame object from the call stack. If optional integer *depth* is
444 given, return the frame object that many calls below the top of the stack. If
445 that is deeper than the call stack, :exc:`ValueError` is raised. The default
446 for *depth* is zero, returning the frame at the top of the call stack.
447
Georg Brandl5d2eb342009-10-27 15:08:27 +0000448 .. impl-detail::
449
450 This function should be used for internal and specialized purposes only.
451 It is not guaranteed to exist in all implementations of Python.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000452
453
Georg Brandl56112892008-01-20 13:59:46 +0000454.. function:: getprofile()
455
456 .. index::
457 single: profile function
458 single: profiler
459
460 Get the profiler function as set by :func:`setprofile`.
461
462 .. versionadded:: 2.6
463
464
465.. function:: gettrace()
466
467 .. index::
468 single: trace function
469 single: debugger
470
471 Get the trace function as set by :func:`settrace`.
472
Georg Brandl5d2eb342009-10-27 15:08:27 +0000473 .. impl-detail::
Georg Brandl56112892008-01-20 13:59:46 +0000474
475 The :func:`gettrace` function is intended only for implementing debuggers,
Georg Brandl5d2eb342009-10-27 15:08:27 +0000476 profilers, coverage tools and the like. Its behavior is part of the
477 implementation platform, rather than part of the language definition, and
478 thus may not be available in all Python implementations.
Georg Brandl56112892008-01-20 13:59:46 +0000479
480 .. versionadded:: 2.6
481
482
Georg Brandl8ec7f652007-08-15 14:28:01 +0000483.. function:: getwindowsversion()
484
485 Return a tuple containing five components, describing the Windows version
486 currently running. The elements are *major*, *minor*, *build*, *platform*, and
487 *text*. *text* contains a string while all other values are integers.
488
489 *platform* may be one of the following values:
490
Jeroen Ruigrok van der Wervenaa3cadb2008-04-21 20:15:39 +0000491 +-----------------------------------------+-------------------------+
492 | Constant | Platform |
493 +=========================================+=========================+
494 | :const:`0 (VER_PLATFORM_WIN32s)` | Win32s on Windows 3.1 |
495 +-----------------------------------------+-------------------------+
496 | :const:`1 (VER_PLATFORM_WIN32_WINDOWS)` | Windows 95/98/ME |
497 +-----------------------------------------+-------------------------+
498 | :const:`2 (VER_PLATFORM_WIN32_NT)` | Windows NT/2000/XP/x64 |
499 +-----------------------------------------+-------------------------+
500 | :const:`3 (VER_PLATFORM_WIN32_CE)` | Windows CE |
501 +-----------------------------------------+-------------------------+
Georg Brandl8ec7f652007-08-15 14:28:01 +0000502
503 This function wraps the Win32 :cfunc:`GetVersionEx` function; see the Microsoft
504 documentation for more information about these fields.
505
506 Availability: Windows.
507
508 .. versionadded:: 2.3
509
510
511.. data:: hexversion
512
513 The version number encoded as a single integer. This is guaranteed to increase
514 with each version, including proper support for non-production releases. For
515 example, to test that the Python interpreter is at least version 1.5.2, use::
516
517 if sys.hexversion >= 0x010502F0:
518 # use some advanced feature
519 ...
520 else:
521 # use an alternative implementation or warn the user
522 ...
523
524 This is called ``hexversion`` since it only really looks meaningful when viewed
525 as the result of passing it to the built-in :func:`hex` function. The
526 ``version_info`` value may be used for a more human-friendly encoding of the
527 same information.
528
529 .. versionadded:: 1.5.2
530
531
532.. data:: last_type
533 last_value
534 last_traceback
535
536 These three variables are not always defined; they are set when an exception is
537 not handled and the interpreter prints an error message and a stack traceback.
538 Their intended use is to allow an interactive user to import a debugger module
539 and engage in post-mortem debugging without having to re-execute the command
540 that caused the error. (Typical use is ``import pdb; pdb.pm()`` to enter the
541 post-mortem debugger; see chapter :ref:`debugger` for
542 more information.)
543
544 The meaning of the variables is the same as that of the return values from
545 :func:`exc_info` above. (Since there is only one interactive thread,
546 thread-safety is not a concern for these variables, unlike for ``exc_type``
547 etc.)
548
549
550.. data:: maxint
551
552 The largest positive integer supported by Python's regular integer type. This
553 is at least 2\*\*31-1. The largest negative integer is ``-maxint-1`` --- the
554 asymmetry results from the use of 2's complement binary arithmetic.
555
Martin v. Löwis4dd019f2008-05-20 08:11:19 +0000556.. data:: maxsize
557
558 The largest positive integer supported by the platform's Py_ssize_t type,
559 and thus the maximum size lists, strings, dicts, and many other containers
560 can have.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000561
562.. data:: maxunicode
563
564 An integer giving the largest supported code point for a Unicode character. The
565 value of this depends on the configuration option that specifies whether Unicode
566 characters are stored as UCS-2 or UCS-4.
567
568
Georg Brandl8943caf2009-04-05 21:11:43 +0000569.. data:: meta_path
570
571 A list of :term:`finder` objects that have their :meth:`find_module`
572 methods called to see if one of the objects can find the module to be
573 imported. The :meth:`find_module` method is called at least with the
574 absolute name of the module being imported. If the module to be imported is
575 contained in package then the parent package's :attr:`__path__` attribute
576 is passed in as a second argument. The method returns :keyword:`None` if
577 the module cannot be found, else returns a :term:`loader`.
578
579 :data:`sys.meta_path` is searched before any implicit default finders or
580 :data:`sys.path`.
581
582 See :pep:`302` for the original specification.
583
584
Georg Brandl8ec7f652007-08-15 14:28:01 +0000585.. data:: modules
586
587 .. index:: builtin: reload
588
589 This is a dictionary that maps module names to modules which have already been
590 loaded. This can be manipulated to force reloading of modules and other tricks.
591 Note that removing a module from this dictionary is *not* the same as calling
592 :func:`reload` on the corresponding module object.
593
594
595.. data:: path
596
597 .. index:: triple: module; search; path
598
599 A list of strings that specifies the search path for modules. Initialized from
600 the environment variable :envvar:`PYTHONPATH`, plus an installation-dependent
601 default.
602
603 As initialized upon program startup, the first item of this list, ``path[0]``,
604 is the directory containing the script that was used to invoke the Python
605 interpreter. If the script directory is not available (e.g. if the interpreter
606 is invoked interactively or if the script is read from standard input),
607 ``path[0]`` is the empty string, which directs Python to search modules in the
608 current directory first. Notice that the script directory is inserted *before*
609 the entries inserted as a result of :envvar:`PYTHONPATH`.
610
611 A program is free to modify this list for its own purposes.
612
613 .. versionchanged:: 2.3
614 Unicode strings are no longer ignored.
615
Georg Brandlc04c2892009-01-14 00:00:17 +0000616 .. seealso::
617 Module :mod:`site` This describes how to use .pth files to extend
618 :data:`sys.path`.
619
Georg Brandl8ec7f652007-08-15 14:28:01 +0000620
Georg Brandl8943caf2009-04-05 21:11:43 +0000621.. data:: path_hooks
622
623 A list of callables that take a path argument to try to create a
624 :term:`finder` for the path. If a finder can be created, it is to be
625 returned by the callable, else raise :exc:`ImportError`.
626
627 Originally specified in :pep:`302`.
628
629
630.. data:: path_importer_cache
631
632 A dictionary acting as a cache for :term:`finder` objects. The keys are
633 paths that have been passed to :data:`sys.path_hooks` and the values are
634 the finders that are found. If a path is a valid file system path but no
635 explicit finder is found on :data:`sys.path_hooks` then :keyword:`None` is
636 stored to represent the implicit default finder should be used. If the path
637 is not an existing path then :class:`imp.NullImporter` is set.
638
639 Originally specified in :pep:`302`.
640
641
Georg Brandl8ec7f652007-08-15 14:28:01 +0000642.. data:: platform
643
Georg Brandl440f2ff2008-01-20 12:57:47 +0000644 This string contains a platform identifier that can be used to append
645 platform-specific components to :data:`sys.path`, for instance.
646
647 For Unix systems, this is the lowercased OS name as returned by ``uname -s``
648 with the first part of the version as returned by ``uname -r`` appended,
649 e.g. ``'sunos5'`` or ``'linux2'``, *at the time when Python was built*.
650 For other systems, the values are:
651
652 ================ ===========================
653 System :data:`platform` value
654 ================ ===========================
655 Windows ``'win32'``
656 Windows/Cygwin ``'cygwin'``
Georg Brandl9af94982008-09-13 17:41:16 +0000657 Mac OS X ``'darwin'``
Georg Brandl440f2ff2008-01-20 12:57:47 +0000658 OS/2 ``'os2'``
659 OS/2 EMX ``'os2emx'``
660 RiscOS ``'riscos'``
661 AtheOS ``'atheos'``
662 ================ ===========================
Georg Brandl8ec7f652007-08-15 14:28:01 +0000663
664
665.. data:: prefix
666
667 A string giving the site-specific directory prefix where the platform
668 independent Python files are installed; by default, this is the string
669 ``'/usr/local'``. This can be set at build time with the :option:`--prefix`
670 argument to the :program:`configure` script. The main collection of Python
671 library modules is installed in the directory ``prefix + '/lib/pythonversion'``
672 while the platform independent header files (all except :file:`pyconfig.h`) are
673 stored in ``prefix + '/include/pythonversion'``, where *version* is equal to
674 ``version[:3]``.
675
676
677.. data:: ps1
678 ps2
679
680 .. index::
681 single: interpreter prompts
682 single: prompts, interpreter
683
684 Strings specifying the primary and secondary prompt of the interpreter. These
685 are only defined if the interpreter is in interactive mode. Their initial
686 values in this case are ``'>>> '`` and ``'... '``. If a non-string object is
687 assigned to either variable, its :func:`str` is re-evaluated each time the
688 interpreter prepares to read a new interactive command; this can be used to
689 implement a dynamic prompt.
690
691
Christian Heimesd7b33372007-11-28 08:02:36 +0000692.. data:: py3kwarning
693
694 Bool containing the status of the Python 3.0 warning flag. It's ``True``
Georg Brandl40e15ed2009-04-05 21:48:06 +0000695 when Python is started with the -3 option. (This should be considered
696 read-only; setting it to a different value doesn't have an effect on
697 Python 3.0 warnings.)
Christian Heimesd7b33372007-11-28 08:02:36 +0000698
Georg Brandl5f794462008-03-21 21:05:03 +0000699 .. versionadded:: 2.6
700
Christian Heimesd7b33372007-11-28 08:02:36 +0000701
Georg Brandl2da0fce2008-01-07 17:09:35 +0000702.. data:: dont_write_bytecode
703
704 If this is true, Python won't try to write ``.pyc`` or ``.pyo`` files on the
705 import of source modules. This value is initially set to ``True`` or ``False``
706 depending on the ``-B`` command line option and the ``PYTHONDONTWRITEBYTECODE``
707 environment variable, but you can set it yourself to control bytecode file
708 generation.
709
710 .. versionadded:: 2.6
711
712
Georg Brandl8ec7f652007-08-15 14:28:01 +0000713.. function:: setcheckinterval(interval)
714
715 Set the interpreter's "check interval". This integer value determines how often
716 the interpreter checks for periodic things such as thread switches and signal
717 handlers. The default is ``100``, meaning the check is performed every 100
718 Python virtual instructions. Setting it to a larger value may increase
719 performance for programs using threads. Setting it to a value ``<=`` 0 checks
720 every virtual instruction, maximizing responsiveness as well as overhead.
721
722
723.. function:: setdefaultencoding(name)
724
725 Set the current default string encoding used by the Unicode implementation. If
726 *name* does not match any available encoding, :exc:`LookupError` is raised.
727 This function is only intended to be used by the :mod:`site` module
728 implementation and, where needed, by :mod:`sitecustomize`. Once used by the
729 :mod:`site` module, it is removed from the :mod:`sys` module's namespace.
730
Georg Brandlb19be572007-12-29 10:57:00 +0000731 .. Note that :mod:`site` is not imported if the :option:`-S` option is passed
732 to the interpreter, in which case this function will remain available.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000733
734 .. versionadded:: 2.0
735
736
737.. function:: setdlopenflags(n)
738
739 Set the flags used by the interpreter for :cfunc:`dlopen` calls, such as when
740 the interpreter loads extension modules. Among other things, this will enable a
741 lazy resolving of symbols when importing a module, if called as
742 ``sys.setdlopenflags(0)``. To share symbols across extension modules, call as
743 ``sys.setdlopenflags(dl.RTLD_NOW | dl.RTLD_GLOBAL)``. Symbolic names for the
744 flag modules can be either found in the :mod:`dl` module, or in the :mod:`DLFCN`
745 module. If :mod:`DLFCN` is not available, it can be generated from
746 :file:`/usr/include/dlfcn.h` using the :program:`h2py` script. Availability:
747 Unix.
748
749 .. versionadded:: 2.2
750
751
752.. function:: setprofile(profilefunc)
753
754 .. index::
755 single: profile function
756 single: profiler
757
758 Set the system's profile function, which allows you to implement a Python source
759 code profiler in Python. See chapter :ref:`profile` for more information on the
760 Python profiler. The system's profile function is called similarly to the
761 system's trace function (see :func:`settrace`), but it isn't called for each
762 executed line of code (only on call and return, but the return event is reported
763 even when an exception has been set). The function is thread-specific, but
764 there is no way for the profiler to know about context switches between threads,
765 so it does not make sense to use this in the presence of multiple threads. Also,
766 its return value is not used, so it can simply return ``None``.
767
768
769.. function:: setrecursionlimit(limit)
770
771 Set the maximum depth of the Python interpreter stack to *limit*. This limit
772 prevents infinite recursion from causing an overflow of the C stack and crashing
773 Python.
774
775 The highest possible limit is platform-dependent. A user may need to set the
776 limit higher when she has a program that requires deep recursion and a platform
777 that supports a higher limit. This should be done with care, because a too-high
778 limit can lead to a crash.
779
780
781.. function:: settrace(tracefunc)
782
783 .. index::
784 single: trace function
785 single: debugger
786
787 Set the system's trace function, which allows you to implement a Python
Georg Brandld2094602008-12-05 08:51:30 +0000788 source code debugger in Python. The function is thread-specific; for a
Georg Brandl8ec7f652007-08-15 14:28:01 +0000789 debugger to support multiple threads, it must be registered using
790 :func:`settrace` for each thread being debugged.
791
Georg Brandld2094602008-12-05 08:51:30 +0000792 Trace functions should have three arguments: *frame*, *event*, and
793 *arg*. *frame* is the current stack frame. *event* is a string: ``'call'``,
794 ``'line'``, ``'return'``, ``'exception'``, ``'c_call'``, ``'c_return'``, or
795 ``'c_exception'``. *arg* depends on the event type.
796
797 The trace function is invoked (with *event* set to ``'call'``) whenever a new
798 local scope is entered; it should return a reference to a local trace
799 function to be used that scope, or ``None`` if the scope shouldn't be traced.
800
801 The local trace function should return a reference to itself (or to another
802 function for further tracing in that scope), or ``None`` to turn off tracing
803 in that scope.
804
805 The events have the following meaning:
806
Georg Brandl734373c2009-01-03 21:55:17 +0000807 ``'call'``
Georg Brandld2094602008-12-05 08:51:30 +0000808 A function is called (or some other code block entered). The
809 global trace function is called; *arg* is ``None``; the return value
810 specifies the local trace function.
811
812 ``'line'``
813 The interpreter is about to execute a new line of code (sometimes multiple
814 line events on one line exist). The local trace function is called; *arg*
815 is ``None``; the return value specifies the new local trace function.
816
817 ``'return'``
818 A function (or other code block) is about to return. The local trace
819 function is called; *arg* is the value that will be returned. The trace
820 function's return value is ignored.
821
822 ``'exception'``
823 An exception has occurred. The local trace function is called; *arg* is a
824 tuple ``(exception, value, traceback)``; the return value specifies the
825 new local trace function.
826
827 ``'c_call'``
828 A C function is about to be called. This may be an extension function or
Georg Brandl4ae4f872009-10-27 14:37:48 +0000829 a built-in. *arg* is the C function object.
Georg Brandld2094602008-12-05 08:51:30 +0000830
831 ``'c_return'``
832 A C function has returned. *arg* is ``None``.
833
834 ``'c_exception'``
835 A C function has thrown an exception. *arg* is ``None``.
836
837 Note that as an exception is propagated down the chain of callers, an
838 ``'exception'`` event is generated at each level.
839
840 For more information on code and frame objects, refer to :ref:`types`.
841
Georg Brandl5d2eb342009-10-27 15:08:27 +0000842 .. impl-detail::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000843
844 The :func:`settrace` function is intended only for implementing debuggers,
Georg Brandl5d2eb342009-10-27 15:08:27 +0000845 profilers, coverage tools and the like. Its behavior is part of the
846 implementation platform, rather than part of the language definition, and
847 thus may not be available in all Python implementations.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000848
849
850.. function:: settscdump(on_flag)
851
852 Activate dumping of VM measurements using the Pentium timestamp counter, if
853 *on_flag* is true. Deactivate these dumps if *on_flag* is off. The function is
854 available only if Python was compiled with :option:`--with-tsc`. To understand
855 the output of this dump, read :file:`Python/ceval.c` in the Python sources.
856
857 .. versionadded:: 2.4
858
Georg Brandl5a692992010-05-19 14:17:00 +0000859 .. impl-detail::
860
861 This function is intimately bound to CPython implementation details and
862 thus not likely to be implemented elsewhere.
863
Georg Brandl8ec7f652007-08-15 14:28:01 +0000864
865.. data:: stdin
866 stdout
867 stderr
868
869 .. index::
870 builtin: input
871 builtin: raw_input
872
873 File objects corresponding to the interpreter's standard input, output and error
874 streams. ``stdin`` is used for all interpreter input except for scripts but
875 including calls to :func:`input` and :func:`raw_input`. ``stdout`` is used for
Georg Brandl584265b2007-12-02 14:58:50 +0000876 the output of :keyword:`print` and :term:`expression` statements and for the
877 prompts of :func:`input` and :func:`raw_input`. The interpreter's own prompts
878 and (almost all of) its error messages go to ``stderr``. ``stdout`` and
879 ``stderr`` needn't be built-in file objects: any object is acceptable as long
Georg Brandl734373c2009-01-03 21:55:17 +0000880 as it has a :meth:`write` method that takes a string argument. (Changing these
Georg Brandl584265b2007-12-02 14:58:50 +0000881 objects doesn't affect the standard I/O streams of processes executed by
Georg Brandl8ec7f652007-08-15 14:28:01 +0000882 :func:`os.popen`, :func:`os.system` or the :func:`exec\*` family of functions in
883 the :mod:`os` module.)
884
885
886.. data:: __stdin__
887 __stdout__
888 __stderr__
889
890 These objects contain the original values of ``stdin``, ``stderr`` and
Georg Brandl9b08e052009-04-05 21:21:05 +0000891 ``stdout`` at the start of the program. They are used during finalization,
892 and could be useful to print to the actual standard stream no matter if the
893 ``sys.std*`` object has been redirected.
894
895 It can also be used to restore the actual files to known working file objects
896 in case they have been overwritten with a broken object. However, the
897 preferred way to do this is to explicitly save the previous stream before
898 replacing it, and restore the saved object.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000899
900
901.. data:: tracebacklimit
902
903 When this variable is set to an integer value, it determines the maximum number
904 of levels of traceback information printed when an unhandled exception occurs.
905 The default is ``1000``. When set to ``0`` or less, all traceback information
906 is suppressed and only the exception type and value are printed.
907
908
909.. data:: version
910
911 A string containing the version number of the Python interpreter plus additional
Georg Brandle64de922010-08-01 22:10:15 +0000912 information on the build number and compiler used. This string is displayed
913 when the interactive interpreter is started. Do not extract version information
914 out of it, rather, use :data:`version_info` and the functions provided by the
915 :mod:`platform` module.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000916
917
918.. data:: api_version
919
920 The C API version for this interpreter. Programmers may find this useful when
921 debugging version conflicts between Python and extension modules.
922
923 .. versionadded:: 2.3
924
925
926.. data:: version_info
927
928 A tuple containing the five components of the version number: *major*, *minor*,
929 *micro*, *releaselevel*, and *serial*. All values except *releaselevel* are
930 integers; the release level is ``'alpha'``, ``'beta'``, ``'candidate'``, or
931 ``'final'``. The ``version_info`` value corresponding to the Python version 2.0
932 is ``(2, 0, 0, 'final', 0)``.
933
934 .. versionadded:: 2.0
935
936
937.. data:: warnoptions
938
939 This is an implementation detail of the warnings framework; do not modify this
940 value. Refer to the :mod:`warnings` module for more information on the warnings
941 framework.
942
943
944.. data:: winver
945
946 The version number used to form registry keys on Windows platforms. This is
947 stored as string resource 1000 in the Python DLL. The value is normally the
948 first three characters of :const:`version`. It is provided in the :mod:`sys`
949 module for informational purposes; modifying this value has no effect on the
950 registry keys used by Python. Availability: Windows.
Mark Dickinson64f91282010-07-02 20:24:32 +0000951
952.. rubric:: Citations
953
954.. [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 .
955