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