我想使用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("")的值为False。

我怎么能得到argparse解析“假”,“F”,和他们的小写变体为假?


当前回答

类似的用法是:

feature.add_argument('--feature',action='store_true')

如果你在命令中设置参数-feature

 command --feature

参数将为True,如果你不设置type -feature参数默认为False!

其他回答

这其实已经过时了。对于Python 3.7+, Argparse现在支持布尔参数(search BooleanOptionalAction)。

实现如下所示:

import argparse

ap = argparse.ArgumentParser()

# List of args
ap.add_argument('--foo', default=True, type=bool, help='Some helpful text that is not bar. Default = True')

# Importable object
args = ap.parse_args()

还有一件事需要提到:这将阻塞通过argparse.ArgumentTypeError参数的除True和False以外的所有条目。如果您出于任何原因想要尝试更改它,您可以为此创建一个自定义错误类。

简单的。它不灵活,但我更喜欢简单。

  parser.add_argument('--boolean_flag',
                      help='This is a boolean flag.',
                      type=eval, 
                      choices=[True, False], 
                      default='True')

编辑:如果你不相信输入,不要使用eval。

下面是另一种变体,没有额外的行/秒来设置默认值。布尔值总是被赋值,这样它就可以在逻辑语句中使用,而无需事先检查:

import argparse
parser = argparse.ArgumentParser(description="Parse bool")
parser.add_argument("--do-something", default=False, action="store_true",
                    help="Flag to do something")
args = parser.parse_args()

if args.do_something:
     print("Do something")
else:
     print("Don't do something")

print(f"Check that args.do_something={args.do_something} is always a bool.")

类似的用法是:

feature.add_argument('--feature',action='store_true')

如果你在命令中设置参数-feature

 command --feature

参数将为True,如果你不设置type -feature参数默认为False!

oneliner:

parser.add_argument('--is_debug', default=False, type=lambda x: (str(x).lower() == 'true'))