问题描述
我想使用 argparse 来解析写为--foo True"或--foo False"的布尔命令行参数.例如:
I would like to use argparse to parse boolean command-line arguments written as "--foo True" or "--foo False". For example:
my_program --my_boolean_flag False
然而,下面的测试代码没有做我想要的:
However, the following test code does not do what I would like:
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
.
Sadly, parsed_args.my_bool
evaluates to True
. This is the case even when I change cmd_line
to be ["--my_bool", ""]
, which is surprising, since bool("")
evalutates to False
.
如何让 argparse 解析 "False"
、"F"
和它们的小写变体为 False
?
How can I get argparse to parse "False"
, "F"
, and their lower-case variants to be False
?
推荐答案
这实际上已经过时了.对于 Python 3.7+,Argparse 现在支持布尔参数(搜索 BooleanOptionalAction).
This is actually outdated. For Python 3.7+, Argparse now supports boolean args (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 参数之外的所有条目.如果您出于任何原因想尝试更改它,您可以为此创建一个自定义错误类.
One other thing to mention: this will block all entries other than True and False for the argument via argparse.ArgumentTypeError. You can create a custom error class for this if you want to try to change this for any reason.
这篇关于使用 argparse 解析布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!