使用方法
三个步骤:
- 创建 ArgumentParser() 对象
- 调用 add_argument() 方法添加参数
- 使用 parse_args() 解析添加的参数
参数类型
两种参数类型:
- 定位参数
- 可选参数
定位参数
示例(计算一个数的平方):
# -*- coding: utf-8 -*-
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", help="display a square of a given number", type=int)
args = parser.parse_args()
print(rgs.square**2)
将上面代码保存为文件argparse_usage.py
,在终端运行,结果如下:
$ python argparse_usage.py 10
10
可选参数
示例:
# -*- coding: utf-8 -*-
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--square", help="display a square of a given number", type=int)
parser.add_argument("--cubic", help="display a cubic of a given number", type=int)
args = parser.parse_args()
if args.square:
print(args.square**2)
if args.cubic:
print(args.cubic**3)
将上面代码保存为文件argparse_usage.py
,在终端运行,结果如下:
$ python argparse_usage.py --square 8
64
$ python argparse_usage.py --cubic 8
512
混合使用
示例(给一个整数序列,输出它们的和或最大值):
import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
const=sum, default=max,
help='sum the integers (default: find the max)')
args = parser.parse_args()
print(args.accumulate(args.integers))
$ python argparse_usage.py
usage: argparse_usage.py [-h] [--sum] N [N ...]
argparse_usage.py: error: too few arguments
$ python argparse_usage.py 1 2 3 4
4
$ python argparse_usage.py 1 2 3 4 --sum
10
add_argument() 方法
add_argument()
方法定义如何解析命令行参数
ArgumentParser.add_argument(name or flags...[,action][,nargs][,const][,default][,type][,choices][,required][,help][,metavar][,dest])
参数解释:
- name or flags - 选项字符串的名字或者列表,例如 foo 或者 -f, --foo。
- action - 命令行遇到参数时的动作,默认值是 store。
- store_const,表示赋值为const;
- append,将遇到的值存储成列表,也就是如果参数重复则会保存多个值;
- append_const,将参数规范中定义的一个值保存到一个列表;
- count,存储遇到的次数;此外,也可以继承 argparse.Action 自定义参数解析;
- nargs - 应该读取的命令行参数个数,可以是具体的数字,或者是?号,当不指定值时对于 Positional argument 使用
default,对于 Optional argument 使用 const;或者是 * 号,表示 0 或多个参数;或者是 + 号表示 1 或多个参数。 - const - action 和 nargs 所需要的常量值。
- default - 不指定参数时的默认值。
- type - 命令行参数应该被转换成的类型。
- choices - 参数可允许的值的一个容器。
- required - 可选参数是否可以省略 (仅针对可选参数)。
- help - 参数的帮助信息,当指定为 argparse.SUPPRESS 时表示不显示该参数的帮助信息.
- metavar - 在 usage 说明中的参数名称,对于必选参数默认就是参数名称,对于可选参数默认是全大写的参数名称.
- dest - 解析后的参数名称,默认情况下,对于可选参数选取最长的名称,中划线转换为下划线.