The Python command line parameter parsing module optparse USES instances

  • 2020-05-09 18:45:01
  • OfStack

The sample


from optparse import OptionParser
[...]
def main():
    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
    [...] if __name__ == "__main__":
    main()

Add options (add_option())

OptionParser.add_option(option)
OptionParser.add_option(*opt_str, attr=value, ...)

Define short options

parser.add_option( " -f " , attr=value, ... )

Define long options

parser.add_option( "� foo " , attr=value, ... )

If you define

​parser.add_option("-f", "--file", action="store", type="string", dest="filename")

The command line format can take the following forms

-ffoo
-f foo
--file=foo
--file foo

Parsed result

options.filename = " foo "

Resolution (parse_args ())

(options, args) = parser.parse_args()

Parameters parsed by options are saved in dictionary form
Parameters that args cannot parse are saved as a list

Behavior (action)

●store default behavior, save the value to dest
● "store_const" holds the constant
● "append" append this option's argument to a list
● "count" increment a counter by one
● "callback" call a specified function

Set the default value (default)


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

Generate help tips (help)

Just provide the help option and you can print it out with parser.print_help ()


parser.add_option( " -f " , "� file " , dest= " filename " ,help= " write report to FILE " , metavar= " FILE " )

Setting boolean value

store_true and store_false are supported


parser.add_option("-v", action="store_true", dest="verbose")
parser.add_option("-q", action="store_false", dest="verbose")

If you encounter -v,verbose=True; If you encounter -q,verbose=False

Error handling


(options, args) = parser.parse_args()
[...]
if options.a and options.b:
    parser.error("options -a and -b are mutually exclusive")

Option group (Grouping Options)

Format is as follows

class optparse.OptionGroup(parser, title, description=None)


group = OptionGroup(parser, "Dangerous Options",
                    "Caution: use these options at your own risk.  "
                    "It is believed that some of them bite.")
group.add_option("-g", action="store_true", help="Group option.")
parser.add_option_group(group)

The results are as follows

Usage: <yourscript> [options] arg1 arg2 Options:
  -h, --help            show this help message and exit
  -v, --verbose         make lots of noise [default]
  -q, --quiet           be vewwy quiet (I'm hunting wabbits)
  -f FILE, --filename=FILE
                        write output to FILE
  -m MODE, --mode=MODE  interaction mode: novice, intermediate, or
                        expert [default: intermediate]   Dangerous Options:
    Caution: use these options at your own risk.  It is believed that some
    of them bite.     -g                  Group option.


Related articles: