解析与argparse布尔值 [英] parsing boolean values with argparse
问题描述
我想用argparse解析写成--foo这样真或假--foo这样的布尔命令行参数。例如:
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
但是,下面的测试code不这样做,我想什么:
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
计算结果为真
。这种情况甚至当我换 cmd_line
是 [ - my_bool,]
,这是奇怪,因为布尔()
evalutates到假
。
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解析假
,F
,和他们的小写变体为假
?
How can I get argparse to parse "False"
, "F"
, and their lower-case variants to be False
?
推荐答案
我觉得更规范的方式做到这一点是通过:
I think a more canonical way to do this is via:
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)
当然,如果你真的想在 - 精氨酸<真|假>
版本,可以通过 ast.literal_eval
作为类型,或用户定义的函数...
Of course, if you really want the --arg <True|False>
version, you could pass ast.literal_eval
as the "type", or a user defined function ...
def t_or_f(arg):
ua = str(arg).upper()
if ua == 'TRUE'[:len(ua)]:
return True
elif ua == 'FALSE'[:len(ua)]:
return False
else:
pass #error condition maybe?
这篇关于解析与argparse布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!