co89757
6/25/2016 - 4:55 AM

parsing command line options with optparse

parsing command line options with optparse

#!/usr/bin/python
# -*- coding: utf-8 -*-

from optparse import OptionParser 
## parser.add_option('<short-hand>', "<long-hand>", dest = <binding attribute>, type=<type>, action=<action>, default=<default_value> )
## four most important option attributes:
# action("store"(default), 'store_false/true' (setting boolean flag), 'store_const', 'append' (append this opt's arg to a list), 'callback' (invoke a callback function) ), 
# type ("string","int",'float',... )
# dest (the attribute name of parsed options object)
# help (help string for this option)
# If you don’t supply a destination, optparse figures out a sensible default from the option strings: 
# if the first long option string is --foo-bar, then the default destination is foo_bar.
# If there are no long option strings, optparse looks at the first short option string: the default destination for -f is f.
# 
# Default values for options can be set by default parameter for each add_option() call 
# use OptionParser.error(<msg>) to raise user-input errors 
def clitool():
    usage = "USAGE: %prog [options] arg1 arg2" 
    parser = OptionParser(usage=usage)
    # parser.set_defaults(<flag>=<default>...)

    parser.add_option("-f","--file" )

def sample_command():
    usage = "usage: %prog [options] arg"
    parser = OptionParser(usage)
    parser.add_option("-f", "--file", dest="filename",
                      help="read data from FILENAME")
    parser.add_option("-v", "--verbose",
                      action="store_true", dest="verbose")
    parser.add_option("-q", "--quiet",
                      action="store_false", dest="verbose")
    ...
    (options, args) = parser.parse_args()
    if len(args) != 1:
        parser.error("incorrect number of arguments")
    if options.verbose:
        print "reading %s..." % options.filename
    # ... all the logic to deal with options and args

if __name__ == "__main__":
    main()