下面是最简单的Python脚本,名为test.py:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--bool', default=True, type=bool, help='Bool type')
args = parser.parse_args()
print(args.bool)
但是当我在命令行上运行这段代码时:
python test.py --bool False
True
然而,当我的代码读取'--bool', default=False
时,argparse可以正确运行。
为什么?
发布于 2017-06-15 15:51:59
您没有传入False
对象。您传入的是'False'
字符串,这是一个长度非零的字符串。
只有长度为0的字符串测试为false:
>>> bool('')
False
>>> bool('Any other string is True')
True
>>> bool('False') # this includes the string 'False'
True
请改用store_true
or store_false
action。对于default=True
,请使用store_false
parser.add_argument('--bool', default=True, action='store_false', help='Bool type')
现在省略开关将args.bool
设置为True
,使用--bool
(不带其他参数)将args.bool
设置为False
python test.py
True
python test.py --bool
False
如果必须解析包含True
或False
的字符串,则必须显式执行此操作:
def boolean_string(s):
if s not in {'False', 'True'}:
raise ValueError('Not a valid boolean string')
return s == 'True'
并将其用作转换参数:
parser.add_argument('--bool', default=True, type=boolean_string, help='Bool type')
在这一点上,--bool False
将如您所期望的那样工作。
https://stackoverflow.com/questions/44561722
复制相似问题