argparse模块中的action参数

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/liuweiyuxiang/article/details/82918911

用argparse模块让python脚本接收参数时,对于True/False类型的参数,向add_argument方法中加入参数action=‘store_true’/‘store_false’。
顾名思义,store_true就代表着一旦有这个参数,做出动作“将其值标为True”,也就是没有时,默认状态下其值为False。反之亦然,store_false也就是默认为True,一旦命令中有此参数,其值则变为False。

>>> 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(bar=False, baz=True, foo=True)

本人测试的另一个指定default的例子:
代码如下:

import argparse

parser = argparse.ArgumentParser(description="description")

parser.add_argument('--pa','-a',action='store_true')
parser.add_argument('--pb','-b',action="store_true",default=True)
parser.add_argument('--pc','-c',action="store_true",default=False)

parser.add_argument('--pd','-d',action='store_false')
parser.add_argument('--pe','-e',action="store_false",default=True)
parser.add_argument('--pf','-f',action="store_false",default=False)

args = parser.parse_args()
print(args)

输出结果如下:
在这里插入图片描述
分析:
可以看到如果指定参数出现,则action_true/false起作用,如果参数不出现default起作用。

参考博文:

  1. 小知识:action=‘store_true’(argparse模块中ArgumentParser对象的add_argument方法)
  2. action=‘store_true’

猜你喜欢

转载自blog.csdn.net/liuweiyuxiang/article/details/82918911