blob: 94e4eb936ecfa38d5b16ce43d4b12580769f6a34 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +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
Georg Brandl116aa622007-08-15 14:28:22 +000032
33.. data:: subversion
34
35 A triple (repo, branch, version) representing the Subversion information of the
36 Python interpreter. *repo* is the name of the repository, ``'CPython'``.
37 *branch* is a string of one of the forms ``'trunk'``, ``'branches/name'`` or
38 ``'tags/name'``. *version* is the output of ``svnversion``, if the interpreter
39 was built from a Subversion checkout; it contains the revision number (range)
40 and possibly a trailing 'M' if there were local modifications. If the tree was
41 exported (or svnversion was not available), it is the revision of
42 ``Include/patchlevel.h`` if the branch is a tag. Otherwise, it is ``None``.
43
Georg Brandl116aa622007-08-15 14:28:22 +000044
45.. data:: builtin_module_names
46
47 A tuple of strings giving the names of all modules that are compiled into this
48 Python interpreter. (This information is not available in any other way ---
49 ``modules.keys()`` only lists the imported modules.)
50
51
52.. data:: copyright
53
54 A string containing the copyright pertaining to the Python interpreter.
55
56
57.. function:: _current_frames()
58
59 Return a dictionary mapping each thread's identifier to the topmost stack frame
60 currently active in that thread at the time the function is called. Note that
61 functions in the :mod:`traceback` module can build the call stack given such a
62 frame.
63
64 This is most useful for debugging deadlock: this function does not require the
65 deadlocked threads' cooperation, and such threads' call stacks are frozen for as
66 long as they remain deadlocked. The frame returned for a non-deadlocked thread
67 may bear no relationship to that thread's current activity by the time calling
68 code examines the frame.
69
70 This function should be used for internal and specialized purposes only.
71
Georg Brandl116aa622007-08-15 14:28:22 +000072
73.. data:: dllhandle
74
75 Integer specifying the handle of the Python DLL. Availability: Windows.
76
77
78.. function:: displayhook(value)
79
80 If *value* is not ``None``, this function prints it to ``sys.stdout``, and saves
81 it in ``__builtin__._``.
82
83 ``sys.displayhook`` is called on the result of evaluating an expression entered
84 in an interactive Python session. The display of these values can be customized
85 by assigning another one-argument function to ``sys.displayhook``.
86
87
88.. function:: excepthook(type, value, traceback)
89
90 This function prints out a given traceback and exception to ``sys.stderr``.
91
92 When an exception is raised and uncaught, the interpreter calls
93 ``sys.excepthook`` with three arguments, the exception class, exception
94 instance, and a traceback object. In an interactive session this happens just
95 before control is returned to the prompt; in a Python program this happens just
96 before the program exits. The handling of such top-level exceptions can be
97 customized by assigning another three-argument function to ``sys.excepthook``.
98
99
100.. data:: __displayhook__
101 __excepthook__
102
103 These objects contain the original values of ``displayhook`` and ``excepthook``
104 at the start of the program. They are saved so that ``displayhook`` and
105 ``excepthook`` can be restored in case they happen to get replaced with broken
106 objects.
107
108
109.. function:: exc_info()
110
111 This function returns a tuple of three values that give information about the
112 exception that is currently being handled. The information returned is specific
113 both to the current thread and to the current stack frame. If the current stack
114 frame is not handling an exception, the information is taken from the calling
115 stack frame, or its caller, and so on until a stack frame is found that is
116 handling an exception. Here, "handling an exception" is defined as "executing
117 or having executed an except clause." For any stack frame, only information
118 about the most recently handled exception is accessible.
119
120 .. index:: object: traceback
121
122 If no exception is being handled anywhere on the stack, a tuple containing three
123 ``None`` values is returned. Otherwise, the values returned are ``(type, value,
124 traceback)``. Their meaning is: *type* gets the exception type of the exception
125 being handled (a class object); *value* gets the exception parameter (its
126 :dfn:`associated value` or the second argument to :keyword:`raise`, which is
127 always a class instance if the exception type is a class object); *traceback*
128 gets a traceback object (see the Reference Manual) which encapsulates the call
129 stack at the point where the exception originally occurred.
130
131 .. warning::
132
133 Assigning the *traceback* return value to a local variable in a function that is
134 handling an exception will cause a circular reference. This will prevent
135 anything referenced by a local variable in the same function or by the traceback
136 from being garbage collected. Since most functions don't need access to the
137 traceback, the best solution is to use something like ``exctype, value =
138 sys.exc_info()[:2]`` to extract only the exception type and value. If you do
139 need the traceback, make sure to delete it after use (best done with a
140 :keyword:`try` ... :keyword:`finally` statement) or to call :func:`exc_info` in
141 a function that does not itself handle an exception.
142
143 .. note::
144
145 Beginning with Python 2.2, such cycles are automatically reclaimed when garbage
146 collection is enabled and they become unreachable, but it remains more efficient
147 to avoid creating cycles.
148
149
150.. data:: exec_prefix
151
152 A string giving the site-specific directory prefix where the platform-dependent
153 Python files are installed; by default, this is also ``'/usr/local'``. This can
154 be set at build time with the :option:`--exec-prefix` argument to the
155 :program:`configure` script. Specifically, all configuration files (e.g. the
156 :file:`pyconfig.h` header file) are installed in the directory ``exec_prefix +
157 '/lib/pythonversion/config'``, and shared library modules are installed in
158 ``exec_prefix + '/lib/pythonversion/lib-dynload'``, where *version* is equal to
159 ``version[:3]``.
160
161
162.. data:: executable
163
164 A string giving the name of the executable binary for the Python interpreter, on
165 systems where this makes sense.
166
167
168.. function:: exit([arg])
169
170 Exit from Python. This is implemented by raising the :exc:`SystemExit`
171 exception, so cleanup actions specified by finally clauses of :keyword:`try`
172 statements are honored, and it is possible to intercept the exit attempt at an
173 outer level. The optional argument *arg* can be an integer giving the exit
174 status (defaulting to zero), or another type of object. If it is an integer,
175 zero is considered "successful termination" and any nonzero value is considered
176 "abnormal termination" by shells and the like. Most systems require it to be in
177 the range 0-127, and produce undefined results otherwise. Some systems have a
178 convention for assigning specific meanings to specific exit codes, but these are
179 generally underdeveloped; Unix programs generally use 2 for command line syntax
180 errors and 1 for all other kind of errors. If another type of object is passed,
181 ``None`` is equivalent to passing zero, and any other object is printed to
182 ``sys.stderr`` and results in an exit code of 1. In particular,
183 ``sys.exit("some error message")`` is a quick way to exit a program when an
184 error occurs.
185
186
187.. function:: getcheckinterval()
188
189 Return the interpreter's "check interval"; see :func:`setcheckinterval`.
190
Georg Brandl116aa622007-08-15 14:28:22 +0000191
192.. function:: getdefaultencoding()
193
194 Return the name of the current default string encoding used by the Unicode
195 implementation.
196
Georg Brandl116aa622007-08-15 14:28:22 +0000197
198.. function:: getdlopenflags()
199
200 Return the current value of the flags that are used for :cfunc:`dlopen` calls.
201 The flag constants are defined in the :mod:`dl` and :mod:`DLFCN` modules.
202 Availability: Unix.
203
Georg Brandl116aa622007-08-15 14:28:22 +0000204
205.. function:: getfilesystemencoding()
206
207 Return the name of the encoding used to convert Unicode filenames into system
208 file names, or ``None`` if the system default encoding is used. The result value
209 depends on the operating system:
210
211 * On Windows 9x, the encoding is "mbcs".
212
213 * On Mac OS X, the encoding is "utf-8".
214
215 * On Unix, the encoding is the user's preference according to the result of
216 nl_langinfo(CODESET), or :const:`None` if the ``nl_langinfo(CODESET)`` failed.
217
218 * On Windows NT+, file names are Unicode natively, so no conversion is
219 performed. :func:`getfilesystemencoding` still returns ``'mbcs'``, as this is
220 the encoding that applications should use when they explicitly want to convert
221 Unicode strings to byte strings that are equivalent when used as file names.
222
Georg Brandl116aa622007-08-15 14:28:22 +0000223
224.. function:: getrefcount(object)
225
226 Return the reference count of the *object*. The count returned is generally one
227 higher than you might expect, because it includes the (temporary) reference as
228 an argument to :func:`getrefcount`.
229
230
231.. function:: getrecursionlimit()
232
233 Return the current value of the recursion limit, the maximum depth of the Python
234 interpreter stack. This limit prevents infinite recursion from causing an
235 overflow of the C stack and crashing Python. It can be set by
236 :func:`setrecursionlimit`.
237
238
239.. function:: _getframe([depth])
240
241 Return a frame object from the call stack. If optional integer *depth* is
242 given, return the frame object that many calls below the top of the stack. If
243 that is deeper than the call stack, :exc:`ValueError` is raised. The default
244 for *depth* is zero, returning the frame at the top of the call stack.
245
246 This function should be used for internal and specialized purposes only.
247
248
249.. function:: getwindowsversion()
250
251 Return a tuple containing five components, describing the Windows version
252 currently running. The elements are *major*, *minor*, *build*, *platform*, and
253 *text*. *text* contains a string while all other values are integers.
254
255 *platform* may be one of the following values:
256
257 +-----------------------------------------+-----------------------+
258 | Constant | Platform |
259 +=========================================+=======================+
260 | :const:`0 (VER_PLATFORM_WIN32s)` | Win32s on Windows 3.1 |
261 +-----------------------------------------+-----------------------+
262 | :const:`1 (VER_PLATFORM_WIN32_WINDOWS)` | Windows 95/98/ME |
263 +-----------------------------------------+-----------------------+
264 | :const:`2 (VER_PLATFORM_WIN32_NT)` | Windows NT/2000/XP |
265 +-----------------------------------------+-----------------------+
266 | :const:`3 (VER_PLATFORM_WIN32_CE)` | Windows CE |
267 +-----------------------------------------+-----------------------+
268
269 This function wraps the Win32 :cfunc:`GetVersionEx` function; see the Microsoft
270 documentation for more information about these fields.
271
272 Availability: Windows.
273
Georg Brandl116aa622007-08-15 14:28:22 +0000274
275.. data:: hexversion
276
277 The version number encoded as a single integer. This is guaranteed to increase
278 with each version, including proper support for non-production releases. For
279 example, to test that the Python interpreter is at least version 1.5.2, use::
280
281 if sys.hexversion >= 0x010502F0:
282 # use some advanced feature
283 ...
284 else:
285 # use an alternative implementation or warn the user
286 ...
287
288 This is called ``hexversion`` since it only really looks meaningful when viewed
289 as the result of passing it to the built-in :func:`hex` function. The
290 ``version_info`` value may be used for a more human-friendly encoding of the
291 same information.
292
Georg Brandl116aa622007-08-15 14:28:22 +0000293
294.. function:: intern(string)
295
296 Enter *string* in the table of "interned" strings and return the interned string
297 -- which is *string* itself or a copy. Interning strings is useful to gain a
298 little performance on dictionary lookup -- if the keys in a dictionary are
299 interned, and the lookup key is interned, the key comparisons (after hashing)
300 can be done by a pointer compare instead of a string compare. Normally, the
301 names used in Python programs are automatically interned, and the dictionaries
302 used to hold module, class or instance attributes have interned keys.
303
Georg Brandl55ac8f02007-09-01 13:51:09 +0000304 Interned strings are not immortal; you must keep a reference to the return
305 value of :func:`intern` around to benefit from it.
Georg Brandl116aa622007-08-15 14:28:22 +0000306
307
308.. data:: last_type
309 last_value
310 last_traceback
311
312 These three variables are not always defined; they are set when an exception is
313 not handled and the interpreter prints an error message and a stack traceback.
314 Their intended use is to allow an interactive user to import a debugger module
315 and engage in post-mortem debugging without having to re-execute the command
316 that caused the error. (Typical use is ``import pdb; pdb.pm()`` to enter the
317 post-mortem debugger; see chapter :ref:`debugger` for
318 more information.)
319
320 The meaning of the variables is the same as that of the return values from
321 :func:`exc_info` above. (Since there is only one interactive thread,
322 thread-safety is not a concern for these variables, unlike for ``exc_type``
323 etc.)
324
325
326.. data:: maxint
327
328 The largest positive integer supported by Python's regular integer type. This
329 is at least 2\*\*31-1. The largest negative integer is ``-maxint-1`` --- the
330 asymmetry results from the use of 2's complement binary arithmetic.
331
332
333.. data:: maxunicode
334
335 An integer giving the largest supported code point for a Unicode character. The
336 value of this depends on the configuration option that specifies whether Unicode
337 characters are stored as UCS-2 or UCS-4.
338
339
340.. data:: modules
341
342 This is a dictionary that maps module names to modules which have already been
343 loaded. This can be manipulated to force reloading of modules and other tricks.
344
345
346.. data:: path
347
348 .. index:: triple: module; search; path
349
350 A list of strings that specifies the search path for modules. Initialized from
351 the environment variable :envvar:`PYTHONPATH`, plus an installation-dependent
352 default.
353
354 As initialized upon program startup, the first item of this list, ``path[0]``,
355 is the directory containing the script that was used to invoke the Python
356 interpreter. If the script directory is not available (e.g. if the interpreter
357 is invoked interactively or if the script is read from standard input),
358 ``path[0]`` is the empty string, which directs Python to search modules in the
359 current directory first. Notice that the script directory is inserted *before*
360 the entries inserted as a result of :envvar:`PYTHONPATH`.
361
362 A program is free to modify this list for its own purposes.
363
Georg Brandl116aa622007-08-15 14:28:22 +0000364
365.. data:: platform
366
367 This string contains a platform identifier, e.g. ``'sunos5'`` or ``'linux1'``.
368 This can be used to append platform-specific components to ``path``, for
369 instance.
370
371
372.. data:: prefix
373
374 A string giving the site-specific directory prefix where the platform
375 independent Python files are installed; by default, this is the string
376 ``'/usr/local'``. This can be set at build time with the :option:`--prefix`
377 argument to the :program:`configure` script. The main collection of Python
378 library modules is installed in the directory ``prefix + '/lib/pythonversion'``
379 while the platform independent header files (all except :file:`pyconfig.h`) are
380 stored in ``prefix + '/include/pythonversion'``, where *version* is equal to
381 ``version[:3]``.
382
383
384.. data:: ps1
385 ps2
386
387 .. index::
388 single: interpreter prompts
389 single: prompts, interpreter
390
391 Strings specifying the primary and secondary prompt of the interpreter. These
392 are only defined if the interpreter is in interactive mode. Their initial
393 values in this case are ``'>>> '`` and ``'... '``. If a non-string object is
394 assigned to either variable, its :func:`str` is re-evaluated each time the
395 interpreter prepares to read a new interactive command; this can be used to
396 implement a dynamic prompt.
397
398
399.. function:: setcheckinterval(interval)
400
401 Set the interpreter's "check interval". This integer value determines how often
402 the interpreter checks for periodic things such as thread switches and signal
403 handlers. The default is ``100``, meaning the check is performed every 100
404 Python virtual instructions. Setting it to a larger value may increase
405 performance for programs using threads. Setting it to a value ``<=`` 0 checks
406 every virtual instruction, maximizing responsiveness as well as overhead.
407
408
409.. function:: setdefaultencoding(name)
410
411 Set the current default string encoding used by the Unicode implementation. If
412 *name* does not match any available encoding, :exc:`LookupError` is raised.
413 This function is only intended to be used by the :mod:`site` module
414 implementation and, where needed, by :mod:`sitecustomize`. Once used by the
415 :mod:`site` module, it is removed from the :mod:`sys` module's namespace.
416
417 .. % Note that \refmodule{site} is not imported if
418 .. % the \programopt{-S} option is passed to the interpreter, in which
419 .. % case this function will remain available.
420
Georg Brandl116aa622007-08-15 14:28:22 +0000421
422.. function:: setdlopenflags(n)
423
424 Set the flags used by the interpreter for :cfunc:`dlopen` calls, such as when
425 the interpreter loads extension modules. Among other things, this will enable a
426 lazy resolving of symbols when importing a module, if called as
427 ``sys.setdlopenflags(0)``. To share symbols across extension modules, call as
428 ``sys.setdlopenflags(dl.RTLD_NOW | dl.RTLD_GLOBAL)``. Symbolic names for the
429 flag modules can be either found in the :mod:`dl` module, or in the :mod:`DLFCN`
430 module. If :mod:`DLFCN` is not available, it can be generated from
431 :file:`/usr/include/dlfcn.h` using the :program:`h2py` script. Availability:
432 Unix.
433
Georg Brandl116aa622007-08-15 14:28:22 +0000434
435.. function:: setprofile(profilefunc)
436
437 .. index::
438 single: profile function
439 single: profiler
440
441 Set the system's profile function, which allows you to implement a Python source
442 code profiler in Python. See chapter :ref:`profile` for more information on the
443 Python profiler. The system's profile function is called similarly to the
444 system's trace function (see :func:`settrace`), but it isn't called for each
445 executed line of code (only on call and return, but the return event is reported
446 even when an exception has been set). The function is thread-specific, but
447 there is no way for the profiler to know about context switches between threads,
448 so it does not make sense to use this in the presence of multiple threads. Also,
449 its return value is not used, so it can simply return ``None``.
450
451
452.. function:: setrecursionlimit(limit)
453
454 Set the maximum depth of the Python interpreter stack to *limit*. This limit
455 prevents infinite recursion from causing an overflow of the C stack and crashing
456 Python.
457
458 The highest possible limit is platform-dependent. A user may need to set the
459 limit higher when she has a program that requires deep recursion and a platform
460 that supports a higher limit. This should be done with care, because a too-high
461 limit can lead to a crash.
462
463
464.. function:: settrace(tracefunc)
465
466 .. index::
467 single: trace function
468 single: debugger
469
470 Set the system's trace function, which allows you to implement a Python
471 source code debugger in Python. See section :ref:`debugger-hooks` in the
472 chapter on the Python debugger. The function is thread-specific; for a
473 debugger to support multiple threads, it must be registered using
474 :func:`settrace` for each thread being debugged.
475
476 .. note::
477
478 The :func:`settrace` function is intended only for implementing debuggers,
479 profilers, coverage tools and the like. Its behavior is part of the
480 implementation platform, rather than part of the language definition, and thus
481 may not be available in all Python implementations.
482
483
484.. function:: settscdump(on_flag)
485
486 Activate dumping of VM measurements using the Pentium timestamp counter, if
487 *on_flag* is true. Deactivate these dumps if *on_flag* is off. The function is
488 available only if Python was compiled with :option:`--with-tsc`. To understand
489 the output of this dump, read :file:`Python/ceval.c` in the Python sources.
490
Georg Brandl116aa622007-08-15 14:28:22 +0000491
492.. data:: stdin
493 stdout
494 stderr
495
496 File objects corresponding to the interpreter's standard input, output and error
497 streams. ``stdin`` is used for all interpreter input except for scripts.
Georg Brandl6911e3c2007-09-04 07:15:32 +0000498 ``stdout`` is used for the output of :func:`print` and expression statements.
Georg Brandl116aa622007-08-15 14:28:22 +0000499 The interpreter's own prompts and (almost all of) its error messages go to
500 ``stderr``. ``stdout`` and ``stderr`` needn't be built-in file objects: any
501 object is acceptable as long as it has a :meth:`write` method that takes a
502 string argument. (Changing these objects doesn't affect the standard I/O
503 streams of processes executed by :func:`os.popen`, :func:`os.system` or the
504 :func:`exec\*` family of functions in the :mod:`os` module.)
505
506
507.. data:: __stdin__
508 __stdout__
509 __stderr__
510
511 These objects contain the original values of ``stdin``, ``stderr`` and
512 ``stdout`` at the start of the program. They are used during finalization, and
513 could be useful to restore the actual files to known working file objects in
514 case they have been overwritten with a broken object.
515
Christian Heimes58cb1b82007-11-13 02:19:40 +0000516 .. note::
517
518 Under some conditions ``stdin``, ``stdout`` and ``stderr`` as well as the
519 original values ``__stdin__``, ``__stdout__`` and ``__stderr__`` can be
520 None. It is usually the case for Windows GUI apps that aren't connected to
521 a console and Python apps started with :program:`pythonw`.
522
Georg Brandl116aa622007-08-15 14:28:22 +0000523
524.. data:: tracebacklimit
525
526 When this variable is set to an integer value, it determines the maximum number
527 of levels of traceback information printed when an unhandled exception occurs.
528 The default is ``1000``. When set to ``0`` or less, all traceback information
529 is suppressed and only the exception type and value are printed.
530
531
532.. data:: version
533
534 A string containing the version number of the Python interpreter plus additional
535 information on the build number and compiler used. It has a value of the form
536 ``'version (#build_number, build_date, build_time) [compiler]'``. The first
537 three characters are used to identify the version in the installation
538 directories (where appropriate on each platform). An example::
539
540 >>> import sys
541 >>> sys.version
542 '1.5.2 (#0 Apr 13 1999, 10:51:12) [MSC 32 bit (Intel)]'
543
544
545.. data:: api_version
546
547 The C API version for this interpreter. Programmers may find this useful when
548 debugging version conflicts between Python and extension modules.
549
Georg Brandl116aa622007-08-15 14:28:22 +0000550
551.. data:: version_info
552
553 A tuple containing the five components of the version number: *major*, *minor*,
554 *micro*, *releaselevel*, and *serial*. All values except *releaselevel* are
555 integers; the release level is ``'alpha'``, ``'beta'``, ``'candidate'``, or
556 ``'final'``. The ``version_info`` value corresponding to the Python version 2.0
557 is ``(2, 0, 0, 'final', 0)``.
558
Georg Brandl116aa622007-08-15 14:28:22 +0000559
560.. data:: warnoptions
561
562 This is an implementation detail of the warnings framework; do not modify this
563 value. Refer to the :mod:`warnings` module for more information on the warnings
564 framework.
565
566
567.. data:: winver
568
569 The version number used to form registry keys on Windows platforms. This is
570 stored as string resource 1000 in the Python DLL. The value is normally the
571 first three characters of :const:`version`. It is provided in the :mod:`sys`
572 module for informational purposes; modifying this value has no effect on the
573 registry keys used by Python. Availability: Windows.
574
575
576.. seealso::
577
578 Module :mod:`site`
579 This describes how to use .pth files to extend ``sys.path``.
580
Christian Heimes58cb1b82007-11-13 02:19:40 +0000581