1.基本方法介绍
import argparse #倒入模块
parser = argparse.ArgumentParser() #创建参数解析对象
parser.add_argument("-p", "--plugin", help="run the plugin case", default='business',type=int) #添加参数
args = parser.parse_args() #获取参数集
print(args.plugin) #取具体参数
group = argparse.add_mutually_exclusive_group() #互斥组
group.add_argument("-c", "--compare", help="result|database") #互斥组内添加参数
2.参数解析
2.1 选项与位置参数
add_argument() 方法必须知道它是否是一个选项,例如 -f
或 --foo
,或是一个位置参数
parser.add_argument('-f', '--foo') #选项
parser.add_argument('bar') #位置参数
当 parse_args() 被调用,选项会以 -
前缀识别,剩下的参数则会被假定为位置参数:
2.2 action
action
命名参数指定了这个命令行参数应当如何处理。
'store_const'
- 存储被 const 命名参数指定的值。 'store_const'
动作通常用在选项中来指定一些标志。
parser.add_argument('--foo', action='store_const', const=42)
>>> parser.parse_args(['--foo'])
'store_true'
and 'store_false'
- 这些是 'store_const'
分别用作存储 True
和 False
值的特殊用例。另外,它们的默认值分别为 False
和 True
。
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=True, bar=False, baz=True)
'append'
- 存储一个列表,并且将每个参数值追加到列表中。在允许多次使用选项时很有用。
parser.add_argument('--foo', action='append')
>>> parser.parse_args('--foo 1 --foo 2'.split())
Namespace(foo=['1', '2'])
'append_const'
- 这存储一个列表,并将 const 命名参数指定的值追加到列表中。(注意 const 命名参数默认为 None
。)``'append_const'`` 动作一般在多个参数需要在同一列表中存储常数时会有用
parser.add_argument('--str', dest='types', action='append_const', const=str)
>>> parser.add_argument('--int', dest='types', action='append_const', const=int)
>>> parser.parse_args('--str --int'.split())
Namespace(types=[<class 'str'>, <class 'int'>])
*action其他使用方法请参照官方文档
2.3 nargs
nargs
命名参数关联不同数目的命令行参数到单一动作。
parser.add_argument('--foo', nargs=2)
--foo a b
Namespace(foo=['a', 'b'])
'*'
。所有当前命令行参数被聚集到一个列表中。注意通过 nargs='*'
来实现多个位置参数通常没有意义,但是多个选项是可能的。
parser.add_argument('--foo', nargs='*')
>>> parser.add_argument('--bar', nargs='*')
>>> parser.add_argument('baz', nargs='*')
>>> parser.parse_args('a b --foo x y --bar 1 2'.split())
Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y'])
2.4 default 默认值
add_argument() 的命名参数 default
,默认值为 None
,指定了在命令行参数未出现时应当使用的值。
parser.add_argument('--length', default='10', type=int)
>>> parser.add_argument('--width', default=10.5, type=int)
>>> parser.parse_args()
Namespace(length=10, width=10.5)
2.5 type -类型
默认情况下,解析器会将命令行参数当作简单字符串读入。 然而,命令行字符串经常应当被解读为其他类型,例如 float 或 int。 add_argument() 的 type
关键字允许执行任何必要的类型检查和类型转换。
parser.add_argument('count', type=int)
parser.add_argument('distance', type=float)
parser.add_argument('street', type=ascii)
parser.add_argument('code_point', type=ord)
parser.add_argument('source_file', type=open)
2.6 choices
某些命令行参数应当从一组受限值中选择。 这可通过将一个容器对象作为 choices 关键字参数传给 add_argument() 来处理。 当执行命令行解析时,参数值将被检查,如果参数不是可接受的值之一就将显示错误消息:
>>> parser.add_argument('move', choices=['rock', 'paper', 'scissors'])
>>> parser.parse_args(['rock'])
Namespace(move='rock')
>>> parser.parse_args(['fire'])
usage: game.py [-h] {rock,paper,scissors}
game.py: error: argument move: invalid choice: 'fire' (choose from 'rock',
'paper', 'scissors')
2.7 required 是否必选参数
argparse 模块会认为 -f
和 --bar
等旗标是指明 可选的 参数,它们总是可以在命令行中被忽略。 要让一个选项成为 必需的,则可以将 True
作为 required=
关键字参数传给 add_argument()
parser.add_argument('--foo', required=True)
>>> parser.parse_args(['--foo', 'BAR'])
Namespace(foo='BAR')
>>> parser.parse_args([])
usage: [-h] --foo FOO
: error: the following arguments are required: --foo
以上基本满足常规使用,更多使用方法参考官方文档
官方文档参考: