parser.add_argument('-auto', action='store_true')
如果未指定 -auto
,如何存储 false?我依稀记得这种情况会将 None 存储下来。
parser.add_argument('-auto', action='store_true')
如果未指定 -auto
,如何存储 false?我依稀记得这种情况会将 None 存储下来。
store_true
选项会自动创建默认值为 False。
同样地,当命令行参数不存在时,store_false
选项默认为 True。
这种行为的源代码非常简洁明了: http://hg.python.org/cpython/file/2.7/Lib/argparse.py#l861
尽管 argparse 文档对这个主题不够清晰,但我现在会对其进行更新:http://hg.python.org/cpython/rev/49677cc6d83a
使用
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-flag', action='store_true')
args = parser.parse_args()
print(args.flag)
False
False
。Raymond Hettinger已经回答了OP的问题。
然而,我们的团队在使用"store_false"时遇到了可读性问题,特别是当新成员加入我们的团队时。这是因为最直观的思考方式是,当用户指定一个参数时,与该参数对应的值将是True或1。
例如,如果代码是 -
parser.add_argument('--stop_logging', action='store_false')
当stop_logging的值为true时,代码读取器可能会期望记录语句关闭。但是像下面的代码将导致与预期行为相反 -
if not stop_logging:
#log
另一方面,如果接口定义如下,则"if语句"有效,并且更易于阅读 -
parser.add_argument('--stop_logging', action='store_true')
if not stop_logging:
#log
parser.add_argument('--stop_logging', action='store_false', dest='use_logging')
。 - Krassi我发现在未指定时,默认值在OSX和Linux之间有所不同。
使用以下代码行:
parser.add_argument('-auto', action='store_true')
然后在命令行中省略-auto,结果是在Mac上将自动分配一个值为False,正如预期的那样,而在Ubuntu Linux上,默认情况下将分配True给auto。
store_false 实际上默认为 0
(您可以测试以验证)。 要更改其默认值,只需在声明中添加 default=True
。
因此,在这种情况下:
parser.add_argument('-auto', action='store_true', default=True)
`>>> parser.add_argument('--bar', action='store_false')`
`_StoreFalseAction(option_strings=['--bar'], dest='bar', nargs=0, const=False, default=True, type=None, choices=None, help=None, metavar=None)`
`>>> parser.parse_args([])`
`Namespace(bar=True)`
- Leynos
./my_python_script --do_something
,那么do_something将被设置为'True'。相反,如果对于同样的cmdline,action='store_false',那么do_something将被设置为'False'。 - ZeZNiQstore_true
选项会自动创建默认值False,需要澄清的是当arg选项不存在时也是默认值。简而言之,如果找到arg选项,store_true
会分配True; 如果找到arg选项,store_false
会分配False。如果未找到arg选项,则分配默认值(请检查答案的前两行),人们称之为“反面惯例”,经过一些澄清后我认为不会引起混淆。 - milpita