Python-用argparse解析布尔值

Python-用argparse解析布尔值,第1张

Python-用argparse解析布尔值

另一个解决方案使用了先前的建议,但存在来自

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>


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5587941.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-15
下一篇2022-12-15

发表评论

登录后才能评论

评论列表(0条)

    保存