使用argparse解析布爾值我想使用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解析"False","F"以及它們的小寫變體False?
3 回答

慕桂英3389331
TA貢獻2036條經驗 獲得超8個贊
使用之前建議的另一種解決方案,但具有“正確”解析錯誤argparse
:
def str2bool(v): if isinstance(v, bool): return v if v.lower() in ('yes', 'true', 't', 'y', '1'): return True elif v.lower() in ('no', 'false', 'f', 'n', '0'): return False else: raise argparse.ArgumentTypeError('Boolean value expected.')
這對于使用默認值制作開關非常有用; 例如
parser.add_argument("--nice", type=str2bool, nargs='?', const=True, default=False, help="Activate nice mode.")
允許我使用:
script --nice script --nice <bool>
并仍然使用默認值(特定于用戶設置)。這種方法的一個(間接相關的)缺點是'nargs'可能會捕獲位置參數 - 請參閱此相關問題和這個argparse錯誤報告。

四季花海
TA貢獻1811條經驗 獲得超5個贊
我認為一個更規范的方法是通過:
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)
當然,如果你真的想要--arg <True|False>
版本,你可以傳遞ast.literal_eval
“類型”或用戶定義的函數...
def t_or_f(arg): ua = str(arg).upper() if 'TRUE'.startswith(ua): return True elif 'FALSE'.startswith(ua): return False else: pass #error condition maybe?

紅顏莎娜
TA貢獻1842條經驗 獲得超13個贊
我建議mgilson的答案,但有互相排斥的群體
,這樣就可以不使用--feature
,并--no-feature
在同一時間。
command --feature
和
command --no-feature
但不是
command --feature --no-feature
腳本:
feature_parser = parser.add_mutually_exclusive_group(required=False)feature_parser.add_argument('--feature', dest='feature', action='store_true')feature_parser.add_argument('--no-feature', dest='feature', action='store_false')parser.set_defaults(feature=True)
如果要設置其中許多幫助,則可以使用此幫助程序:
def add_bool_arg(parser, name, default=False): group = parser.add_mutually_exclusive_group(required=False) group.add_argument('--' + name, dest=name, action='store_true') group.add_argument('--no-' + name, dest=name, action='store_false') parser.set_defaults(**{name:default})add_bool_arg(parser, 'useful-feature')add_bool_arg(parser, 'even-more-useful-feature')
添加回答
舉報
0/150
提交
取消