4366
Comment:
|
4972
|
Deletions are marked like this. | Additions are marked like this. |
Line 13: | Line 13: |
Line 31: | Line 30: |
import os | |
Line 57: | Line 57: |
elif opts.make_template: make_template() return 0 |
|
Line 72: | Line 75: |
Line 100: | Line 104: |
parser.add_option("--make-template", action="store_true", help="print a simplified template") |
|
Line 102: | Line 108: |
error=None, | error=None, make_template=False, |
Line 107: | Line 114: |
def make_template(): """Read current source file and print a version with no comments |
|
Line 108: | Line 117: |
run like: $ script.py --make-template > my_program.py """ import re source = open( __file__,'r' ) for line in source: # include the starting #!, but remove comments if not re.match(" *#[^!]", line): sys.stdout.write(line) |
|
Line 125: | Line 144: |
# # |
|
Line 133: | Line 151: |
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 """Module summary
9
10 If you import this module and do help (module) you'll see this.
11 The first line of a docstring is the "summary", and should be
12 a one line description.
13
14 You can go into more detail after the summary if needed.
15 See http://www.python.org/dev/peps/pep-0257/
16 for the python docstring style guide.
17 """
18
19 # optparse is both easy to use and produces clean code
20 # the main optparse docs can be found here:
21 # http://docs.python.org/library/optparse.html
22 # there's a much better tutorial that works you through optparse
23 # starting with a simple example and slowly adding complexity.
24 from optparse import OptionParser
25 import os
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 elif opts.make_template:
53 make_template()
54 return 0
55
56 # args is now just a list, of everything that wasn't an
57 # "option". AKA everything that started with - or --
58 for i in range(len(args)):
59 print "arg %d: %s" % (i, args[i])
60
61 print "the number is:", opts.number
62 # opts.number is always defined, as I set a default value
63 # up in the make_parser
64
65 return 0
66
67
68 def make_parser():
69 """Construct an option parser"""
70
71 usage = """%prog: args
72
73 Sometimes you might explain the purpose of this program as well.
74 """
75
76 parser = OptionParser(usage)
77
78 # add_options takes at least one long option
79 # you can optionally include a short option.
80 # - are one character (short) options (e.g. -h)
81 #
82 # -- are long options, the name is also used as the
83 # variable name attached that holds the option
84
85 parser.add_option("-e", "--error", help="set error code")
86
87 # opt_parse can be configured to store different kinds of values
88 # like filenames, and boolean options
89 parser.add_option("-b", "--bad-option", action="store_true",
90 help="trigger an option error")
91
92 # you can also do simple type checking on parameters
93 parser.add_option("-n", "--number", help="set a number", type="int")
94
95 # if needed you can tell optparse to use a different variable name.
96 # with the dest argument.
97 parser.add_option("--index", dest="createRDSIndex", action="store_true")
98
99 parser.add_option("--make-template", action="store_true",
100 help="print a simplified template")
101 parser.set_defaults(bad_option=False,
102 createRDSIndex=False,
103 error=None,
104 make_template=False,
105 number=0)
106
107 return parser
108
109 def make_template():
110 """Read current source file and print a version with no comments
111
112 run like:
113 $ script.py --make-template > my_program.py
114 """
115 import re
116 source = open( __file__,'r' )
117 for line in source:
118 # include the starting #!, but remove comments
119 if not re.match(" *#[^!]", line):
120 sys.stdout.write(line)
121
122 if __name__ == "__main__":
123 # this runs when the application is run from the command
124 # it grabs sys.argv[1:] which is everything after the program name
125 # and passes it to main
126 # the return value from main is then used as the argument to
127 # sys.exit, which you can test for in the shell.
128 # program exit codes are usually 0 for ok, and non-zero for something
129 # going wrong.
130 sys.exit(main(sys.argv[1:]))
131
132 # Try the following examples
133 # python script_template.py
134 # python script_template.py --help
135 # ./script_template.py a b c
136 # ./script_template.py --bad-option
137 # python ./script_template.py -n 4
138 # python ./script_template.py --number foo
139 #
140 #
141 # Guido von Rossum (inventor of python) has this write up on how to
142 # write a main
143 # http://www.artima.com/weblogs/viewpost.jsp?thread=4829
144 # however he used the older getopt module which isn't as easy
145 # to configure as optparse