argparse笔记
argparse介绍
argparse
模块用于编写命令行接口,将命令行参数传入程序中。argparse
模块还会自动生成帮助和使用手册,并在用户给程序传入无效参数时报出错误信息。
实例:
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='You can write some description at here.',epilog='the message at the end of help doc')
parser.add_argument('args1',type=int,help='the help of args1')
parser.add_argument('--args2', help='the help of args2')
args = parser.parse_args()
print(args.args1)
这是一个最简单的示例,添加了两个参数:位置参数args1,可选参数args2.
运行帮助文档:
(torch131) D:\CV\Python-Note\programs>python Argparse.py --help
usage: Argparse.py [-h] [--args2 ARGS2] args1
You can write some description at here.
positional arguments:
args1 the help of args1
optional arguments:
-h, --help show this help message and exit
--args2 ARGS2 the help of args2
the message at the end of help doc
(torch131) D:\CV\Python-Note\programs>python Argparse.py 2
2
可以看到,帮助文档分为4个部分:usage,必须参数,可选参数,文末说明。
位置参数不能带参数名。python Argparse.py args1 2会报错
创建解析器
使用 argparse 的第一步是创建一个ArgumentParser对象。
parser = argparse.ArgumentParser(description='You can write some description at here.')
ArgumentParser的初始化可选参数有很多,但大多数平时都用不到。
def __init__(self,
prog=None,
usage=None,
description=None,
epilog=None,
parents=[],
formatter_class=HelpFormatter,
prefix_chars='-',
fromfile_prefix_chars=None,
argument_default=None,
conflict_handler='error',
add_help=True,
allow_abbrev=True):
- prog - 程序的名称(默认:
sys.argv[0]
) - usage - 描述程序用途的字符串(默认值:从添加到解析器的参数生成)
- description - 在参数帮助文档之前显示的文本(默认值:无)
- epilog - 在参数帮助文档之后显示的文本(默认值:无)
- parents - 一个
ArgumentParser
对象的列表,它们的参数也应包含在内 - formatter_class - 用于自定义帮助文档输出格式的类
- prefix_chars - 可选参数的前缀字符集合(默认值:’-’)
- fromfile_prefix_chars - 当需要从文件中读取其他参数时,用于标识文件名的前缀字符集合(默认值:
None
) - argument_default - 参数的全局默认值(默认值:
None
) - conflict_handler - 解决冲突选项的策略(通常是不必要的)
- add_help - 为解析器添加一个
-h/--help
选项(默认值:True
) - allow_abbrev - 如果缩写是无歧义的,则允许缩写长选项 (默认值:
True
)
添加参数
在创建解析器之后,需要添加参数,此参数与命令行需要的参数对应。
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 - 命令行参数应该被转换成的类型,默认的参数都是str类型的。
- choices - 参数可允许的值的一个容器。
- required - 可选参数是否可以省略 (仅针对可选参数)。
- help - 参数的帮助信息,当指定为 argparse.SUPPRESS 时表示不显示该参数的帮助信息.
- metavar - 在 usage 说明中的参数名称,对于必选参数默认就是参数名称,对于可选参数默认是全大写的参数名称.
- dest - 解析后的参数名称,默认情况下,对于可选参数选取最长的名称,中划线转换为下划线.
特别需要注意的是:对于可选参数,通常情况下可以必须指定值。或者对action进行添加。
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='You can write some description at here.',epilog='the message at the end of help doc')
parser.add_argument('args1',type=int,help='the help of args1')
parser.add_argument('--args2', help='the help of args2')
args = parser.parse_args()
print(args.args1)
if args.args2:
print('args2 exists!')
运行:
(torch131) D:\CV\Python-Note\programs>python Argparse.py 2 --args2
usage: Argparse.py [-h] [--args2 ARGS2] args1
Argparse.py: error: argument --args2: expected one argument
改为:parser.add_argument('--args2', action='store_true',help='the help of args2')
运行:
(torch131) D:\CV\Python-Note\programs>python Argparse.py 2 --args2
2
args2 exists!
同时,对于可选参数,可以赋予其缺省值。
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='You can write some description at here.',
epilog='the message at the end of help doc')
parser.add_argument('args1',type=int,choices=[1,2,3],help='the help of args1')
parser.add_argument('--args2',default='This is default', action='store_true',help='the help of args2')
args = parser.parse_args()
print(args.args1)
if args.args2:
print(args.args2)
输出:
(torch131) D:\CV\Python-Note\programs>python Argparse.py 1
1
This is default
可利用dest修改解析后的参数名,在程序中不得再使用args2这个变量名。
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='You can write some description at here.',
epilog='the message at the end of help doc')
parser.add_argument('args1',type=int,choices=[1,2,3],help='the help of args1')
parser.add_argument('--args2',dest='a2',default='This is default', action='store_true',help='the help of args2')
args = parser.parse_args()
print(args.args1)
if args.a2:
print(args.a2)
解析参数
ArgumentParser
通过 parse_args()
方法解析参数。它将检查命令行,把每个参数转换为适当的类型然后调用相应的操作。在大多数情况下,这意味着一个简单的 Namespace
对象将从命令行参数中解析出的属性构建。