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