另一个解决方案使用了先前的建议,但存在来自
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 --nicescript --nice <bool>



