The sys Module
The sys module provides a number of functions and variables that can be
used to manipulate different parts of the Python runtime environment.
Working with Command-line Arguments
The argv list contains the arguments that were passed to the
script, when the interpreter was started, as shown in Example 1-66. The first item contains the
name of the script itself.
Example 1-66. Using the sys Module to Get Script Arguments
File: sys-argv-example-1.py
import sys
print "script name is", sys.argv[0]
if len(sys.argv) > 1:
print "there are", len(sys.argv)-1, "arguments:"
for arg in sys.argv[1:]:
print arg
else:
print "there are no arguments!"
script name is sys-argv-example-1.py
there are no arguments!If you read the script from standard input (like
“python < sys-argv-example-1.py”),
the script name is set to an empty string. If you pass in the program
as a string (using the -c option), the script name
is set to “-c.”
Working with Modules
The path list contains a list of directory names
in which Python looks for extension modules (Python source modules,
compiled modules, or binary extensions). When you start Python, this
list is initialized from a mixture of built-in rules, the contents of
the PYTHONPATH environment variable, and the
registry contents (on Windows). But since it’s an ordinary list, you
can also manipulate it from within the program, as Example 1-67 shows.
Example 1-67. Using the sys Module to Manipulate the Module Search Path
File: sys-path-example-1.py import ...