Optparse is a Python module that allows programmers to easily design a simple, easy-to-use, standard-compliant UNIX command-list program. Generate usage and help information.
The following is a simple example:
Import Optparse
Parser =Optparse. Optionparser () parser.add_option ("- F", "--file", Dest="filename", Help="write report to FILE", Metavar="FILE") 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 (args)
Now you can enter the following command to test:
# Display Help information <yourscript>-H<yourscript>--Assist# Test < yourscript>--file=outfile-q<yourscript> f outfile--quiet<yourscript>--quiet-- file outfile<yourscript> Q-foutfile<yourscript>-qfoutfile
You can also specify that the type parameter in the Add_option () method is a different value, such as int or float, and so on:
Parser.add_option ("-n", type="int", dest="num ")
This option does not have a long option, and the long option is optional, and if you do not specify the DEST option, the value of the options object is accessed using the command-line parameter name. The store also has two other forms: Stort_true and Store_false, which handle cases with no values after command-line options, such as command-line arguments such as-v,-q
Parser.add_option ("-v", action="store_true", dest=" verbose") parser.add_option ("-Q", action=" store_false", dest="verbose")
In this case, when parsing to '-V ', the options.verbose will be given a True value, and conversely, parsing to '-Q ' will be given a value of False.
Other actions are: Store_const, append, Count, callback
Setting the Metavar parameter in the Add_option method helps remind the user of the parameters that the command-line argument expects, such as metavar= "mode":
Parser.add_option ("-M", dest="Modevar", metavar="mode ")
Use%default to insert the default value of the command-line parameter in the Help information for the assist parameter.
If your program has a lot of command-line arguments, you might want to group them, and you can useOptionGroup:
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)
Python module Optparse