This represents our best thinking about how to start your python script.
(Though you probably want to remove the excess comments).
1 #!/usr/bin/env python
2
3 # #!/usr/bin/env python - will search for the first python
4 # interpreter on your path
5 # unlike
6 # #!/usr/bin/python2.5 - which will only run if there is a file
7 # python 2.5 is installed at /usr/bin
8
9 """
10 Module doc string
11
12 if you import this module and do help (module) you'll see this
13
14 """
15 # optparse is both easy to use and produces clean code
16 # the main optparse docs can be found here:
17 # http://docs.python.org/library/optparse.html
18 # there's a much better tutorial that works you through optparse
19 # starting with a simple example and slowly adding complexity.
20 from optparse import OptionParser
21 import sys
22
23
24 # I like to make a separate function to configure the option parser
25 # I like my functions to fit with-in a single screen-full)
26
27 def make_parser():
28 """
29 Construct an option parser
30 """
31 usage = """%prog: args
32
33 this describes how to use the program
34 """
35
36 parser = OptionParser(usage)
37
38 # add_options usually takes two options, you can skip the
39 # - are one character (short) options (e.g. -h)
40 #
41 # -- are long options, the name is also used as the
42 # variable name attached that holds the option
43
44 parser.add_option('-e', '--error', help="set error code")
45
46 # opt_parse can be configured to store different kinds of values
47 # like filenames, and boolean options
48 parser.add_option('-b', '--bad-option', action="store_true",
49 help='trigger an option error')
50
51 # you can also do simple type checking on parameters
52 parser.add_option('-n', '--number', help="set a number", type="int")
53 parser.set_defaults(error=None,
54 bad_option=False,
55 number=0)
56
57 return parser
58
59 def main(cmdline=None):
60 """
61 Example main function.
62
63 If cmdline is none, parser.parse_args will look at
64 sys.argv[1:] by default
65
66 However if import this module in python call this main function
67 like this:
68
69 main(['-n', '3', 'asdf', 'jkl'])
70
71 in addition to running it from the shell.
72 """
73 parser = make_parser()
74
75 opts, args = parser.parse_args(cmdline)
76
77 if opts.error is not None:
78 return opts.error
79 elif opts.bad_option:
80 # you can call parser.error, which will show an error message
81 # displays the help, and then exits the program
82 parser.error("you called a bad option")
83
84 # args is now just a list, of everything that wasn't an
85 # "option". AKA everything that started with - or --
86 for i in range(len(args)):
87 print "arg %d: %s" % (i, args[i])
88
89 print "the number is:", opts.number
90 # opts.number is always defined, as I set a default value
91 # up in the make_parser
92
93 return 0
94
95 if __name__ == "__main__":
96 # this runs when the application is run from the command
97 # it grabs sys.argv[1:] which is everything after the program name
98 # and passes it to main
99 # the return value from main is then used as the argument to
100 # sys.exit, which you can test for in the shell.
101 # program exit codes are usually 0 for ok, and non-zero for something
102 # going wrong.
103 sys.exit(main(sys.argv[1:]))
104
105 # Try the following examples
106 # python script_template.py
107 # python script_template.py --help
108 # ./script_template.py a b c
109 # ./script_template.py --bad-option
110 # python ./script_template.py -n 4
111 # python ./script_template.py --number foo
112
113
114
115 # Guido von Rossum (inventor of python) has this write up on how to
116 # write a main
117 # http://www.artima.com/weblogs/viewpost.jsp?thread=4829
118 # however he used the older getopt module which isn't as easy
119 # to configure as optparse