|I l@ve RuBoard|
The sys module contains several functions and attributes internal to Python; sys in this case means Python system, not operating system. Some of the most useful attributes are:
A list containing the directories Python looks into when doing imports.
A dictionary of the modules that have been loaded in the current session.
A string referring to the current platform. Its possible values include 'win32', 'mac', 'osf1', 'linux-i386', 'sunos4', etc. It's sometimes useful to check the value of sys.platform when doing platform-specific things (such as starting a window manager).
Two printable objects, used by Python in the interactive interpreter as the primary and secondary prompts. Their default values are ... and >>> . You can set them to strings or to instances of classes that define a __repr_ _ method.
One of the most frequently used attributes of the sys module is sys.argv, a list of the words input on the command line, excluding the reference to Python itself if it exists. In other words, if you type at the shell:
csh> python run.py a x=3 foo
then when run.py starts, the value of the sys.argv attribute is ['run.py', 'a', 'x=3', 'foo']. The sys.argv attribute is mutable (after all, it's just a list). Common usage involves iterating over the arguments of the Python program, that is, sys.argv[1:]; slicing from index 1 till the end gives all of the arguments to the program itself, but doesn't include the name of the program (module) stored in sys.argv.
Finally, there are three file attributes in the sys module: sys.stdin, sys.stdout, and sys.stderr. They are references to the standard input, output, and error streams respectively. Standard input is generally associated by the operating system with the user's keyboard; standard output and standard error are usually associated with the console. The print statement in Python outputs to standard output (sys.stdout), while error messages such as exceptions are output on the standard error stream (sys.stderr). Finally, as we'll see in an example, these are mutable attributes: you can redirect output of a Python program to a file simply by assigning to sys.stdout:
sys.stdout = open('log.out', 'w')
|I l@ve RuBoard|