Example
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 ()ifLen (args)! =1: Parser.error ("Incorrect number of arguments")ifOptions.verbose:print"Reading%s ..."% Options.filename [...]if__name__ = ="__main__": Main ()
Add option (Add_option ())
...)
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 have the following form
-ffoo-f foo--file=foo--file foo
Results after parsing
Options.filename = "Foo"
Parsing (Parse_args ())
(options, args) = Parser.parse_args ()
Options parsed parameters, saved in dictionary form
Args cannot parse parameters, save as a list
Behavior (Action)
Store default behavior, save value to Dest
"Store_const" Saving constants
"Append" append this option ' s argument to a list
"Count" increment a counter by one
"Callback" call a specified function
Set defaults (default)
parser.add_option("-v", action="store_true", dest="verbose"default=True)parser.set_defaults(verbose=True)
Generate Help Tips
The Help option is available and can be printed with parser.print_help ()
Parser.add_option ("-F", "–file", dest= "filename", help= "write report to File", metavar= "file")
Set a Boolean value
Supports Store_true and store_false two behaviors
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)
The format is as follows
Class Optparse. OptionGroup (parser, title, Description=none)
group"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 prompt results are as follows
Usage:<yourscript> [options] arg1 arg2Options:-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.
Python's command parsing module optparse