blob: c7be1311b1a573dc351d360f2ee4cb94c1958fc9 [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 +------------------------------+------------------------------------------+
278 | :const:`no_site` | -S |
279 +------------------------------+------------------------------------------+
Andrew M. Kuchling7ce9b182008-01-15 01:29:16 +0000280 | :const:`ignore_environment` | -E |
Christian Heimesf31b69f2008-01-14 03:42:48 +0000281 +------------------------------+------------------------------------------+
282 | :const:`tabcheck` | -t or -tt |
283 +------------------------------+------------------------------------------+
284 | :const:`verbose` | -v |
285 +------------------------------+------------------------------------------+
286 | :const:`unicode` | -U |
287 +------------------------------+------------------------------------------+
288
289 .. versionadded:: 2.6
290
291
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000292.. data:: float_info
293
Christian Heimesc94e2b52008-01-14 04:13:37 +0000294 A structseq holding information about the float type. It contains low level
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000295 information about the precision and internal representation. Please study
296 your system's :file:`float.h` for more information.
297
298 +---------------------+--------------------------------------------------+
Christian Heimesc94e2b52008-01-14 04:13:37 +0000299 | attribute | explanation |
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000300 +=====================+==================================================+
301 | :const:`epsilon` | Difference between 1 and the next representable |
302 | | floating point number |
303 +---------------------+--------------------------------------------------+
304 | :const:`dig` | digits (see :file:`float.h`) |
305 +---------------------+--------------------------------------------------+
306 | :const:`mant_dig` | mantissa digits (see :file:`float.h`) |
307 +---------------------+--------------------------------------------------+
308 | :const:`max` | maximum representable finite float |
309 +---------------------+--------------------------------------------------+
310 | :const:`max_exp` | maximum int e such that radix**(e-1) is in the |
311 | | range of finite representable floats |
312 +---------------------+--------------------------------------------------+
313 | :const:`max_10_exp` | maximum int e such that 10**e is in the |
314 | | range of finite representable floats |
315 +---------------------+--------------------------------------------------+
316 | :const:`min` | Minimum positive normalizer float |
317 +---------------------+--------------------------------------------------+
318 | :const:`min_exp` | minimum int e such that radix**(e-1) is a |
319 | | normalized float |
320 +---------------------+--------------------------------------------------+
321 | :const:`min_10_exp` | minimum int e such that 10**e is a normalized |
322 | | float |
323 +---------------------+--------------------------------------------------+
324 | :const:`radix` | radix of exponent |
325 +---------------------+--------------------------------------------------+
326 | :const:`rounds` | addition rounds (see :file:`float.h`) |
327 +---------------------+--------------------------------------------------+
328
329 .. note::
330
331 The information in the table is simplified.
332
Christian Heimes3e76d932007-12-01 15:40:22 +0000333 .. versionadded:: 2.6
334
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000335
Georg Brandl8ec7f652007-08-15 14:28:01 +0000336.. function:: getcheckinterval()
337
338 Return the interpreter's "check interval"; see :func:`setcheckinterval`.
339
340 .. versionadded:: 2.3
341
342
343.. function:: getdefaultencoding()
344
345 Return the name of the current default string encoding used by the Unicode
346 implementation.
347
348 .. versionadded:: 2.0
349
350
351.. function:: getdlopenflags()
352
353 Return the current value of the flags that are used for :cfunc:`dlopen` calls.
354 The flag constants are defined in the :mod:`dl` and :mod:`DLFCN` modules.
355 Availability: Unix.
356
357 .. versionadded:: 2.2
358
359
360.. function:: getfilesystemencoding()
361
362 Return the name of the encoding used to convert Unicode filenames into system
363 file names, or ``None`` if the system default encoding is used. The result value
364 depends on the operating system:
365
366 * On Windows 9x, the encoding is "mbcs".
367
368 * On Mac OS X, the encoding is "utf-8".
369
370 * On Unix, the encoding is the user's preference according to the result of
371 nl_langinfo(CODESET), or :const:`None` if the ``nl_langinfo(CODESET)`` failed.
372
373 * On Windows NT+, file names are Unicode natively, so no conversion is
374 performed. :func:`getfilesystemencoding` still returns ``'mbcs'``, as this is
375 the encoding that applications should use when they explicitly want to convert
376 Unicode strings to byte strings that are equivalent when used as file names.
377
378 .. versionadded:: 2.3
379
380
381.. function:: getrefcount(object)
382
383 Return the reference count of the *object*. The count returned is generally one
384 higher than you might expect, because it includes the (temporary) reference as
385 an argument to :func:`getrefcount`.
386
387
388.. function:: getrecursionlimit()
389
390 Return the current value of the recursion limit, the maximum depth of the Python
391 interpreter stack. This limit prevents infinite recursion from causing an
392 overflow of the C stack and crashing Python. It can be set by
393 :func:`setrecursionlimit`.
394
395
Robert Schuppenies47629022008-07-10 17:13:55 +0000396.. function:: getsizeof(object[, default])
Robert Schuppenies51df0642008-06-01 16:16:17 +0000397
398 Return the size of an object in bytes. The object can be any type of
399 object. All built-in objects will return correct results, but this
Robert Schuppenies47629022008-07-10 17:13:55 +0000400 does not have to hold true for third-party extensions as it is implementation
Robert Schuppenies51df0642008-06-01 16:16:17 +0000401 specific.
402
Benjamin Peterson751c2032009-09-22 22:30:03 +0000403 If given, *default* will be returned if the object does not provide means to
404 retrieve the size. Otherwise a `TypeError` will be raised.
Robert Schuppenies47629022008-07-10 17:13:55 +0000405
Benjamin Peterson751c2032009-09-22 22:30:03 +0000406 :func:`getsizeof` calls the object's ``__sizeof__`` method and adds an
407 additional garbage collector overhead if the object is managed by the garbage
408 collector.
Robert Schuppenies47629022008-07-10 17:13:55 +0000409
Robert Schuppenies51df0642008-06-01 16:16:17 +0000410 .. versionadded:: 2.6
411
412
Georg Brandl8ec7f652007-08-15 14:28:01 +0000413.. function:: _getframe([depth])
414
415 Return a frame object from the call stack. If optional integer *depth* is
416 given, return the frame object that many calls below the top of the stack. If
417 that is deeper than the call stack, :exc:`ValueError` is raised. The default
418 for *depth* is zero, returning the frame at the top of the call stack.
419
Georg Brandl5d2eb342009-10-27 15:08:27 +0000420 .. impl-detail::
421
422 This function should be used for internal and specialized purposes only.
423 It is not guaranteed to exist in all implementations of Python.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000424
425
Georg Brandl56112892008-01-20 13:59:46 +0000426.. function:: getprofile()
427
428 .. index::
429 single: profile function
430 single: profiler
431
432 Get the profiler function as set by :func:`setprofile`.
433
434 .. versionadded:: 2.6
435
436
437.. function:: gettrace()
438
439 .. index::
440 single: trace function
441 single: debugger
442
443 Get the trace function as set by :func:`settrace`.
444
Georg Brandl5d2eb342009-10-27 15:08:27 +0000445 .. impl-detail::
Georg Brandl56112892008-01-20 13:59:46 +0000446
447 The :func:`gettrace` function is intended only for implementing debuggers,
Georg Brandl5d2eb342009-10-27 15:08:27 +0000448 profilers, coverage tools and the like. Its behavior is part of the
449 implementation platform, rather than part of the language definition, and
450 thus may not be available in all Python implementations.
Georg Brandl56112892008-01-20 13:59:46 +0000451
452 .. versionadded:: 2.6
453
454
Georg Brandl8ec7f652007-08-15 14:28:01 +0000455.. function:: getwindowsversion()
456
457 Return a tuple containing five components, describing the Windows version
458 currently running. The elements are *major*, *minor*, *build*, *platform*, and
459 *text*. *text* contains a string while all other values are integers.
460
461 *platform* may be one of the following values:
462
Jeroen Ruigrok van der Wervenaa3cadb2008-04-21 20:15:39 +0000463 +-----------------------------------------+-------------------------+
464 | Constant | Platform |
465 +=========================================+=========================+
466 | :const:`0 (VER_PLATFORM_WIN32s)` | Win32s on Windows 3.1 |
467 +-----------------------------------------+-------------------------+
468 | :const:`1 (VER_PLATFORM_WIN32_WINDOWS)` | Windows 95/98/ME |
469 +-----------------------------------------+-------------------------+
470 | :const:`2 (VER_PLATFORM_WIN32_NT)` | Windows NT/2000/XP/x64 |
471 +-----------------------------------------+-------------------------+
472 | :const:`3 (VER_PLATFORM_WIN32_CE)` | Windows CE |
473 +-----------------------------------------+-------------------------+
Georg Brandl8ec7f652007-08-15 14:28:01 +0000474
475 This function wraps the Win32 :cfunc:`GetVersionEx` function; see the Microsoft
476 documentation for more information about these fields.
477
478 Availability: Windows.
479
480 .. versionadded:: 2.3
481
482
483.. data:: hexversion
484
485 The version number encoded as a single integer. This is guaranteed to increase
486 with each version, including proper support for non-production releases. For
487 example, to test that the Python interpreter is at least version 1.5.2, use::
488
489 if sys.hexversion >= 0x010502F0:
490 # use some advanced feature
491 ...
492 else:
493 # use an alternative implementation or warn the user
494 ...
495
496 This is called ``hexversion`` since it only really looks meaningful when viewed
497 as the result of passing it to the built-in :func:`hex` function. The
498 ``version_info`` value may be used for a more human-friendly encoding of the
499 same information.
500
501 .. versionadded:: 1.5.2
502
503
504.. data:: last_type
505 last_value
506 last_traceback
507
508 These three variables are not always defined; they are set when an exception is
509 not handled and the interpreter prints an error message and a stack traceback.
510 Their intended use is to allow an interactive user to import a debugger module
511 and engage in post-mortem debugging without having to re-execute the command
512 that caused the error. (Typical use is ``import pdb; pdb.pm()`` to enter the
513 post-mortem debugger; see chapter :ref:`debugger` for
514 more information.)
515
516 The meaning of the variables is the same as that of the return values from
517 :func:`exc_info` above. (Since there is only one interactive thread,
518 thread-safety is not a concern for these variables, unlike for ``exc_type``
519 etc.)
520
521
522.. data:: maxint
523
524 The largest positive integer supported by Python's regular integer type. This
525 is at least 2\*\*31-1. The largest negative integer is ``-maxint-1`` --- the
526 asymmetry results from the use of 2's complement binary arithmetic.
527
Martin v. Löwis4dd019f2008-05-20 08:11:19 +0000528.. data:: maxsize
529
530 The largest positive integer supported by the platform's Py_ssize_t type,
531 and thus the maximum size lists, strings, dicts, and many other containers
532 can have.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000533
534.. data:: maxunicode
535
536 An integer giving the largest supported code point for a Unicode character. The
537 value of this depends on the configuration option that specifies whether Unicode
538 characters are stored as UCS-2 or UCS-4.
539
540
Georg Brandl8943caf2009-04-05 21:11:43 +0000541.. data:: meta_path
542
543 A list of :term:`finder` objects that have their :meth:`find_module`
544 methods called to see if one of the objects can find the module to be
545 imported. The :meth:`find_module` method is called at least with the
546 absolute name of the module being imported. If the module to be imported is
547 contained in package then the parent package's :attr:`__path__` attribute
548 is passed in as a second argument. The method returns :keyword:`None` if
549 the module cannot be found, else returns a :term:`loader`.
550
551 :data:`sys.meta_path` is searched before any implicit default finders or
552 :data:`sys.path`.
553
554 See :pep:`302` for the original specification.
555
556
Georg Brandl8ec7f652007-08-15 14:28:01 +0000557.. data:: modules
558
559 .. index:: builtin: reload
560
561 This is a dictionary that maps module names to modules which have already been
562 loaded. This can be manipulated to force reloading of modules and other tricks.
563 Note that removing a module from this dictionary is *not* the same as calling
564 :func:`reload` on the corresponding module object.
565
566
567.. data:: path
568
569 .. index:: triple: module; search; path
570
571 A list of strings that specifies the search path for modules. Initialized from
572 the environment variable :envvar:`PYTHONPATH`, plus an installation-dependent
573 default.
574
575 As initialized upon program startup, the first item of this list, ``path[0]``,
576 is the directory containing the script that was used to invoke the Python
577 interpreter. If the script directory is not available (e.g. if the interpreter
578 is invoked interactively or if the script is read from standard input),
579 ``path[0]`` is the empty string, which directs Python to search modules in the
580 current directory first. Notice that the script directory is inserted *before*
581 the entries inserted as a result of :envvar:`PYTHONPATH`.
582
583 A program is free to modify this list for its own purposes.
584
585 .. versionchanged:: 2.3
586 Unicode strings are no longer ignored.
587
Georg Brandlc04c2892009-01-14 00:00:17 +0000588 .. seealso::
589 Module :mod:`site` This describes how to use .pth files to extend
590 :data:`sys.path`.
591
Georg Brandl8ec7f652007-08-15 14:28:01 +0000592
Georg Brandl8943caf2009-04-05 21:11:43 +0000593.. data:: path_hooks
594
595 A list of callables that take a path argument to try to create a
596 :term:`finder` for the path. If a finder can be created, it is to be
597 returned by the callable, else raise :exc:`ImportError`.
598
599 Originally specified in :pep:`302`.
600
601
602.. data:: path_importer_cache
603
604 A dictionary acting as a cache for :term:`finder` objects. The keys are
605 paths that have been passed to :data:`sys.path_hooks` and the values are
606 the finders that are found. If a path is a valid file system path but no
607 explicit finder is found on :data:`sys.path_hooks` then :keyword:`None` is
608 stored to represent the implicit default finder should be used. If the path
609 is not an existing path then :class:`imp.NullImporter` is set.
610
611 Originally specified in :pep:`302`.
612
613
Georg Brandl8ec7f652007-08-15 14:28:01 +0000614.. data:: platform
615
Georg Brandl440f2ff2008-01-20 12:57:47 +0000616 This string contains a platform identifier that can be used to append
617 platform-specific components to :data:`sys.path`, for instance.
618
619 For Unix systems, this is the lowercased OS name as returned by ``uname -s``
620 with the first part of the version as returned by ``uname -r`` appended,
621 e.g. ``'sunos5'`` or ``'linux2'``, *at the time when Python was built*.
622 For other systems, the values are:
623
624 ================ ===========================
625 System :data:`platform` value
626 ================ ===========================
627 Windows ``'win32'``
628 Windows/Cygwin ``'cygwin'``
Georg Brandl9af94982008-09-13 17:41:16 +0000629 Mac OS X ``'darwin'``
Georg Brandl440f2ff2008-01-20 12:57:47 +0000630 OS/2 ``'os2'``
631 OS/2 EMX ``'os2emx'``
632 RiscOS ``'riscos'``
633 AtheOS ``'atheos'``
634 ================ ===========================
Georg Brandl8ec7f652007-08-15 14:28:01 +0000635
636
637.. data:: prefix
638
639 A string giving the site-specific directory prefix where the platform
640 independent Python files are installed; by default, this is the string
641 ``'/usr/local'``. This can be set at build time with the :option:`--prefix`
642 argument to the :program:`configure` script. The main collection of Python
643 library modules is installed in the directory ``prefix + '/lib/pythonversion'``
644 while the platform independent header files (all except :file:`pyconfig.h`) are
645 stored in ``prefix + '/include/pythonversion'``, where *version* is equal to
646 ``version[:3]``.
647
648
649.. data:: ps1
650 ps2
651
652 .. index::
653 single: interpreter prompts
654 single: prompts, interpreter
655
656 Strings specifying the primary and secondary prompt of the interpreter. These
657 are only defined if the interpreter is in interactive mode. Their initial
658 values in this case are ``'>>> '`` and ``'... '``. If a non-string object is
659 assigned to either variable, its :func:`str` is re-evaluated each time the
660 interpreter prepares to read a new interactive command; this can be used to
661 implement a dynamic prompt.
662
663
Christian Heimesd7b33372007-11-28 08:02:36 +0000664.. data:: py3kwarning
665
666 Bool containing the status of the Python 3.0 warning flag. It's ``True``
Georg Brandl40e15ed2009-04-05 21:48:06 +0000667 when Python is started with the -3 option. (This should be considered
668 read-only; setting it to a different value doesn't have an effect on
669 Python 3.0 warnings.)
Christian Heimesd7b33372007-11-28 08:02:36 +0000670
Georg Brandl5f794462008-03-21 21:05:03 +0000671 .. versionadded:: 2.6
672
Christian Heimesd7b33372007-11-28 08:02:36 +0000673
Georg Brandl2da0fce2008-01-07 17:09:35 +0000674.. data:: dont_write_bytecode
675
676 If this is true, Python won't try to write ``.pyc`` or ``.pyo`` files on the
677 import of source modules. This value is initially set to ``True`` or ``False``
678 depending on the ``-B`` command line option and the ``PYTHONDONTWRITEBYTECODE``
679 environment variable, but you can set it yourself to control bytecode file
680 generation.
681
682 .. versionadded:: 2.6
683
684
Georg Brandl8ec7f652007-08-15 14:28:01 +0000685.. function:: setcheckinterval(interval)
686
687 Set the interpreter's "check interval". This integer value determines how often
688 the interpreter checks for periodic things such as thread switches and signal
689 handlers. The default is ``100``, meaning the check is performed every 100
690 Python virtual instructions. Setting it to a larger value may increase
691 performance for programs using threads. Setting it to a value ``<=`` 0 checks
692 every virtual instruction, maximizing responsiveness as well as overhead.
693
694
695.. function:: setdefaultencoding(name)
696
697 Set the current default string encoding used by the Unicode implementation. If
698 *name* does not match any available encoding, :exc:`LookupError` is raised.
699 This function is only intended to be used by the :mod:`site` module
700 implementation and, where needed, by :mod:`sitecustomize`. Once used by the
701 :mod:`site` module, it is removed from the :mod:`sys` module's namespace.
702
Georg Brandlb19be572007-12-29 10:57:00 +0000703 .. Note that :mod:`site` is not imported if the :option:`-S` option is passed
704 to the interpreter, in which case this function will remain available.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000705
706 .. versionadded:: 2.0
707
708
709.. function:: setdlopenflags(n)
710
711 Set the flags used by the interpreter for :cfunc:`dlopen` calls, such as when
712 the interpreter loads extension modules. Among other things, this will enable a
713 lazy resolving of symbols when importing a module, if called as
714 ``sys.setdlopenflags(0)``. To share symbols across extension modules, call as
715 ``sys.setdlopenflags(dl.RTLD_NOW | dl.RTLD_GLOBAL)``. Symbolic names for the
716 flag modules can be either found in the :mod:`dl` module, or in the :mod:`DLFCN`
717 module. If :mod:`DLFCN` is not available, it can be generated from
718 :file:`/usr/include/dlfcn.h` using the :program:`h2py` script. Availability:
719 Unix.
720
721 .. versionadded:: 2.2
722
723
724.. function:: setprofile(profilefunc)
725
726 .. index::
727 single: profile function
728 single: profiler
729
730 Set the system's profile function, which allows you to implement a Python source
731 code profiler in Python. See chapter :ref:`profile` for more information on the
732 Python profiler. The system's profile function is called similarly to the
733 system's trace function (see :func:`settrace`), but it isn't called for each
734 executed line of code (only on call and return, but the return event is reported
735 even when an exception has been set). The function is thread-specific, but
736 there is no way for the profiler to know about context switches between threads,
737 so it does not make sense to use this in the presence of multiple threads. Also,
738 its return value is not used, so it can simply return ``None``.
739
740
741.. function:: setrecursionlimit(limit)
742
743 Set the maximum depth of the Python interpreter stack to *limit*. This limit
744 prevents infinite recursion from causing an overflow of the C stack and crashing
745 Python.
746
747 The highest possible limit is platform-dependent. A user may need to set the
748 limit higher when she has a program that requires deep recursion and a platform
749 that supports a higher limit. This should be done with care, because a too-high
750 limit can lead to a crash.
751
752
753.. function:: settrace(tracefunc)
754
755 .. index::
756 single: trace function
757 single: debugger
758
759 Set the system's trace function, which allows you to implement a Python
Georg Brandld2094602008-12-05 08:51:30 +0000760 source code debugger in Python. The function is thread-specific; for a
Georg Brandl8ec7f652007-08-15 14:28:01 +0000761 debugger to support multiple threads, it must be registered using
762 :func:`settrace` for each thread being debugged.
763
Georg Brandld2094602008-12-05 08:51:30 +0000764 Trace functions should have three arguments: *frame*, *event*, and
765 *arg*. *frame* is the current stack frame. *event* is a string: ``'call'``,
766 ``'line'``, ``'return'``, ``'exception'``, ``'c_call'``, ``'c_return'``, or
767 ``'c_exception'``. *arg* depends on the event type.
768
769 The trace function is invoked (with *event* set to ``'call'``) whenever a new
770 local scope is entered; it should return a reference to a local trace
771 function to be used that scope, or ``None`` if the scope shouldn't be traced.
772
773 The local trace function should return a reference to itself (or to another
774 function for further tracing in that scope), or ``None`` to turn off tracing
775 in that scope.
776
777 The events have the following meaning:
778
Georg Brandl734373c2009-01-03 21:55:17 +0000779 ``'call'``
Georg Brandld2094602008-12-05 08:51:30 +0000780 A function is called (or some other code block entered). The
781 global trace function is called; *arg* is ``None``; the return value
782 specifies the local trace function.
783
784 ``'line'``
785 The interpreter is about to execute a new line of code (sometimes multiple
786 line events on one line exist). The local trace function is called; *arg*
787 is ``None``; the return value specifies the new local trace function.
788
789 ``'return'``
790 A function (or other code block) is about to return. The local trace
791 function is called; *arg* is the value that will be returned. The trace
792 function's return value is ignored.
793
794 ``'exception'``
795 An exception has occurred. The local trace function is called; *arg* is a
796 tuple ``(exception, value, traceback)``; the return value specifies the
797 new local trace function.
798
799 ``'c_call'``
800 A C function is about to be called. This may be an extension function or
Georg Brandl4ae4f872009-10-27 14:37:48 +0000801 a built-in. *arg* is the C function object.
Georg Brandld2094602008-12-05 08:51:30 +0000802
803 ``'c_return'``
804 A C function has returned. *arg* is ``None``.
805
806 ``'c_exception'``
807 A C function has thrown an exception. *arg* is ``None``.
808
809 Note that as an exception is propagated down the chain of callers, an
810 ``'exception'`` event is generated at each level.
811
812 For more information on code and frame objects, refer to :ref:`types`.
813
Georg Brandl5d2eb342009-10-27 15:08:27 +0000814 .. impl-detail::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000815
816 The :func:`settrace` function is intended only for implementing debuggers,
Georg Brandl5d2eb342009-10-27 15:08:27 +0000817 profilers, coverage tools and the like. Its behavior is part of the
818 implementation platform, rather than part of the language definition, and
819 thus may not be available in all Python implementations.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000820
821
822.. function:: settscdump(on_flag)
823
824 Activate dumping of VM measurements using the Pentium timestamp counter, if
825 *on_flag* is true. Deactivate these dumps if *on_flag* is off. The function is
826 available only if Python was compiled with :option:`--with-tsc`. To understand
827 the output of this dump, read :file:`Python/ceval.c` in the Python sources.
828
829 .. versionadded:: 2.4
830
831
832.. data:: stdin
833 stdout
834 stderr
835
836 .. index::
837 builtin: input
838 builtin: raw_input
839
840 File objects corresponding to the interpreter's standard input, output and error
841 streams. ``stdin`` is used for all interpreter input except for scripts but
842 including calls to :func:`input` and :func:`raw_input`. ``stdout`` is used for
Georg Brandl584265b2007-12-02 14:58:50 +0000843 the output of :keyword:`print` and :term:`expression` statements and for the
844 prompts of :func:`input` and :func:`raw_input`. The interpreter's own prompts
845 and (almost all of) its error messages go to ``stderr``. ``stdout`` and
846 ``stderr`` needn't be built-in file objects: any object is acceptable as long
Georg Brandl734373c2009-01-03 21:55:17 +0000847 as it has a :meth:`write` method that takes a string argument. (Changing these
Georg Brandl584265b2007-12-02 14:58:50 +0000848 objects doesn't affect the standard I/O streams of processes executed by
Georg Brandl8ec7f652007-08-15 14:28:01 +0000849 :func:`os.popen`, :func:`os.system` or the :func:`exec\*` family of functions in
850 the :mod:`os` module.)
851
852
853.. data:: __stdin__
854 __stdout__
855 __stderr__
856
857 These objects contain the original values of ``stdin``, ``stderr`` and
Georg Brandl9b08e052009-04-05 21:21:05 +0000858 ``stdout`` at the start of the program. They are used during finalization,
859 and could be useful to print to the actual standard stream no matter if the
860 ``sys.std*`` object has been redirected.
861
862 It can also be used to restore the actual files to known working file objects
863 in case they have been overwritten with a broken object. However, the
864 preferred way to do this is to explicitly save the previous stream before
865 replacing it, and restore the saved object.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000866
867
868.. data:: tracebacklimit
869
870 When this variable is set to an integer value, it determines the maximum number
871 of levels of traceback information printed when an unhandled exception occurs.
872 The default is ``1000``. When set to ``0`` or less, all traceback information
873 is suppressed and only the exception type and value are printed.
874
875
876.. data:: version
877
878 A string containing the version number of the Python interpreter plus additional
879 information on the build number and compiler used. It has a value of the form
880 ``'version (#build_number, build_date, build_time) [compiler]'``. The first
881 three characters are used to identify the version in the installation
882 directories (where appropriate on each platform). An example::
883
884 >>> import sys
885 >>> sys.version
886 '1.5.2 (#0 Apr 13 1999, 10:51:12) [MSC 32 bit (Intel)]'
887
888
889.. data:: api_version
890
891 The C API version for this interpreter. Programmers may find this useful when
892 debugging version conflicts between Python and extension modules.
893
894 .. versionadded:: 2.3
895
896
897.. data:: version_info
898
899 A tuple containing the five components of the version number: *major*, *minor*,
900 *micro*, *releaselevel*, and *serial*. All values except *releaselevel* are
901 integers; the release level is ``'alpha'``, ``'beta'``, ``'candidate'``, or
902 ``'final'``. The ``version_info`` value corresponding to the Python version 2.0
903 is ``(2, 0, 0, 'final', 0)``.
904
905 .. versionadded:: 2.0
906
907
908.. data:: warnoptions
909
910 This is an implementation detail of the warnings framework; do not modify this
911 value. Refer to the :mod:`warnings` module for more information on the warnings
912 framework.
913
914
915.. data:: winver
916
917 The version number used to form registry keys on Windows platforms. This is
918 stored as string resource 1000 in the Python DLL. The value is normally the
919 first three characters of :const:`version`. It is provided in the :mod:`sys`
920 module for informational purposes; modifying this value has no effect on the
921 registry keys used by Python. Availability: Windows.