It happens quite often that you need to pass a variable to a program. You have to use the sys module. It tells you about all the input variables including the file name itself. A simple program is the following:
——————————————————————
import sys
if len(sys.argv) < 2:
print “Usage: script.py <number>”
sys.exit(0)
try:
numeric_arg = int(sys.argv[1])
except:
print ‘1st argument must be numeric.’
sys.exit(0)
if len(sys.argv) == 2:
print “The input number is”, int(sys.argv[1])
sys.exit(0)
———————————————————————
When you run it, the output is like this:
$ python file.py
Usage: script.py <number>
$ python file.py 5
The input number is 5
There are many things more that you can do with sys. For instance, it tells you the library search path. Python looks in several places when you try to import a module. Specifically, it looks in all the directories defined in sys.path
. This is just a list, and you can easily view it or modify :
>>> import sys
>>> sys.path
[”, ‘/usr/lib/python2.5’, ‘/usr/lib/python2.5/plat-linux2’, …..]
Leave a comment