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 that affect the interpreter directly. This section documents the most frequently used attributes of sys, in alphabetical order.

argv

The list of command-line arguments passed to the main script. argv[0] is the name or full path of the main script, or '-c' if the -c option was used. See Section 8.4 later in this chapter for a good way to use sys.argv.

displayhook

displayhook(value)

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
    print repr(value)

You can rebind sys.displayhook in order to change interactive behavior. The original value is available as sys._ _displayhook_ _.

excepthook

excepthook(type,value,traceback)

When an exception is not caught by any handler, Python calls excepthook, passing it the exception class, exception object, and traceback object, as covered in Chapter 6. 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 also available as sys._ _excepthook_ _.

exc_info

exc_info(  )

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 has to retain in memory data that might otherwise be garbage-collected. So you should 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 Chapter 6).

exit

exit(arg=0)

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).

getdefaultencoding

getdefaultencoding(  )

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 Chapter 9.

getrefcount

getrefcount(object)

Returns the reference count of object. Reference counts are covered in Section 13.4.

getrecursionlimit

getrecursionlimit(  )

Returns the current limit on the depth of Python's call stack. See also Section 4.10.9 and setrecursionlimit in this section.

_getframe

_getframe(depth=0)

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 for internal specialized purposes. Chapter 17 covers ways in which you can use frame objects for debugging.

maxint

The largest integer in this version of Python (at least 2147483647). Negative integers can go down to -maxint-1, due to 2's complement notation.

modules

A dictionary whose items are the names and module objects for all loaded modules. See Chapter 7 for more information on sys.modules.

path

A list of strings that specifies the directories that Python searches when looking for a module to load. See Chapter 7 for more information on sys.path.

platform

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, ps2

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 non-string object, Python prompts by calling str( ) 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.

setdefaultencoding

setdefaultencoding(name)

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 during startup; the site module removes this attribute from sys. You can call reload(sys) to make this attribute available again, but this is not considered good programming practice. Unicode, codecs, encoding, and decoding are covered in Chapter 9. The site and sitecustomize modules are covered in Chapter 13.

setprofile

setprofile(profilefunc)

Sets a global profile function, a callable object that Python then calls at each function entry and return. Profiling is covered in Chapter 17.

setrecursionlimit

setrecursionlimit(limit)

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. Lowering the limit may help you check, during debugging, that your program is gracefully degrading under situations of almost-runaway recursion. See also Section 4.10.9.

settrace

settrace(tracefunc)

Sets a global trace function, a callable object that Python then calls as each logical source line executes. Chapter 17 covers tracing.

stdin, stdout, stderr

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 accepting 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_ _. Chapter 10 covers file objects and streams.

tracebacklimit

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 less than or equal to 0, traceback information is suppressed and only the exception type and value are printed.

version

A string that describes the Python version, build number and date, and C compiler used. version[:3] is '2.1' for Python 2.1, '2.2' for 2.2, and so on.



    Part III: Python Library and Extension Modules