首頁  >  文章  >  後端開發  >  如何在 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