The usage of the Python optparse module is detailed

Source: Internet
Author: User

A brief introduction to the Optparse module

Python has two built-in modules for handling command-line arguments:
One is that getopt can only handle command-line arguments easily;
The other is Optparse, which is powerful and easy to use, and makes it easy to generate standard, UNIX/POSIX-compliant command-line instructions. will automatically take care of the-H help option for you.

To customize the parameters of the program control, you can use the Python optparse module, of course, can also directly parse the parameters in the SYS.ARGV (but this is more troublesome)

Import Optparseoptparse is now no longer updated, the updated version is called Argparse.import Argparse

  

Optparse supports option methods for general gun, including:

No entry,-V has a candidacy,-p value,–para=value value,-pvalue (not supported long parameter) merge option,-ABC,-abcp value (last one can be a parameter, the rest is not a parameter)

Parsing time-and-difference:

-Just look at the value behind, if there is no argument, then continue to read the next; If there is a reference, read the parameters (delimited or integrated).--Directly read the value behind;

  

Optparse modlue Basic Usage one, basic usage
1, Load Optionparser class, new object: Optionparser () 2, add option: add_option (...) 3, parameter resolution: Parse_args ()

As an example:

# _*_ coding:utf-8 _*_ import optparsefrom optparse import optionparser# a Help document explaining string hstr = '%prog custom Help string ' Pars ER = Optionparser (hstr, description= ' custom description ', version= '%prog 1.0 ') #通过OptionParser类创建parser实例, initial parameter in usage %prog is equivalent to Os.path.basename (Sys.argv[0]), which is the name of the script that you are currently running, and the version parameter is used to display the versions of the current script. "' Add parameters,-F 、--file is the long and short options, one can. dest= ' user ' saves the parameter entered by the user to the variable, and can be options.user to get the value action to indicate how the value after option is handled, such as: xxx.py-f Test.txt after Parser.parse_args () processing, the value of Test.txt is stored in an object represented by-F, which defines the dest in-f as Option.filename = ' test.txt ' The common options for action are store_true,store_false, and so on, which are typically used in Boolean-valued options. Metavar is only useful in display help, such as when displaying Help:-F FILE,--filename=file write output to file-m MODE,--mode=mode interaction Mode:novic E, intermediate, or expert [default:intermediate] If-f is not a METAVR parameter, it will be shown as-f FILENAME--filename =filename, the value of dest is displayed Defalut is the default value of an option, and when the script is called, the default value for the defaults is used when the parameter does not have a value specified. ' Parser.add_option ('-I ', '--input ', action= ' store ', dest= ' input ', help= ' read input data froM input file ') parser.add_option ('-O ', '--output ', action= ' store ', dest= ' output ', help= ' write data to output file ') parser . add_option ('-Q ', '--quite ', action= ' store_false ', dest= ' version ', help= ' don\ ' t print the version ') # Parser.add_option ('-V ', '--version ', action= ' store_true ', dest= ' version ', Default=false, help= ' Print the Version ') # parser.add_option (' -V ', '--version ', action= ' store_true ', dest= ' version ', help= ' Print the Version ') parser.add_option ('-f ', '--file ', Action= ' Store ', dest= ' file ', help= ' file to handle ') parser.add_option ('-a ', '--add ', action= ' append ', dest= ' add ', help= ' Add to handle ') parser.add_option ('-C ', '--count ', action= ' count ', dest= ' count ', help= ' count to handle ') parser.add_ Option ('-d ', '--count1 ', action= ' count ', dest= ' count ', help= ' count1 to handle ') #parser. Add_option ('-V ', '--version ', dest= ' version ') if Parser.has_option ('-f '): print (' content-f ') # Parser.set_default ('-f ', ' myFile ') parser.remove_op tion ('-f ') if not parser.has_option ('-f '): print (' Do not ' Content-f ') # simulates command parameters with an array #testargs = ['-I ', ' someforinput ', '-f ', ' someforfile ', '-vq ', '-a ', ' test1 test2 test3 ', '-C ', '-d ']testargs = ['-I ', ' someforinput ', ' someforfile ', ' someForFile1 ', '-Q ', '-a ', ' test1 test2 test3 ', '-c ', '-d ', '-H ']o ptions, args = Parser.parse_args (testargs) print (' Options:%s '% options) print (' args:%s '% args) if Options.input:pri NT (' Input in args:%s '% options.input) if Options.version:print (' version 1.0.0 ') # if options.file:# print (' File in AR GS:%s '% options.file) if Options.add:print (' Add in args:%s '% options.add) print (' version in Args ', options.version )

  

Results:

Content-fdo not content-fusage:optparse module exercises. py Custom Help Stringcustom descriptionoptions:  --version             Show Program ' s version number and exit-  H,--help Show this help            message  and exit-I INPUT,--input=input                        Read Input data from input file  -o output,--output=output                        write data to output file  -Q,--quite           don ' t print th E version  -a add,--add=add     add to handle  -C,--count           count to handle-  D,--count1          count1 To Handleprocess finished with exit code 0
Second, new object
Parse = Optionparse ()
Formal parameters include:
def __init__ (self,             usage=none,             option_list=none,             option_class=option,             Version=none,             Conflict_handler= "Error",             Description=none,             formatter=none,             add_help_option=true,             Prog=none,             Epilog=none):
Third, the new option 3.1 can be used in several ways:
Add_option, Add_option_group, Add_options.
3.2 Specific parameter analysis:
Add_option (...): the previous parameter in the Add_option method is an option for the command, which can be an equivalent short name or long name, usually preceded by a short name, followed by a long name. The parameters you can configure are as follows: Dest: You can determine the name of the property when the value is parsed, especially if it is suitable for more than one equivalent parameter .    When not specified, the option is not added-the string.    Type: The value type of the option, the default type of the value is the string, where the value is specified as a different type. Default: Defaults.    No default value is set for none.    Help: An option that has an-H to print the information.    Metavar: Represents the default value displayed to the Help options, choices: This value is required when type is set to choices.    Const: Specifies a constant value to the option, which will be used for subsequent store_const and Append_const, together.        Action: Used to control the handling of options and parameters, such as parameterless option processing, can be set to the following string: "Store": stores the value to dest the specified property, forcing the request to provide parameters;        "Store_true": When this option is used, the following dest will be set to true, not with the arguments. "Store_false": When this option is used, the subsequent dest will be set to false. Used when the same dest is used in conjunction with another "store_true" option.        Not with parameters.        "Append": Stores the value to dest the specified property, and is in the form of an array, which must be followed by the parameter. "Store_const": Used to store the value set by the const parameter to the Dest specified property. Commonly used when dest is 2 or more options with the same name.        Not with parameters. "Append_const": Used to store an array of parameters that are const set to the Dest specified property.        Not with parameters. "Count": After use, the stored value to dest the specified attribute value plus 1, you can count the number of occurrences in the parameter. Not very useful.        Not with parameters.        "Callback": After specifying the callback function name (without parentheses), the corresponding opt and args are passed to the callback function. "Help", "version": corresponds to the aid and version.    be used in addition to your own design. When ACTIWhen on is set to Store_ture/store_false, when the parameter is parsed, if there is a value of Ture/false, no value is none.     When the dest phase is set to Store_false, and the other action is set to Store_ture, the argument is resolved as it appears later.

  

Four, option related parameters: 4.1, can be used to set the default parameters of multiple options at the same time
    def set_default (self, dest, value):    def set_defaults (self, **kwargs):

  

4.2, check if there is a corresponding option
  def has_option (self, OPT_STR):

  

4.3, delete option
     def remove_option (self, OPT_STR):

4.4, for example:
Parser = Optionparser () parser.add_option ('-f ', '--file ', action= ' store ', dest= ' file ', help= ' file to handle ') if Parser.h As_option ('-f '):     print (' content-f ')     parser.set_default ('-f ', ' myFile ')     parser.remove_option ('-f ') if Not parser.has_option ('-f '):     print (' Do not content-f ')

Output:

Content-fdo not Content-f
4.5, add option group Add_option_group ()

If you have a lot of options, you can group them and then add them. The advantage of grouping is that a set of program parameters can be divided into a group, if there is a separate description, can be processed separately. Use the following:

Group = OptionGroup (parser)  #创建分组group. Add_option () #添加选项parser. Add_option_group (group) #将分组加入到解释器
4.6, add option array add_options ([Option1,...])

Put each option object in a list and add it together

Five, parameter resolution Parse_args ()

Using parse_args() the parameter parsing, the default is to use sys.argv[1:] as a parameter, or you can pass a command-line argument list: parse_args(list) .

parse_args()The two values returned:

    Options, which is an object that holds command-line parameter values. As long as you know the command line parameter name, such as input, you can access its corresponding value: Options.input.    args, which is a list of command-line arguments that have not been parsed.

VI, Help documentation

The default automatically comes with-H and--help to output the help document, and the program terminates after the output.
The help document consists of three parts:

    The usage help section, which is typically entered at Optionparser initialization, is the first parameter or can be specified with a specific formal parameter name. You can use%prog to represent the current program name.    The description describes the content specified by the description parameter at the time of initialization of the Optionparser.    Options and description text defined when the option Description section option is added

  

The Optionparser parameter version can specify a string for the--version output, as well as support for %prog, such as version= "%prog 1.0"

As an example:
# A Help document explaining the string hstr = '%prog custom Help string ' parser = Optionparser (hstr, description= ' custom description ')

  

Get_usage (), Get_description (), get_version (): Gets the corresponding string. Print_help (), Print_usage (), Print_description (), Print_ Version (): Output the appropriate content error (STR): Error and output str.

  



This article is for reference: https://www.jianshu.com/p/bec089061742

The usage of the Python optparse module is detailed

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.