Detailed usage of python OptParse module

A brief introduction to the OptParse module

Python has two built-in modules for handling command-line arguments:
  one is getopt which can only handle command-line arguments simply;
  the other is optparse, which is powerful and easy to use, and can easily generate standard, Unix/Posix-compliant Canonical command line instructions. will automatically help you with the -h help option.

  To customize the parameter option control of the program, you can use the OptParse module that comes with python, and of course you can directly parse the parameters in sys.argv (but this is more troublesome)

import optparse

optparse is no longer updated, the updated version is called argparse.
import argparse

  

 OptParse supports generic GNU option methods, including:

No argument option, -v
With parameters, -p value, --para=value
value argument, -pvalue (long arguments are not supported)
Merge options, -abc, -abcp value (the last one can have parameters, the rest have no parameters)

  The difference between - and -- when parsing:

- Just look at the following value, if there is no parameter, then continue to read the next one; if there is a parameter, read the parameter in (separated or integrated).

-- read the following value directly;

  

Basic usage of optparse module

1. Basic usage

1. Load the OptionParser class and create a new object: OptionParser()

2. Add options: add_option(…)

3. Parameter parsing: parse_args()

for example:

# _*_ coding: utf-8 _*_
import optparse

from optparse import OptionParser
# A help documentation explanation string
hstr = '%prog custom help string'
parser = OptionParser(hstr, description='custom description', version='%prog 1.0')
#Create a parser instance through the OptionParser class, the %prog in the initial parameter usage is equivalent to os.path.basename(sys.argv[0]), ie
#The name of the script you are currently running, the version parameter is used to display the version of the current script.
'''
Add parameters, -f, --file are long and short options, one is enough.
dest='user' saves the parameters entered by the user into the variable user, which can be obtained through the options.user method
Action is used to indicate how to process the value after option, for example:
XXX.py -f test.txt
After processing by parser.parse_args(), the value of test.txt is stored in an object represented by -f, that is, dest in -f is defined
即option.filename = 'test.txt'
Common options for action are store_true, store_false, etc. These two are usually used in boolean options.

 metavar is only useful in displaying help, such as when displaying help:
 -f FILE, --filename=FILE    write output to FILE
 -m MODE, --mode=MODE  interaction mode: novice, intermediate, or expert
                         [default: intermediate]
If there is no metavr parameter in the -f item, it will be displayed as -f FILENAME --filename=FILENAME above, which will display the value of dest

 defalut is the default value of an option. When the script is called, if the parameter does not have a specified value, the default value of default is adopted.
 '''
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_option('-f')
if not parser.has_option('-f'):
    print('do not content -f')
# Simulate command arguments 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']
options, args = parser.parse_args(testArgs)
print('options : %s' % options)
print('args : %s' % args)

if options.input:
    print('input in args : %s' % options.input)
if options.version:
    print('version 1.0.0')

# if options.file:
# print('file in args : %s' % options.file)
if options.add:
    print('add in args : %s' % options.add)

print('version in args', options.version)

  

result:

content -f
do not content -f
Usage: Exercises for optParse module.py custom help string

custom description

Options:
  --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 the version
  -a ADD, --add=ADD     add to handle
  -c, --count           count to handle
  -d, --count1          count1 to handle

Process finished with exit code 0

 Second, create a 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 The following methods can be used:

add_option, add_option_group, add_options.

3.2 Analysis of specific parameters:

add_option(…):

    The first parameter in the add_option method is the option of the command, which can be the equivalent short name or long name, usually the short name in the front and the long name in the back.

The parameters that can be configured are the following:
    dest: can determine the attribute name when fetching the value after parsing, especially suitable for having multiple equivalent parameters. When not specified, it is a string without the option -.
    type: The value type of the option, the default type of the value is a string, here the value is specified as another type.
    default: The default value. If no default value is set, it is None.
    help: help information to print when -h is present in the option.
    metavar: indicates the default value of the option displayed in help;
    choices: When type is set to choices, this value needs to be set.
    const: Specify a constant value to the option, the constant value will be used in the following store_const and append_const, together.
    action: used to control the processing of options and parameters, like no-parameter option processing, can be set to the following strings:
        "store": store the value to the attribute specified by dest, and it is mandatory to provide parameters later;
        "store_true": When this option is used, the following dest will be set to true, without the parameter.
        "store_false": When this option is used, the following dest will be set to false. It is often used when using the same dest with another "store_true" option. It does not follow the parameter.
        "append": Store the value to the property specified by dest, in the form of an array, which must be followed by the parameter.
        "store_const": It is used to store the value set by the parameter as const to the attribute specified by dest. It is often used for processing when dest is two or more options with the same name. It does not follow the parameter.
        "append_const": used to store the array whose parameter is set as const to the attribute specified by dest. Does not follow the parameter.
        "count": After use, it will add 1 to the attribute value specified by the stored value to dest, which can count the number of occurrences in the parameter. It is not very useful. It does not follow the parameter.
        "callback": After specifying the callback function name (without parentheses), the corresponding opt and args will be passed to the callback function.
        "help", "version": Corresponding to help and version. Use when you want to design it yourself.

    When action is set to store_ture / store_false, when parsing parameters, it is True / False if there is a value, and None if there is no value.
    When dest is the same, one action is set to store_false, and the other action is set to store_ture, when parsing parameters, whichever appears later.

    

  

 Four, option related parameters:

4.1, which can be used to set default parameters for multiple options at the same time

    def set_default(self, dest, value):

    def set_defaults(self, **kwargs):

  

4.2, check if there are corresponding options

  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.has_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 -f
do not content -f

4.5, add option group add_option_group()

  If there are a lot of options, you can group them and then add them. The advantage of grouping is that a series of program parameters can be grouped into a group, and if there is an independent description, it can be processed separately. Use the following:

group = OptionGroup(parser) #Create a group
group.add_option() #Add options
parser.add_option_group(group) #Add the group to the interpreter

4.6, add option array add_options([Option1,…])

Put each Option object in a list and add it together

 

Five, parameter parsing parse_args()

Use parse_args()to parse parameters, the default is to use sys.argv[1:]as parameters, you can also pass a list of command line parameters: 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 were not parsed.

 

Six, help documentation

By default, -h and --help are automatically used to output the help document, and the program terminates after the output.
The help document consists of three parts:

    usage help section,
The usage help part is usually entered when OptionParser is initialized, as the first parameter, and can also be specified with a specific parameter name. You can use %prog to indicate the current program name.

    description description section
The content specified by the description parameter when the OptionParser was initialized.

    Option and option description section
Description text defined when the option was added

  

The formal parameter version of OptionParser can specify the string output by --version, and also supports %prog , such as version="%prog 1.0"

for example:
# A help documentation explanation string
hstr = '%prog custom help string'
parser = OptionParser(hstr, description='custom description')

  

get_usage(), get_description(), get_version(): Get the corresponding string.
print_help(), print_usage(), print_description(), print_version(): output the corresponding content
error(str): Error and output str.

  



 

 

 

Reference for this article: https://www.jianshu.com/p/bec089061742

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325088156&siteId=291194637