创建解析

import argparse

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

添加参数 add_argument方法

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

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)')

参数

  • name or flags - 一个命名或者一个选项字符串的列表,例如 foo 或 -f, --foo。
  • action - 当参数在命令行中出现时使用的动作基本类型。
  • nargs - 命令行参数应当消耗的数目。
  • const - 被一些 action 和 nargs 选择所需求的常数。
  • default - 当参数未在命令行中出现时使用的值。
  • type - 命令行参数应当被转换成的类型。
  • choices - 可用的参数的容器。
  • required - 此命令行选项是否可省略 (仅选项可用)。
  • help - 一个此选项作用的简单描述。
  • metavar - 在使用方法消息中使用的参数值示例。
  • dest - 被添加到 parse_args() 所返回对象上的属性名。
name or flags

1.optional arguments 参数在使用时必须使用参数名,然后是参数具体数值,设置可以是无序的。

parser.add_argument('-f', '--foo')

2.positional arguments 参数按照参数设置的先后顺序对应读取,实际中不用设置参数名,必须有序设计。

parser.add_argument('bar')
action
  • ‘store’ - 存储参数的值。这是默认的动作。
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo')
>>> parser.parse_args('--foo 1'.split())
Namespace(foo='1')
  • ‘store_true’ and ‘store_false’
    这些是 ‘store_const’ 分别用作存储 True 和 False 值的特殊用例。另外,它们的默认值分别为 False 和 True。
>>> 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(foo=False, bar=True, baz=True)
nargs

参数的数量,有如下几个设定:

  • N:N个参数
  • ?:首先从命令行中获取,若没有则从const中获取,仍然没有则从default中获取
  • */+:任意多个参数
default

默认值

type

参数类型, 默认是str

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('foo', type=int)
>>> parser.add_argument('bar', type=open)
>>> parser.parse_args('2 temp.txt'.split())
Namespace(bar=<_io.TextIOWrapper name='temp.txt' encoding='UTF-8'>, foo=2)
required

是否为必选参数, 默认是false

dest

参数别名

help

参数的帮助信息,即解释信息

>>> parser.add_argument('--foo', action='store_true',
                        help='foo the bars before frobbling')
metavar

帮助信息中显示的参数名称

模板

parser = argparse.ArgumentParser()
parser.add_argument('-m', '--msg_p', action='store', dest="msg_path",
                   help="path")
parser.add_argument('-g', action='store', dest="graph",
                   help="input graph")
parser.add_argument('-p', action='store', dest="prizes",
                   help="input prizes")
parser.add_argument('-t', action='store', dest="terminals", default=None,
                   help="input terminals")
parser.add_argument('-o', action='store', dest="output", default='pcsf.graphml',
                   help="graphML format to cytoscape")
args = parser.parse_args()