python argparser解析

目录
  1. 创建
  2. 添加参数
  3. 解析参数

parser是python标准库的一个参数解析模块,通过使用’import argparse’即可导入使用,可方便编写命令行接口。当命令有错时其会自动产生错误提示信息。

创建

1
>>> parser = argparse.ArgumentParser(description='Process some integers.')

添加参数

通过使用add_argument函数可以添加参数信息,其原型为:

1
ArgumentParser.add_argument(name or flags…[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])

示例如下

1
2
3
4
5
>>> 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)')

函数中的参数说明如下:

  • type
    type 指出了参数的类型,如int, double
    parser.add_argument(‘intergers’, type=int, nargs=’+’)
  • nargs
    表示参数的个数,’+’表示1个以上,’*’表示0个以上
  • action
    action 参数指出了解析参数的动作, 如count表示计数,store_const
  • help
    为该参数的帮助信息
  • default
    默认值或者默认行为
  • metavar
    usage提示信息中的参数名
  • const
    常量或者固定的行为,通过匹配参数选项来决定,但不能通过输入指定,如例子中的const=sum
  • dest
    parse_args的返回值名称

解析参数

1
2
>>> args = parser.parse_args()
>>> print args.accumulate(args.integers)

运行上面的例子:

1
2
3
4
5
$ python prog.py 1 2 3 4
4
$ python prog.py 1 2 3 4 --sum
10

parser支持更多选项,请查阅其官网文档argparse — Parser for command-line options, arguments and sub-commands

入门资料:
Argparse Tutorial

本站总访问量