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