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 """Module summary
10
11 If you import this module and do help (module) you'll see this.
12 The first line of a docstring is the "summary", and should be
13 a one line description.
14
15 You can go into more detail after the summary if needed.
16 See http://www.python.org/dev/peps/pep-0257/
17 for the python docstring style guide.
18 """
19
20 # optparse is both easy to use and produces clean code
21 # the main optparse docs can be found here:
22 # http://docs.python.org/library/optparse.html
23 # there's a much better tutorial that works you through optparse
24 # starting with a simple example and slowly adding complexity.
25 from optparse import OptionParser
26 import sys
27
28
29 def main(cmdline=None):
30 """Example main function.
31
32 If cmdline is none, parser.parse_args will look at
33 sys.argv[1:] by default
34
35 However if import this module in python call this main function
36 like this:
37
38 main(["-n", "3", "asdf", "jkl"])
39
40 in addition to running it from the shell.
41 """
42 parser = make_parser()
43
44 opts, args = parser.parse_args(cmdline)
45
46 if opts.error is not None:
47 return opts.error
48 elif opts.bad_option:
49 # you can call parser.error, which will show an error message
50 # displays the help, and then exits the program
51 parser.error("you called a bad option")
52
53 # args is now just a list, of everything that wasn't an
54 # "option". AKA everything that started with - or --
55 for i in range(len(args)):
56 print "arg %d: %s" % (i, args[i])
57
58 print "the number is:", opts.number
59 # opts.number is always defined, as I set a default value
60 # up in the make_parser
61
62 return 0
63
64
65 def make_parser():
66 """Construct an option parser"""
67 usage = """%prog: args
68
69 Sometimes you might explain the purpose of this program as well.
70 """
71
72 parser = OptionParser(usage)
73
74 # add_options takes at least one long option
75 # you can optionally include a short option.
76 # - are one character (short) options (e.g. -h)
77 #
78 # -- are long options, the name is also used as the
79 # variable name attached that holds the option
80
81 parser.add_option("-e", "--error", help="set error code")
82
83 # opt_parse can be configured to store different kinds of values
84 # like filenames, and boolean options
85 parser.add_option("-b", "--bad-option", action="store_true",
86 help="trigger an option error")
87
88 # you can also do simple type checking on parameters
89 parser.add_option("-n", "--number", help="set a number", type="int")
90
91 # if needed you can tell optparse to use a different variable name.
92 # with the dest argument.
93 parser.add_option("--index", dest="createRDSIndex", action="store_true")
94
95 parser.set_defaults(bad_option=False,
96 createRDSIndex=False,
97 error=None,
98 number=0)
99
100 return parser
101
102
103 if __name__ == "__main__":
104 # this runs when the application is run from the command
105 # it grabs sys.argv[1:] which is everything after the program name
106 # and passes it to main
107 # the return value from main is then used as the argument to
108 # sys.exit, which you can test for in the shell.
109 # program exit codes are usually 0 for ok, and non-zero for something
110 # going wrong.
111 sys.exit(main(sys.argv[1:]))
112
113 # Try the following examples
114 # python script_template.py
115 # python script_template.py --help
116 # ./script_template.py a b c
117 # ./script_template.py --bad-option
118 # python ./script_template.py -n 4
119 # python ./script_template.py --number foo
120
121
122
123 # Guido von Rossum (inventor of python) has this write up on how to
124 # write a main
125 # http://www.artima.com/weblogs/viewpost.jsp?thread=4829
126 # however he used the older getopt module which isn't as easy
127 # to configure as optparse