python笔记8--命令行解析Argparse
python获取输入参数的方式有多种,一种使用sys.argv获取输入的参数,然后根据值判断是否包括某个参数;第二种使用Argparse来获取和设置参数,该方法较实用,笔者查阅了相关资料并加以整理,放在此处以便于后续查阅和学习!
1 功能
- 默认功能
- 添加参数
- 添加说明
- 设置参数类型
- 设置参数可省略
- 同时存在可省略和必须参数
- 设置参数的范围
- 结束案例
2 源码案例
2.1 默认功能
源码:
#!/usr/bin/python
import argparse
parser = argparse.ArgumentParser()
args = parser.parse_args()
测试结果:
```bash
(py3_env) xg@xghome:~/file/code/python/argparse$ python arg0.py
(py3_env) xg@xghome:~/file/code/python/argparse$ python arg0.py -h
usage: arg0.py [-h]
optional arguments:
-h, --help show this help message and exit
默认有-h|--help帮助信息。
## 2.2 添加参数
源码:
```python
#!/usr/bin/python
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("echo")
args = parser.parse_args()
print(args.echo)
测试结果:
(py3_env) xg@xghome:~/file/code/python/argparse$ python arg1.py
usage: arg1.py [-h] echo
arg1.py: error: the following arguments are required: echo
(py3_env) xg@xghome:~/file/code/python/argparse$ python arg1.py -h
usage: arg1.py [-h] echo
positional arguments:
echo
optional arguments:
-h, --help show this help message and exit
(py3_env) xg@xghome:~/file/code/python/argparse$ python arg1.py test
test
添加一个echo参数,可以通过args.echo获取具体参数值。
2.3 添加说明
源码:
#!/usr/bin/python
import argparse
parser = argparse.ArgumentParser()
parser.description = 'This is a basic test'
parser.add_argument("echo", help='print string')
args = parser.parse_args()
print(args.echo)
测试结果:
(py3_env) xg@xghome:~/file/code/python/argparse$ python arg2.py -h
usage: arg2.py [-h] echo
This is a basic test
positional arguments:
echo print string
optional arguments:
-h, --help show this help message and exit
(py3_env) xg@xghome:~/file/code/python/argparse$ python arg2.py test2
test2
通过description添加说明,通过help对参数加以说明。
2.4 设置参数类型
源码:
#!/usr/bin/python
import argparse
parser = argparse.ArgumentParser()
parser.description = 'This is a basic test, A+B'
parser.add_argument("paraA", help='this is int', type=int)
parser.add_argument("paraB", help='this is int', type=int)
args = parser.parse_args()
print('{0} + {1} = {2}'.format(args.paraA, args.paraB,args.paraA+args.paraB))
测试结果:
(py3_env) xg@xghome:~/file/code/python/argparse$ python arg3.py pa pb
usage: arg3.py [-h] paraA paraB
arg3.py: error: argument paraA: invalid int value: 'pa'
(py3_env) xg@xghome:~/file/code/python/argparse$ python arg3.py 1 2
1 + 2 = 3
通过type设置参数类型,设置类型后直接获取参数就可以执行相关运算。
2.5 设置参数可省略
源码:
#!/usr/bin/python
import argparse
parser = argparse.ArgumentParser()
parser.description = 'This is a basic test, A+B'
parser.add_argument("--paraA", help='this is int', type=int)
parser.add_argument("--paraB", help='this is int', type=int)
args = parser.parse_args()
if args.paraA:
print('A={0}'.format(args.paraA))
if args.paraB:
print('B={0}'.format(args.paraB))
if args.paraA and args.paraB:
print('{0} + {1} = {2}'.format(args.paraA, args.paraB,args.paraA+args.paraB))
测试结果:
(py3_env) xg@xghome:~/file/code/python/argparse$ python arg4.py --paraA 1
A=1
(py3_env) xg@xghome:~/file/code/python/argparse$ python arg4.py --paraB 1
B=1
(py3_env) xg@xghome:~/file/code/python/argparse$ python arg4.py -- paraA 1 --paraB 2
A=1
B=2
1 + 2 = 3
在参数名称前加–即可设置参数为可省略;
通过 parser.add_argument(’-a’, “–paraA”, help=‘this is int’, type=int) 添加-a,也可以使用-a 1来简化参数输入。
parser.add_argument('-a', "--paraA", help='this is int', type=int)
parser.add_argument('-b', "--paraB", help='this is int', type=int)
测试结果:
(py3_env) xg@xghome:~/file/code/python/argparse$ python arg4.py -a 1 -b 2
A=1
B=2
1 + 2 = 3
2.6 同时存在可省略和必须参数
源码:
#!/usr/bin/python
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
help="display a square of a given number")
parser.add_argument("-v", "--verbose", action="store_true",
help="increase output verbosity")
args = parser.parse_args()
answer = args.square**2
if args.verbose:
print("the square of {} equals {}".format(args.square, answer))
else:
print(answer)
测试结果:
(py3_env) xg@xghome:~/file/code/python/argparse$ python arg5.py -h
usage: arg5.py [-h] [-v] square
positional arguments:
square display a square of a given number
optional arguments:
-h, --help show this help message and exit
-v, --verbose increase output verbosity
(py3_env) xg@xghome:~/file/code/python/argparse$ python arg5.py 3 --verbose
the square of 3 equals 9
(py3_env) xg@xghome:~/file/code/python/argparse$ python arg5.py 3
9
–verbose 后添加action,且值为store_true,因此只要出现 --verbose 其值就为True,不需要额外对–verbose赋值;
2.7 设置参数的范围
源码:
#!/usr/bin/python
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)
测试结果:
(py3_env) xg@xghome:~/file/code/python/argparse$ python arg6.py 3 -v 3
usage: arg6.py [-h] [-v {0,1,2}] square
arg6.py: error: argument -v/--verbosity: invalid choice: 3 (choose from 0, 1, 2)
(py3_env) xg@xghome:~/file/code/python/argparse$ python arg6.py 3 -v 1
3^2 == 9
通过choices=[]设置参数的范围,超出范围即报错;
2.8 结束案例
源码:
#!/usr/bin/python
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))
测试结果:
(py3_env) xg@xghome:~/file/code/python/argparse$ python arg7.py -h
usage: arg7.py [-h] [-v | -q] x y
calculate X to the power of Y
positional arguments:
x the base
y the exponent
optional arguments:
-h, --help show this help message and exit
-v, --verbose
-q, --quiet
(py3_env) xg@xghome:~/file/code/python/argparse$ python arg7.py 2 3 -q
8
(py3_env) xg@xghome:~/file/code/python/argparse$ python arg7.py 2 3 -v
2 to the power 3 equals 8
3 说明
参考文献:
[1]Argparse Tutorial
[2]Python3.7 - Argparse模块讲解