The sys Module

The sys module provides access to some objects used or maintained by the interpreter and to functions that interact strongly with the interpreter.

The sys module also provides the three standard files used by Python.

sys.stdin

Standard input file object; used by raw_input and input. Also available via sys.stdin.read() and related methods of the file object.

sys.stdout

Standard output file object; used by the print statement. Also available via sys.stdout.write() and related methods of the file object.

sys.stderr

Standard error object; used for error messages, typically unhandled exceptions. Available via sys.stderr.write() and related methods of the file object.

A program can assign another file object to one of these global variables. When you change the file for these globals, this will redirect all of the interpreter's I/O.

One important object made available by this module is the variable sys.argv. This variable has the command line arguments used to run this script. For example, if we had a python script called portfolio.py, and executed it with the following command:

python portfolio.py -xvb display.csv

Then the sys.argv list would be ["portfolio.py", "-xvb", "display.csv"]. Sophisticated argument processing is done with the getopt or optparse modules.

A few other interesting objects in the sys module are the following variables.

sys.version

The version of this interpreter as a string. For example, '2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)]'

sys.version_info

Version information as a tuple, for example: (2, 5, 1, 'final', 0).

sys.hexversion

Version information encoded as a single integer. Evaluating hex(sys.hexversion) yields '0x20501f0'.

sys.copyright

Copyright notice pertaining to this interpreter.

sys.platform

Platform identifier, for example, 'darwin', 'win32' or 'linux2'.

sys.prefix

Prefix used to find the Python library, for example '/usr', '/Library/Frameworks/Python.framework/Versions/2.5', 'c:\\Python25'.