This represents our best thinking about how to start your python script.

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