2011/07/02

Usage of optparse

Sample code for optparse [sample_code.py]

from optparse import OptionParser

def main():
usage = "usage: %prog [options] something"
parser = OptionParser(usage)

parser.add_option("-f", "--file",
default=None, dest="filename",
help="read data from FILENAME")

parser.add_option("-v", "--verbose",
default=True, action="store_true", dest="verbose",
help="verbose output")

(options, args) = parser.parse_args()

if len(args) != 1:
parser.error("incorrect number of arguments")

if options.verbose:
print "reading %s..." % options.filename

print options.verbose
print options.filename

if __name__ == "__main__":
main()


Testing above sample code
# python sample_code.py something
reading None...
True
None

No comments:

Post a Comment

100