【问题标题】:Why in argparse, a 'True' is always 'True'? [duplicate]为什么在 argparse 中,“真”总是“真”? [复制]
【发布时间】:2017-11-17 14:33:10
【问题描述】:

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

为什么?

【问题讨论】:

    标签: python argparse


    【解决方案1】:

    您没有传入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.boolTrue,使用--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 将按照您的预期工作。

    【讨论】:

    • 标准库函数 distutils.util.strtobool() 函数可以用来代替 boolean_string() 并且还支持像“yes”和“no”这样的字符串(虽然它返回一个 0 或 1 的 int 所以你可能仍然如果你真的需要一个合适的布尔值,想包装它)
    猜你喜欢
    • 2020-09-04
    • 1970-01-01
    • 2015-05-09
    • 2018-06-06
    • 2022-11-10
    • 2015-08-19
    • 2016-09-06
    • 2017-04-28
    • 1970-01-01
    相关资源
    最近更新 更多