这是最简单的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)
Run Code Online (Sandbox Code Playgroud)
但是当我在命令行上运行此代码时:
python test.py --bool False
True
Run Code Online (Sandbox Code Playgroud)
而当我的代码读取时'--bool', default=False,argparse正确运行.
为什么?
Mar*_*ers 24
你没有传入这个False对象.你传入的是'False'字符串,这是一个非零长度的字符串.
只有一串长度为0的测试为false:
>>> bool('')
False
>>> bool('Any other string is True')
True
>>> bool('False') # this includes the string 'False'
True
Run Code Online (Sandbox Code Playgroud)
请改用store_true或store_false使用动作.对于default=True,使用store_false:
parser.add_argument('--bool', default=True, action='store_false', help='Bool type')
Run Code Online (Sandbox Code Playgroud)
现在省略开关组args.bool到True,使用--bool(没有进一步的参数)设定args.bool到False:
python test.py
True
python test.py --bool
False
Run Code Online (Sandbox Code Playgroud)
如果你必须用True或False在里面解析一个字符串,你必须明确地这样做:
def boolean_string(s):
if s not in {'False', 'True'}:
raise ValueError('Not a valid boolean string')
return s == 'True'
Run Code Online (Sandbox Code Playgroud)
并将其用作转换参数:
parser.add_argument('--bool', default=True, type=boolean_string, help='Bool type')
Run Code Online (Sandbox Code Playgroud)
此时--bool False将按预期工作.