argparse布尔参数传入False仍被解析为True该如何修复?
问题原因
Python argparse 模块中直接指定 type=bool 无法正确解析命令行传入的布尔字符串:
bool()函数的逻辑是只要传入非空字符串就返回True,你传入的False本质是字符串"False",所以bool("False")运行结果为True,和预期不符。
修复方案
方案1:使用argparse内置的布尔参数动作(最推荐)
把参数配置中的type=bool改为action='store_true',不需要额外传True/False值:
- 命令行传
-rm参数时,remove_ads值为True - 不传时使用默认值
False
修改后代码:
parser.add_argument( "-rm", "--remove_ads", action="store_true", # 替换原来的type=bool required=False, default=False, help="Should remove disapproved ads. Default: false", ) args = parser.parse_args() _REMOVE_ADS = args.remove_ads print(_REMOVE_ADS)
使用方式:要开启去广告就执行 python your_script.py -rm,不需要加后面的True;不需要去广告就直接执行 python your_script.py 即可。
方案2:自定义布尔解析函数(需要显式传True/False的场景)
如果你的使用习惯需要显式传入True/False值,可以自定义类型转换逻辑:
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( "-rm", "--remove_ads", type=str2bool, # 替换成自定义转换函数 required=False, default=False, help="Should remove disapproved ads. Default: false", ) args = parser.parse_args() _REMOVE_ADS = args.remove_ads print(_REMOVE_ADS)
这种方式下执行 python your_script.py -rm False 就能正确得到 _REMOVE_ADS 为 False。
内容的提问来源于stack exchange,提问作者Elad Benda
相关产品推荐
相关产品推荐

