python optparse example

September 25th, 2008 by webstersprodigy

This is a short commented optparse example

#!/usr/bin/env python

from optparse import OptionParser

#action, type, dest (destination), and help, default

#can optionally pass usage in here as a string
parser = OptionParser()
#notice the first arguments are a list - they define the synonomous commands
#destination is the most important - it is what your file is

#help is for the --help options
parser.add_option("-f", "--file", dest="filename",
                  help="write report to FILE", metavar="FILE")

#action store_true and store_false are common - they can be used for boolean flags
# other actions include store_const, append, count, callback
parser.add_option("-q", "--quiet",
                  action="store_false", dest="verbose", default=True,
                  help="don't print status messages to stdout")

(options, args) = parser.parse_args()

print options
print options.filename

Tags:

Leave a Reply


No computers were harmed in the 0.195 seconds it took to produce this page.