用argpars解析布尔值

2024-04-25 17:24:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用argparse来解析写为“-foo True”或“-foo False”的布尔命令行参数。例如:

my_program --my_boolean_flag False

但是,以下测试代码并没有按我的要求执行:

import argparse
parser = argparse.ArgumentParser(description="My parser")
parser.add_argument("--my_bool", type=bool)
cmd_line = ["--my_bool", "False"]
parsed_args = parser.parse(cmd_line)

遗憾的是,parsed_args.my_bool的计算结果是True。甚至当我把cmd_line改为["--my_bool", ""]时也是这样,这是令人惊讶的,因为bool("")将evalute改为False

如何让argparse解析"False""F",以及它们的小写变量False


Tags: 命令行cmdfalsetrueparser参数foomy
3条回答

我认为一个更规范的方法是通过:

command --feature

以及

command --no-feature

argparse很好地支持此版本:

parser.add_argument('--feature', dest='feature', action='store_true')
parser.add_argument('--no-feature', dest='feature', action='store_false')
parser.set_defaults(feature=True)

当然,如果您真的需要--arg <True|False>版本,可以将ast.literal_eval作为“类型”传递,或者传递用户定义的函数。。。

def t_or_f(arg):
    ua = str(arg).upper()
    if 'TRUE'.startswith(ua):
       return True
    elif 'FALSE'.startswith(ua):
       return False
    else:
       pass  #error condition maybe?

我推荐mgilson的答案,但有一个相互排斥的组
这样就不能同时使用--feature--no-feature

command --feature

以及

command --no-feature

但不是

command --feature --no-feature

脚本:

feature_parser = parser.add_mutually_exclusive_group(required=False)
feature_parser.add_argument('--feature', dest='feature', action='store_true')
feature_parser.add_argument('--no-feature', dest='feature', action='store_false')
parser.set_defaults(feature=True)

如果要设置许多辅助对象,则可以使用此辅助对象:

def add_bool_arg(parser, name, default=False):
    group = parser.add_mutually_exclusive_group(required=False)
    group.add_argument('--' + name, dest=name, action='store_true')
    group.add_argument('--no-' + name, dest=name, action='store_false')
    parser.set_defaults(**{name:default})

add_bool_arg(parser, 'useful-feature')
add_bool_arg(parser, 'even-more-useful-feature')

另一个解决方案使用了前面的建议,但是有来自argparse的“正确”解析错误:

def str2bool(v):
    if isinstance(v, bool):
       return v
    if v.lower() in ('yes', 'true', 't', 'y', '1'):
        return True
    elif v.lower() in ('no', 'false', 'f', 'n', '0'):
        return False
    else:
        raise argparse.ArgumentTypeError('Boolean value expected.')

这对于使用默认值进行切换非常有用;例如

parser.add_argument("--nice", type=str2bool, nargs='?',
                        const=True, default=False,
                        help="Activate nice mode.")

允许我使用:

script --nice
script --nice <bool>

仍然使用默认值(特定于用户设置)。这种方法的一个(间接相关的)缺点是“nargs”可能捕获一个位置参数——请参见this related questionthis argparse bug report

相关问题 更多 >