8.3. The sys Module
The attributes of the sys module are bound to data and functions that provide information on the state of the Python interpreter or affect the interpreter directly. This section documents the most frequently used attributes of sys, in alphabetical order.
The list of command-line arguments passed to the main script. argv is the name or full path of the main script, or '-c' if the -c option was used. See "The optparse Module" on page 179 for a good way to use sys.argv.
In interactive sessions, the Python interpreter calls displayhook, passing it the result of each expression statement entered. The default displayhook does nothing if value is None; otherwise, it preserves and displays value:
if value is not None:
_ _builtin_ _._ = value
You can rebind sys.displayhook
in order to change interactive behavior. The original value is available as sys._ _displayhook_ _.
When an exception is not caught by any handler, and thus propagates all the way up the call stack, Python calls excepthook, passing it the exception class, exception object, and traceback object, as covered in "Exception Propagation" on page 126. The default excepthook displays the error and traceback. You can rebind sys.excepthook to change what is displayed for uncaught exceptions (just before Python returns to the interactive loop or terminates). The original value is available as sys._ _excepthook_ _.
If the current thread is handling an exception, exc_info returns a tuple whose three items are the class, object, and traceback for the exception. If the current thread is not handling any exception, exc_info returns (None,None,None). A traceback object indirectly holds references to all variables of all functions that propagated the exception. Thus, if you hold a reference to the traceback object (for example, indirectly, by binding a variable to the whole tuple that exc_info returns), Python must retain in memory data that might otherwise be garbage-collected; so make sure that any binding to the traceback object is of short duration. To ensure that the binding gets removed, you can use a try/finally statement (discussed in "try/finally" on page 123). To print information from a traceback object, see "The traceback Module" on page 466.
Raises a SystemExit exception, which normally terminates execution after executing cleanup handlers installed by try/finally statements. If arg is an integer, Python uses arg as the program's exit code: 0 indicates successful termination, while any other value indicates unsuccessful termination of the program. Most platforms require exit codes to be between 0 and 127. If arg is not an integer, Python prints arg to sys.stderr, and the exit code of the program is 1 (i.e., a generic unsuccessful termination code).
Returns the name of the default codec used to encode and decode Unicode and string objects (normally 'ascii'). Unicode, codecs, encoding, and decoding are covered in "Unicode" on page 198.
Returns the reference count of object. Reference counts are covered in "Garbage Collection" on page 332.
Returns the current limit on the depth of Python's call stack. See also "Recursion" on page 80 and setrecursionlimit on page 171.
Returns a frame object from the call stack. When depth is 0, the result is the frame of _getframe's caller. When depth is 1, the result is the frame of the caller's caller, and so forth. The leading _ in _getframe's name is a reminder that it's a private system function to be used only for internal specialized purposes. Debugging, covered in "Debugging" on page 461, is a typical, good reason to use _getframe.
The largest int in this version of Python (at least 2**31, that is, 2147483647). Negative ints can go down to -maxint-1, due to 2's complement notation.
A dictionary whose items are the names and module objects for all loaded modules. See "Module Loading" on page 144 for more information on sys.modules.
A list of strings that specifies the directories and ZIP files that Python searches when looking for a module to load. See "Searching the Filesystem for a Module" on page 144 for more information on sys.path.
A string that names the platform on which this program is running. Typical values are brief operating system names, such as 'sunos5', 'linux2', and 'win32'.
ps1 and ps2 specify the primary and secondary interpreter prompt strings, initially '>>> ' and '... ', respectively. These attributes exist only in interactive interpreter sessions. If you bind either attribute to a nonstring object x, Python prompts by calling str(x) on the object each time a prompt is output. This feature lets you create dynamic prompting by coding a class that defines _ _str_ _ and assigning an instance of that class to sys.ps1 and/or sys.ps2. For example, to get numbered prompts:
>>> import sys
>>> class Ps1(object):
... def _ _init_ _(self):
... self.p = 0
... def _ _str_ _(self):
... self.p += 1
... return '[%d]>>> ' % self.p
>>> class Ps2(object):
... def _ _str_ _(self):
... return '[%d]... ' % sys.ps1.p
>>> sys.ps1 = Ps1( ); sys.ps2 = Ps2( )
>>> (2 +
Sets the default codec used to encode and decode Unicode and string objects (normally 'ascii'). setdefaultencoding is meant to be called only from sitecustomize.py at program startup; the site module then removes this attribute from sys. You can call reload(sys) to make this attribute available again, but this is not a good programming practice. Unicode, codecs, encoding, and decoding are covered in "Unicode" on page 198. The site and sitecustomize modules are covered in "The site and sitecustomize Modules" on page 338.
Sets a global profile function, a callable object that Python then calls at each function entry and return. Profiling is covered in "Profiling" on page 480.
Sets the limit on the depth of Python's call stack (the default is 1000). The limit prevents runaway recursion from crashing Python. Raising the limit may be necessary for programs that rely on deep recursion, but most platforms cannot support very large limits on call-stack depth. More usefully, lowering the limit may help you check, during testing and debugging, that your program is gracefully degrading, rather than abruptly crashing, under situations of almost-runaway recursion. See also "Recursion" on page 80 and getrecursionlimit on page 169.
Sets a global trace function, a callable object that Python then calls as each logical source line executes. settrace is meant to be used for implementing tools such as profilers, coverage analyzers, and debuggers. I do not cover tracing further in this book.
stdin, stdout, and stderr are predefined file objects that correspond to Python's standard input, output, and error streams. You can rebind stdout and stderr to file-like objects (objects that supply a write method that accepts a string argument) to redirect the destination of output and error messages. You can rebind stdin to a file-like object open for reading (one that supplies a readline method returning a string) to redirect the source from which built-in functions raw_input and input read. The original values are available as _ _stdin_ _, _ _stdout_ _, and _ _stderr_ _. File objects are covered in "File Objects" on page 216.
The maximum number of levels of traceback displayed for unhandled exceptions. By default, this attribute is not set (i.e., there is no limit). When sys.tracebacklimit is <=0, Python suppresses traceback and prints only the exception type and value.
A string that describes the Python version, build number and date, and C compiler used. version[:3] is '2.3' for Python 2.3, '2.4' for Python 2.4, and so on.