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