Python command-line parameter analysis tool argparse

Why argparse #

Straight to the point, for example a simple calculator code, wherein the script executes sys.argv parameter passed back to reading.

def calculator(x, y, operation):
    if "add" == operation:
        return x + y
    elif "mod" == operation:
        return x % y
    elif "sub" == operation:
        return x - y
    elif "div" == operation:
        return x / y
    elif "mul" == operation:
        return x * y


def main():
    print(calculator(sys.argv[1], sys.argv[2], sys.argv[3]))


if __name__ == '__main__':
    main()

We define a calculator ways to do some simple calculations, it seems fairly ordinary, but for users, in the absence of good documentation to support the premise, passing different parameters behave differently, if only a few parameters also can be accepted, with the increase of parameters, methods will become more and more difficult to use. This time parameters will need to resolve, argparse module will officially recommended in optparse on the basis of a further modified version of the standard library. Let us look at her true colors before the first to know argparse related features through an example.

I believe small partners are more or less used Linux system, let us through the following example argparse intuitive understanding of what to do.

# 只输入ls,默认显示当前目录下内容
[root@host workarea]# ls
demo  scripts
# 当我们给ls命令加一个参数,便会去找这个参数对应目录下的内容
[root@host workarea]# ls pythondemo/
arg1.py  argparsedemo1.py  fangzhen.py  numpyapi.py  tools
# 我们也可以使用ls -[cmd]来改变行为,获得更详细的信息
[root@host workarea]# ls -l
total 8
drwxr-xr-x 3 root root 4096 Dec 14 14:05 pythondemo
drwxr-xr-x 2 root root 4096 Dec 14 14:29 scripts
# 如果我们想知道ls命令的其他用法和相关信息可以使用ls --help
[root@host workarea]# ls --help
Usage: ls [OPTION]... [FILE]...
List information about the FILEs (the current directory by default).
Sort entries alphabetically if none of -cftuvSUX nor --sort is specified.

Mandatory arguments to long options are mandatory for short options too.
  -a, --all                  do not ignore entries starting with .
  -A, --almost-all           do not list implied . and ..
...

The script parameters passed to display binding, allowing users to more clearly himself what to do, and give you some information about the user when he forgot how to use our script, which is what we need to do, of course, if the number of parameters does not more or less complex behavior can not be used.

argparse first experience #

#总体使用流程如下
import argparse
# 模板创建一个解析参数对象
parser = argparse.ArgumentParser()
# 用来指定程序需要接受的命令参数
parser.add_argument()
# 通过分析指定的参数返回一些数据
args = parser.parse_args()

We try to direct the above example to distinguish under renovation, with an intuitive feel argparse

def calculator(args):
    operation = args.operation
    x = args.x
    y = args.y
    if "add" == operation:
        return x + y
    elif "mod" == operation:
        return x % y
    elif "sub" == operation:
        return x - y
    elif "div" == operation:
        return x / y
    elif "mul" == operation:
        return x * y


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--x", type=float, default=1.0, help="What is the first number")
    parser.add_argument("--y", type=float, default=1.0, help="What is the second number")
    parser.add_argument("--operation", type=str, help="What operation? [add,mod,sub,div,mul]")
    args = parser.parse_args()
    print(args)
    print(calculator(args))


if __name__ == '__main__':
    main()

After a simple transformation, when you call the calculator method, we can more clearly what they are doing to operate, and can help to use the information without the need to read the source code, it really saves a lot of unnecessary time.

# 直接调用不加参数,会提示None,命名空间那行为print(args)
[root@host pythondemo]# python arg2.py 
Namespace(operation=None, x=1.0, y=1.0)
None
# 加上参数-h 或 --help我们就能看到帮助信息,感觉像模像样
[root@host pythondemo]# python arg2.py -h
usage: arg2.py [-h] [--x X] [--y Y] [--operation OPERATION]

optional arguments:
  -h, --help            show this help message and exit
  --x X                 What is the first number
  --y Y                 What is the second number
  --operation OPERATION
                        What operation? [add,mod,sub,div,mul]
# 参数传入方法,这里的等于号可以省略
[root@host pythondemo]# python arg2.py --x=2 --y=3 --operation=mul
6.0
# 当我们少输入或者没有输入要求的参数
[root@host pythondemo]# python arg2.py 2
usage: arg2.py [-h] [--x X] [--y Y] [--operation OPERATION]
arg2.py: error: unrecognized arguments: 2

Of course, this does not complete all our needs, we can do better, then we have to get insight into the protagonist argparse next day.

Detailed argparse #

Template creation argparse.ArgumentParser () #

We can have a simple title to parse the template will be displayed in the --help

argparse.ArgumentParser(description='sample demo')

If we do not want to use Linux-style "-" or "-" as a command prefix, as our custom

parser = argparse.ArgumentParser(prefix_chars='-+/')

Is added by default -h and --help help when the template is created, if we do not want, you can write to get rid of

argparse.ArgumentParser(add_help=False)

We can also add version information will be automatically added to obtain the version information -v --version command and

argparse.ArgumentParser(version='1.0')

Highlight parser.add_argument () #

Direct a string "-a" or "--a" When you call incoming values ​​behind the script, can be used in the method of Riga arg.a get incoming values, default values ​​passed from sys.argv [1:] obtained

parser.add_argument("-a")
args = parser.parse_args()
print(args)
print(args.a)

# 结果
λ python exam2.py --a=1
Namespace(a='1')
1

If we want to change the access method can be used dest parameter

parser.add_argument("--a", dest="c")
args = parser.parse_args()
print(args)
print(args.c)

# 结果
λ python exam2.py --a=1    

Namespace(c='1')           
1

We can not display variable assignment, without "-" or "-", such as the order of incoming values ​​and parameters defined, this desk does not work

parser.add_argument("a")
parser.add_argument("b")
args = parser.parse_args()
print(args)

# 结果
λ python exam2.py 1 2
Namespace(a='1', b='2')

Of course, we can also give the incoming two kinds of acceptance, this "-" at the beginning of shorthand for the command to get the incoming parameters "-" after the property

parser.add_argument('-n', '--name', help="What's ur name")
args = parser.parse_args()
print(args)
print(args.name)

# 结果
λ python exam3.py -n=ling
Namespace(name='ling')
ling
λ python exam3.py --name=wang
Namespace(name='wang')
wang

We pass the default value is interpreted as a string, if we need to specify the type parameter type can be used, as shown in the above definition calculator, if you do not specify the type int, and will be given. The default type supported types are int, float, open

parser.add_argument(type="")

If it is determined action required number of arguments passed, we can also add nargs do enforce restrictions. [ "N-': absolute number of parameters,"? ": 0 or 1," * ": 0 or so," + ": all and at least one]

parser.add_argument(nargs="")

Parameters action #

argparse built six kinds of actions can be triggered when parsing a parameter:

storeSaving parameter values, the parameter values ​​may be first converted to another data type. If not explicitly specified action, for the default operation.

store_constSave constant, if this action is triggered, the value is the value of the parameter specifications are defined in advance, and can not pass command-line value.

store_ture/ store_falseSave the corresponding boolean values. These two actions are used to implement Boolean switches.

appendThe value is saved to a list. If the parameter is repeated, the stored plurality of values.

append_constSave a parameter defined in the specification values ​​into a list.

versionPrint version information on the program, and then exit

Are used as follows:

parser.add_argument('-s', action='store', dest='simple_value', help='Store a simple value')
parser.add_argument('-c', action='store_const', dest='constant_value',
        const='value-to-store',
        help='Store a constant value')

parser.add_argument('-t', action='store_true', default=False,
        dest='boolean_switch',
        help='Set a switch to true')
parser.add_argument('-f', action='store_false', default=False,
        dest='boolean_switch',
        help='Set a switch to false')

parser.add_argument('-a', action='append', dest='collection',
        default=[],
        help='Add repeated values to a list')

parser.add_argument('-A', action='append_const', dest='const_collection',
        const='value-1-to-append',
        default=[],
        help='Add different values to list')
parser.add_argument('-B', action='append_const', dest='const_collection',
        const='value-2-to-append',
        help='Add different values to list')

parser.add_argument('--version', action='version', version='%(prog)s 1.0')
results = parser.parse_args()
print 'simple_value     =', results.simple_value
print 'constant_value   =', results.constant_value
print 'boolean_switch   =', results.boolean_switch
print 'collection       =', results.collection
print 'const_collection =', results.const_collection

# 结果
λ python argparse_action.py -s value

simple_value     = value
constant_value   = None
boolean_switch   = False
collection       = []
const_collection = []

λ python argparse_action.py -c

simple_value     = None
constant_value   = value-to-store
boolean_switch   = False
collection       = []
const_collection = []

λ python argparse_action.py -t

simple_value     = None
constant_value   = None
boolean_switch   = True
collection       = []
const_collection = []

λ python argparse_action.py -f

simple_value     = None
constant_value   = None
boolean_switch   = False
collection       = []
const_collection = []

λ python argparse_action.py -a one -a two -a three

simple_value     = None
constant_value   = None
boolean_switch   = False
collection       = ['one', 'two', 'three']
const_collection = []

λ python argparse_action.py -B -A

simple_value     = None
constant_value   = None
boolean_switch   = False
collection       = []
const_collection = ['value-2-to-append', 'value-1-to-append']
λ python argparse_action.py --version
argparse_action.py 1.0

Parser Group #

We often encounter many of the same parameter parser will need, for example, will need to enter a user name and password, so that we can define a parent parser definition of common rules, sub-parser can be integrated and expanded. If the same parameter defines a conflict occurs. argparse has two built-in conflict handlers error(default) and resolve, resolvewill be based on the order of addition of the conflict option to select a parameter processor, add after covering the old rules. We should try to avoid conflict, it is generally not the father of the parser to define help. The following give a simple example.

First, father parser defined as follows:

parser = argparse.ArgumentParser(description='parent 2', add_help=False)
parser.add_argument('-p', '--password', help='What is your passwrd')
parser.add_argument('-user', '--username', help='What is your username')
parser.add_argument('-m', '--female', help='What is your female')
args = parser.parse_args()
print(args)

# 结果
λ python arg_parent.py -h
usage: arg_parent.py [-p PASSWORD] [-user USERNAME] [-m FEMALE]
arg_parent.py: error: unrecognized arguments: -h

λ python arg_parent.py -p 123 -user ling -m man
Namespace(female='man', password='123', username='ling')

Sub-parser: Integration and rewrite

import arg_parent

parser = argparse.ArgumentParser(description='son 1', parents=[arg_parent.parser], conflict_handler='resolve')
parser.add_argument('-w', '--weather', help="What's the weather")
parser.add_argument('-m', '--female', action='store_const', const='TRUE', help='What is your female')

args = parser.parse_args()
print(args)

# 结果
λ python arg_son.py -m -w cold -p 123
Namespace(female='TRUE', password='123', username=None, weather='cold')

λ python arg_son.py -m man
usage: arg_son.py [-h] [-p PASSWORD] [-user USERNAME] [-w WEATHER] [-m]
arg_son.py: error: unrecognized arguments: man

Currently only used the above features, there are some features will not describe the subsequent use to add.

Guess you like

Origin www.linuxidc.com/Linux/2019-10/161114.htm