Argparse
python自带的命令行参数解析,可以用来方便的读取命令行参数。
- 创建解析对象:parser = argparse.ArgumentParser()
- 添加参数:parser.add_argument()
- 解析参数:parser.parse_args()
示例代码
import argparse
# 创建解析对象
parser = argparse.ArgumentParser(description="Process some integers",
epilog="And what can i do for u?")
# 添加参数
parser.add_argument('integers', type=int, metavar='N', nargs='+',
help='an integer for the accumulator')
parser.add_argument('--sum', action='store_const', const=sum, default=max, dest='accumulate',
help='sum the integers (default: find the max)')
# 解析参数
args = parser.parse_args()
if __name__ == '__main__':
print(args.accumulate)
print(args.accumulate(args.integers))
argparse.ArgumentParser()
# 创建解析对象
parser = argparse.ArgumentParser(description="Process some integers",
epilog="And what can i do for u?")
# description:帮助文档之前
# epilog:帮助文档之后
效果图
parser.add_argument()
name or flags:
1、不带"–“的参数:positional arguments、必须输入、参数输入顺序与程序中定义的顺序一致; python arg.py 直接写参数值
2、带”-“的参数:optional arguments、可不输入; python arg.py 参数名(-x) 参数值
3、带”–"的参数:optional arguments、可不输入、参数别名; python arg.py 参数名(–x) 参数值
示例:
parser.add_argument(‘integer’)
parser.add_argument(‘-shortname’, ‘–name’)
metavar:参数值示例
dest:参数在程序中对应的变量名称;add_argument(“a”,dest=‘code_name’),好像和不带“–/-”的参数 不能 混合使用
type:默认string
nargs:
1、N:N个参数;
2、?:首先从命令行中获取,若没有,则从const中获取,仍然没有则从default中获取;
3、+或*:任意多个参数;
help:参数作用解释
action:
1、默认store;
2、action=“store_const”; 不能与 type 混用,即此时不能输入;
parser.add_argument('-test',action='store_const',const=12)
print(args.test)
#action='store_const' 不能与type一起使用
命令行:python untitled.py -test
output:12
命令行:python untitled.py -test 13 #报错
3、action= ‘store_true’ or ‘stror_false’
store_true:一旦有这个参数,做出动作“将其值标为True”,否则为“False”;
store_false:一旦有这个参数,做出动作“将其值标为False”,否则为“True”;
若同时有default,此种情况可参考这篇博客
parser = argparse.ArgumentParser()
parser.add_argument('--foo', action='store_true')
parser.add_argument('--bar', action='store_false')
parser.add_argument('--baz', action='store_false')
parser.parse_args('--foo --bar'.split())
Namespace(bar=False, baz=True, foo=True)
4、action=‘append’:将多次输入的参数值保存到一个list中;
parser.add_argument('-test',action='append')
print(args.test)
命令行:python untitled.py -test 12 -test 12
output:['12', '12']
命令行:python untitled.py -test 12 -test 13
output:['12', '13']
5、action=‘count’:遇到参数命令的次数;
parser.add_argument('-test',action='count')
print(args)
命令行:python untitled.py -test -test
output:Namespace<test=2>
const:配合action=‘store_const’或’append_const’
default:
choices:参数集合
例:choices=[1,3,5,7,9] 只能传入1,3,5,7,9
parser.parse_args()
args = parser.parse_args(['--sum', '7', '-1', '42'])
args = parser.parse_args()
上述内容,参考了一下博文(如有侵权,请联系删除)
【1】https://blog.csdn.net/foneone/article/details/103984895
【2】https://blog.csdn.net/liuweiyuxiang/article/details/82918911