我想使用 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 = ["...
parser.add_argument('-f', action='store_false', default=False, dest='boolean_switch', help='Set a switch to false') parser.add_argument('-a', action='append', dest='collection', default=[], help='Add repeated values to a list') parser.add_argument('-A', action='append_const',...
将以上代码加入到之前的脚本中。定义一个可选参数default=True,这样即便不给该参数输入任何内容,其值默认为True。type=strtobool确保输入内容转变成boolean数据类型。否则,当该脚本在输入中传递时,它将是字符串数据类型。如果需要整数参数,也可以将其定义为type=int。help中的%(default)s)用来检索参数中的默认值。
我想使用 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 = ["--...
我想使用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_...
parser.set_defaults(test=False) args = parser.parse_args() print(args) 如果需要设置args.test为 True,那么执行python3 tmp.py --test;如果需要设置args.test为 False,执行python3 tmp.py --no_test。 References Parsing boolean values with argparse - Stack Overflow...
parser = argparse.ArgumentParser(description='Process some booleans.') group = parser.add_mutually_exclusive_group() group.add_argument('--foo', action='store_true', help='Foo option') group.add_argument('--bar', action='store_true', help='Bar option') ...
BooleanOptionalAction) >>> parser.parse_args(['--no-foo']) Namespace(foo=False) 创建自定义动作的推荐方式是扩展 Action,重载 __call__ 方法以及可选的 __init__ 和format_usage 方法。 一个自定义动作的例子: >>> >>> class FooAction(argparse.Action): ... def __init__(self, option_...
ArgumentTypeError('Boolean value expected.') def test_bool(): parser = argparse.ArgumentParser(description="This code is used to test bool value.") parser.add_argument("--flag", type=str2bool, default=True, help="Run or not.") args = parser.parse_args() print("# The type of flag:...
boolean_switch = False collection = [] const_collection = [] $ python argparse_action.py -t simple_value = None constant_value = None boolean_switch = True collection = [] const_collection = [] $ python argparse_action.py -f simple_value = None ...