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     """
  68     usage = """%prog: args
  69 
  70 Sometimes you might explain the purpose of this program as well.
  71 """
  72     
  73     parser = OptionParser(usage)
  74 
  75     # add_options takes at least one long option
  76     # you can optionally include a short option.
  77     # - are one character (short) options (e.g. -h)
  78     #
  79     # -- are long options, the name is also used as the 
  80     #    variable name attached that holds the option
  81 
  82     parser.add_option("-e", "--error", help="set error code")
  83 
  84     # opt_parse can be configured to store different kinds of values
  85     # like filenames, and boolean options
  86     parser.add_option("-b", "--bad-option", action="store_true",
  87                       help="trigger an option error")
  88     
  89     # you can also do simple type checking on parameters
  90     parser.add_option("-n", "--number", help="set a number", type="int")
  91 
  92     # if needed you can tell optparse to use a different variable name.
  93     # with the dest argument.
  94     parser.add_option("--index", dest="createRDSIndex", action="store_true")
  95 
  96     parser.set_defaults(bad_option=False, 
  97                         createRDSIndex=False,
  98                         error=None,                         
  99                         number=0)
 100 
 101     return parser
 102 
 103 
 104 if __name__ == "__main__":
 105     # this runs when the application is run from the command
 106     # it grabs sys.argv[1:] which is everything after the program name
 107     # and passes it to main
 108     # the return value from main is then used as the argument to
 109     # sys.exit, which you can test for in the shell.
 110     # program exit codes are usually 0 for ok, and non-zero for something
 111     # going wrong.
 112     sys.exit(main(sys.argv[1:]))
 113 
 114 # Try the following examples
 115 # python script_template.py
 116 # python script_template.py --help
 117 # ./script_template.py a b c
 118 # ./script_template.py --bad-option
 119 # python ./script_template.py -n 4
 120 # python ./script_template.py --number foo
 121 
 122 
 123 
 124 # Guido von Rossum (inventor of python) has this write up on how to
 125 # write a main
 126 # http://www.artima.com/weblogs/viewpost.jsp?thread=4829
 127 # however he used the older getopt module which isn't as easy
 128 # to configure as optparse