Argparse
是 Python
标准库中推荐的命令行解析模块,经常需要解析脚本参数的话这是个方便的工具模块,摆脱万年手动 system.argv
。
引入
1 2 3
| import argparse parser = argparse.ArgumentParser(description='描述说明,可用于 Help 输出说明', add_help=True) parser.parse_args()
|
ArgumentParser
可选参数如下:
- prog – 此脚本程序名称 (默认: sys.argv[0])
- usage – 用法说明 (默认: 根据参数自动生成)
- description – 脚本说明
- epilog – 也是说明,在 help 输出最后
- parents – 父 Parsers
- formatter_class – 输出帮助信息的定制类
- prefix_chars – 可选前缀参数字符(设置后参数名称需以此为前缀)
- fromfile_prefix_chars – 从文件读取可选前缀参数字符
- argument_default – 所有参数的默认值
- conflict_handler – 冲突处理器
- add_help – 是否添加帮助
常用方法
add_argument()
// test.py
1 2 3 4 5
| import argparse parser = argparse.ArgumentParser() parser.add_argument('-p', '--param') args = parser.parse_args() print args.param
|
运行 python test.py -p value
or python test.py --param value
即可。
add_argument 可选方法参数如下:
- name or flags - 参数的名字.
- 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 - 参数的类型. 如 int、str
- choices - 参数允许的值. 如:[‘a’, ‘b’, ‘c’]
- required - 可选参数是否可以省略(仅针对 optionals ).
- help - 参数的帮助信息,当指定为 argparse.SUPPRESS 时表示不显示该参数的帮助信息.
- metavar - 在usage说明中的参数名称,对于必选参数默认就是参数名称,对于可选参数默认是全大写的参数名称.
- dest - 解析后的参数名称,默认情况下,对于可选参数选取最长的名称,中划线转换为下划线.
add_mutually_exclusive_group()
设置冲突参数,当需要设置指定输入参数只能包含其中一个时即可用此方法。
// test.py
1 2 3 4 5
| parse = argparse.ArgumentParser() group = parse.add_mutually_exclusive_group() group.add_argument("-a", action="store_true") group.add_argument("-b", action="store_true") args = parse.parse_args()
|
此种情形下 test.py 输入参数只能包含 a 或 b, a、b 不能同时存在。
add_argument_group()
参数分组设置。当有分组命令的需求时可用,输入参数将归于所属分组下。
1 2 3 4
| parse = argparse.ArgumentParser() some_group = parse.add_argument_group('Publish plugin') some_group.add_argument('-f' type=str)
|
add_subparsers()
子命令模式,类似 git commit
、 git push
等命令.
1 2 3
| parse = argparse.ArgumentParser() sub_parse = parse.add_subparsers()
|
Sample
下面由一个使用场景说起。一个脚本:publish.py
,包含两个功能:发布和查询,运行环境有测试服和正式服,发布时需要两个账号系统的密码,查询时需要一个账号系统的密码和版本、渠道参数。那么脚本如下,其它见注释:
// publish.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| import argparse def get_args(): parse = argparse.ArgumentParser(description='Publish tools.', add_help=True) group = parse.add_mutually_exclusive_group(required=True) group.add_argument("-s", "--Search", action="store_true") group.add_argument("-p", "--Publish", action="store_true") parse.add_argument('-e', '--Env', type=str, help='Running environment', choices=['test', 'product'], default='test') parse.add_argument('-a', '--ApiAuth', required=True, type=str, help='username:password') publish_group = parse.add_argument_group('Publish') publish_group.add_argument('-f', '--FtpAuth', type=str, help='username:password') search_group = parse.add_argument_group('Search') search_group.add_argument('-c', '--channel', type=str, help='channel') search_group.add_argument('-v', '--versonCode', type=int, help='Search verson code') args = parse.parse_args() return vars(args) args=get_args() print 'opt search?:', args['Search'],' opt publish?:', args['Publish'], '\n', args
|
publish.py -h
使用帮助如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| usage: test.py [-h] (-s | -p) [-e {test,product}] -a APIAUTH [-f FTPAUTH] [-c CHANNEL] [-v HOSTVERSONCODE] Publish tools. optional arguments: -h, --help show this help message and exit -s, --Search -p, --Publish -e {test,product}, --Env {test,product} Running environment -a APIAUTH, --ApiAuth APIAUTH username:password Publish plugin: -f FTPAUTH, --FtpAuth FTPAUTH username:password Search plugin: -c CHANNEL, --channel CHANNEL channel -v VERSONCODE, --VersonCode VERSONCODE Search verson code
|
使用如下:
1 2 3 4
| # 1 publish python publish.py -p -a U:P -f U:P # 2 search python publish.py -s -a U:P -c channel -v 100
|