parser.add_argument('-auto', action='store_true')
如果未指定-auto
,我如何存储假?我可以隐约记得这样,如果没有指定,它会存储None
答案 0 :(得分:116)
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
答案 1 :(得分:8)
使用
import argparse
parser=argparse.ArgumentParser()
parser.add_argument('-auto', action='store_true', )
args=parser.parse_args()
print(args)
运行
% test.py
产量
Namespace(auto=False)
所以它似乎默认存储False
。
答案 2 :(得分:0)
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
答案 3 :(得分:-2)
store_false实际默认为0
(您可以测试验证)。要更改默认设置,只需在声明中添加default=True
即可。
所以在这种情况下:
parser.add_argument('-auto', action='store_true', default=True)