1. argparse介绍
- 是python的一个命令行解析包
2. 基本用法
- test1.py是在linux下测试argparse的文件,其内容如下:
root@iZ2zee0spkwcgvz4do5kt2Z:/tmp/arg# cat test1.py
#!/usr/bin/env python
# encoding: utf-8
import argparse
parser = argparse.ArgumentParser()
parser.parse_args()
测试:
root@iZ2zee0spkwcgvz4do5kt2Z:/tmp/arg# python test1.py
root@iZ2zee0spkwcgvz4do5kt2Z:/tmp/arg# python test1.py -help
usage: test1.py [-h]
test1.py: error: argument -h/--help: ignored explicit argument 'elp'
root@iZ2zee0spkwcgvz4do5kt2Z:/tmp/arg# python test1.py -v
usage: test1.py [-h]
test1.py: error: unrecognized arguments: -v
root@iZ2zee0spkwcgvz4do5kt2Z:/tmp/arg# python test1.py bar
usage: test1.py [-h]
test1.py: error: unrecognized arguments: bar
第一个没有任何输出和出错
第二个测试为打印帮助信息,argparse会自动生成帮助文档
第三个测试为未定义的-v参数,会出错
第四个测试为未定义的参数foo,出错
3. positional arguments
- positional arguments为英文定义,中文名叫有翻译为定位参数的,用法是不用带-就可用
root@iZ2zee0spkwcgvz4do5kt2Z:/tmp/arg# cat test2.py
#!/usr/bin/env python
# encoding: utf-8
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("echo")
args = parser.parse_args()
print args.echo
执行测试如下:
root@iZ2zee0spkwcgvz4do5kt2Z:/tmp/arg# python test2.py
usage: test2.py [-h] echo
test2.py: error: too few arguments
root@iZ2zee0spkwcgvz4do5kt2Z:/tmp/arg# python test2.py -h
usage: test2.py [-h] echo
positional arguments:
echo
optional arguments:
-h, --help show this help message and exit
root@iZ2zee0spkwcgvz4do5kt2Z:/tmp/arg# python test2.py -v
usage: test2.py [-h] echo
test2.py: error: too few arguments
root@iZ2zee0spkwcgvz4do5kt2Z:/tmp/arg# python test2.py 666666666
666666666
定义了一个叫echo的参数,默认必选
第一个测试为不带参数,由于echo参数为空,所以报错,并给出用法(usage)和错误信息
第二个测试为打印帮助信息
第三个测试为正常用法,回显了输入字符串 6666666
4. optional arguments
中文名叫可选参数,有两种方式:
一种是通过一个-来指定的短参数,如 -h;
一种是通过–来指定的长参数,如 --help
这两种方式可以同存,也可以只存在一个 。
root@iZ2zee0spkwcgvz4do5kt2Z:/tmp/arg# cat test3.py
#!/usr/bin/env python
# encoding: utf-8
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-v", "--verbosity", help="increase output verbosity")
args = parser.parse_args()
if args.verbosity:
print "verbosity turned on"
注意这一行:
parser.add_argument("-v", "--verbosity", help="increase output verbosity")
定义了可选参数 -v 或 --verbosity,通过解析后,其值保存在args.verbosity变量中
用法如下:
root@iZ2zee0spkwcgvz4do5kt2Z:/tmp/arg# python test3.py -v 6
verbosity turned on
root@iZ2zee0spkwcgvz4do5kt2Z:/tmp/arg# python test3.py --verbosity 1
verbosity turned on
root@iZ2zee0spkwcgvz4do5kt2Z:/tmp/arg# python test3.py --help
usage: test3.py [-h] [-v VERBOSITY]
optional arguments:
-h, --help show this help message and exit
-v VERBOSITY, --verbosity VERBOSITY
increase output verbosity
root@iZ2zee0spkwcgvz4do5kt2Z:/tmp/arg# python test3.py -v
usage: test3.py [-h] [-v VERBOSITY]
test3.py: error: argument -v/--verbosity: expected one argument
测试1中,通过-v来指定参数值
测试2中,通过–verbosity来指定参数值
测试3中,通过-h来打印帮助信息
测试4中,没有给-v指定参数值,所以会报错
5. action=‘store_true’
上一个用法中 -v 必须指定参数值,否则就会报错,有没有像 -h 那样,不需要指定参数值的呢,答案是有,通过定义参数时指定 action=“store_true” 即可,用法如下
root@iZ2zee0spkwcgvz4do5kt2Z:/tmp/arg# cat test4.py
#!/usr/bin/env python
# encoding: utf-8
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-v", "--verbose", help="increase output verbosity",action="store_true")
args = parser.parse_args()
if args.verbose:
print "verbosity turned on"
测试:
root@iZ2zee0spkwcgvz4do5kt2Z:/tmp/arg# python test4.py -v
verbosity turned on
root@iZ2zee0spkwcgvz4do5kt2Z:/tmp/arg# python test4.py -h
usage: test4.py [-h] [-v]
optional arguments:
-h, --help show this help message and exit
-v, --verbose increase output verbosity
第一个例子中,-v 没有指定任何参数也可,其实存的是True和False,如果出现,则其值为True,否则为False
6. 类型 type
默认的参数类型为str,如果要进行数学计算,需要对参数进行解析后进行类型转换,如果不能转换则需要报错,这样比较麻烦
argparse提供了对参数类型的解析,如果类型不符合,则直接报错。如下是对参数进行平方计算的程序:
root@iZ2zee0spkwcgvz4do5kt2Z:/tmp/arg# cat test5.py
#!/usr/bin/env python
# encoding: utf-8
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('x', type=int, help="the base")
args = parser.parse_args()
answer = args.x ** 2
print answer
测试
root@iZ2zee0spkwcgvz4do5kt2Z:/tmp/arg# python test5.py 3
9
root@iZ2zee0spkwcgvz4do5kt2Z:/tmp/arg# python test5.py four
usage: test5.py [-h] x
test5.py: error: argument x: invalid int value: 'four'
root@iZ2zee0spkwcgvz4do5kt2Z:/tmp/arg# python test5.py -h
usage: test5.py [-h] x
positional arguments:
x the base
optional arguments:
-h, --help show this help message and exit
第一个测试为计算2的平方数,类型为int,正常
第二个测试为一个非int数,报错
第三个为打印帮助信息
7. 可选值choices=[]
5 中的action的例子中定义了默认值为 True 和 False 的方式,如果要限定某个值的取值范围,比如6 中的整形,限定其取值范围为0, 1, 2,该如何进行呢?
root@iZ2zee0spkwcgvz4do5kt2Z:/tmp/arg# cat test6.py
#!/usr/bin/env python
# encoding: utf-8
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,help="display a square of a given number")
parser.add_argument("-v", "--verbosity", type=int, choices=[0, 1, 2],help="increase output verbosity")
args = parser.parse_args()
answer = args.square**2
if args.verbosity == 2:
print "the square of {} equals {}".format(args.square, answer)
elif args.verbosity == 1:
print "{}^2 == {}".format(args.square, answer)
else:
print answer
测试如下:
root@iZ2zee0spkwcgvz4do5kt2Z:/tmp/arg# python test6.py 4 -v 0
16
root@iZ2zee0spkwcgvz4do5kt2Z:/tmp/arg# python test6.py 4 -v 1
4^2 == 16
root@iZ2zee0spkwcgvz4do5kt2Z:/tmp/arg# python test6.py 4 -v 2
the square of 4 equals 16
root@iZ2zee0spkwcgvz4do5kt2Z:/tmp/arg# python test6.py 4 -v 3
usage: test6.py [-h] [-v {0,1,2}] square
test6.py: error: argument -v/--verbosity: invalid choice: 3 (choose from 0, 1, 2)
root@iZ2zee0spkwcgvz4do5kt2Z:/tmp/arg# python test6.py 4 -h
usage: test6.py [-h] [-v {0,1,2}] square
positional arguments:
square display a square of a given number
optional arguments:
-h, --help show this help message and exit
-v {0,1,2}, --verbosity {0,1,2}
increase output verbosity
root@iZ2zee0spkwcgvz4do5kt2Z:/tmp/arg# python test6.py 4
16
测试1, 2, 3 为可选值范围,通过其值,打印不同的格式输出;
测试4的 verbosity 值不在可选值范围内,打印错误
测试5打印帮助信息
8. 自定义帮助信息help
上面很多例子中都为help赋值,如
parser.add_argument("square", type=int, help="display a square of a given number")
在打印输出时,会有如下内容
positional arguments:
square display a square of a given number
也就是help为什么,打印输出时,就会显示什么
9. 程序用法帮助
8 中介绍了为每个参数定义帮助文档,那么给整个程序定义帮助文档该怎么进行呢?
通过
argparse.ArgumentParser(description="calculate X to the power of Y")
即可
root@iZ2zee0spkwcgvz4do5kt2Z:/tmp/arg# cat test7.py
#!/usr/bin/env python
# encoding: utf-8
import argparse
parser = argparse.ArgumentParser(description="calculate X to the power of Y")
group = parser.add_mutually_exclusive_group()
group.add_argument("-v", "--verbose", action="store_true")
group.add_argument("-q", "--quiet", action="store_true")
parser.add_argument("x", type=int, help="the base")
parser.add_argument("y", type=int, help="the exponent")
args = parser.parse_args()
answer = args.x**args.y
if args.quiet:
print answer
elif args.verbose:
print "{} to the power {} equals {}".format(args.x, args.y, answer)
else:
print "{}^{} == {}".format(args.x, args.y, answer)
打印帮助信息时即显示 calculate X to the power of Y
root@iZ2zee0spkwcgvz4do5kt2Z:/tmp/arg# python test7.py
usage: test7.py [-h] [-v | -q] x y
test7.py: error: too few arguments
root@iZ2zee0spkwcgvz4do5kt2Z:/tmp/arg# python test7.py -q 2 3
8
root@iZ2zee0spkwcgvz4do5kt2Z:/tmp/arg# python test7.py 2 3
2^3 == 8
root@iZ2zee0spkwcgvz4do5kt2Z:/tmp/arg# python test7.py -v 2 3
2 to the power 3 equals 8
root@iZ2zee0spkwcgvz4do5kt2Z:/tmp/arg# python test7.py -q -v 2 3 #互斥
usage: test7.py [-h] [-v | -q] x y
test7.py: error: argument -v/--verbose: not allowed with argument -q/--quiet
10. 互斥参数
在上个例子中介绍了互斥的参数
group = parser.add_mutually_exclusive_group()
group.add_argument("-v", "--verbose", action="store_true")
group.add_argument("-q", "--quiet", action="store_true")
第一行定义了一个互斥组,
第二、三行在互斥组中添加了-v和-q两个参数
可以看出,-q和-v不出现,或仅出现一个都可以,同时出现就会报错。
可定义多个互斥组
11.参数默认值
参数默认值该如何定义
root@iZ2zee0spkwcgvz4do5kt2Z:/tmp/arg# cat test8.py
#!/usr/bin/env python
# encoding: utf-8
import argparse
parser = argparse.ArgumentParser(description="calculate X to the power of Y")
parser.add_argument("square", type=int,help="display a square of a given number")
parser.add_argument("-v", "--verbosity", type=int, choices=[0, 1, 2], default=1, help="increase output verbosity")
args = parser.parse_args()
answer = args.square**2
if args.verbosity == 2:
print "the square of {} equals {}".format(args.square, answer)
elif args.verbosity == 1:
print "{}^2 == {}".format(args.square, answer)
else:
print answer
测试结果如下
root@iZ2zee0spkwcgvz4do5kt2Z:/tmp/arg# python test8.py -v 1
usage: test8.py [-h] [-v {0,1,2}] square
test8.py: error: too few arguments
root@iZ2zee0spkwcgvz4do5kt2Z:/tmp/arg# python test8.py -v 2 3 ###!!!
the square of 3 equals 9
root@iZ2zee0spkwcgvz4do5kt2Z:/tmp/arg# python test8.py 8 -v 2 3
usage: test8.py [-h] [-v {0,1,2}] square
test8.py: error: unrecognized arguments: 3
root@iZ2zee0spkwcgvz4do5kt2Z:/tmp/arg# python test8.py 8 -v 2 ###!!!
the square of 8 equals 64
root@iZ2zee0spkwcgvz4do5kt2Z:/tmp/arg# python test8.py 8 -v 0
64
root@iZ2zee0spkwcgvz4do5kt2Z:/tmp/arg# python test8.py 8 -v 1
8^2 == 64
root@iZ2zee0spkwcgvz4do5kt2Z:/tmp/arg# python test8.py 8 -v 2
the square of 8 equals 64
root@iZ2zee0spkwcgvz4do5kt2Z:/tmp/arg# python test8.py 8 -v 3
usage: test8.py [-h] [-v {0,1,2}] square
test8.py: error: argument -v/--verbosity: invalid choice: 3 (choose from 0, 1, 2)
可以看到如果不指定-v的值,args.verbosity的值默认为1,为了更清楚的看到默认值,也可以直接打印进行测试。
本文转自 http://yarving.historytale.com/ 感谢