首页  >  文章  >  后端开发  >  如何在 Python 中使用 argparse 正确处理布尔参数?

如何在 Python 中使用 argparse 正确处理布尔参数?

Susan Sarandon
Susan Sarandon原创
2024-10-28 08:11:30477浏览

How to Properly Handle Boolean Arguments with argparse in Python?

在 argparse 中处理布尔参数

可以使用 Python 中的 argparse 模块简化从命令行解析参数。虽然它支持解析布尔标志,但某些情况可能会导致意外结果。

要正确解析“--foo True”或“--foo False”等布尔值,argparse 的默认行为可能不够。例如,当参数设置为“False”或空字符串时,单独使用 type=bool 可能会导致意外结果。

一种解决方案是利用 Python 3.9 中引入的 BooleanOptionalAction。此操作提供了更直观的布尔值处理,自动将 True、t、y、yes 和 1 转换为 True,将 False、f、n、no 和 0 转换为 False。

适用于之前的 Python 版本3.9 中,解决方法涉及组合“store_true”和“store_false”操作。 'store_true' 操作将标志设置为 True(如果存在),而 'store_false' 将其设置为 False。默认情况下,该标志假定为 True,允许用户指定正标志和负标志:

<code class="python">import argparse

parser = argparse.ArgumentParser(description="My parser")
parser.add_argument('--feature', action='store_true')
parser.add_argument('--no-feature', dest='feature', action='store_false')
parser.set_defaults(feature=True)

cmd_line = ["--no-feature"]
parsed_args = parser.parse_args(cmd_line)

if parsed_args.feature:
    print("Feature is True.")
else:
    print("Feature is False.")</code>

或者,可以定义自定义函数来处理特定的解析逻辑。例如,一个不区分大小写区分“True”和“False”的函数:

<code class="python">def t_or_f(arg):
    ua = str(arg).upper()
    if 'TRUE'.startswith(ua):
        return True
    elif 'FALSE'.startswith(ua):
        return False
    else:
        raise ValueError("Invalid argument: {}".format(arg))</code>

此函数可以与 argparse 的类型参数一起使用:

<code class="python">import argparse

parser = argparse.ArgumentParser(description="My parser")
parser.add_argument('--my_bool', type=t_or_f)

cmd_line = ["--my_bool", "False"]
parsed_args = parser.parse_args(cmd_line)

if parsed_args.my_bool:
    print("my_bool is True.")
else:
    print("my_bool is False.")</code>

以上是如何在 Python 中使用 argparse 正确处理布尔参数?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn