为什么在 argparse 中,'True' 总是 'True'?

Why in argparse, a 'True' is always 'True'?

这里是最简单的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 运行 正确。

为什么?

您没有传入 False 对象。您正在传递 'False' 字符串,这是一个非零长度的字符串。

只有长度为 0 的字符串测试为假:

>>> 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

如果您必须解析其中包含TrueFalse的字符串,您必须明确地这样做:

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 将按照您的预期工作。