当对字符串使用bool函数时,对于没有值的字符串(也就是None或者空字符串)返回False,否则返回True。
>>> bool('')
False
>>> bool(None)
False
>>> bool('asd')
故在python的argparse中定义bool类型参数时,无论脚本传入的参数是什么,只要不为空,最终得到的结果均是True
parser.add_argument("--istrue", type=bool, default=False)
应该使用store_true来实现
parser.add_argument('--istrue', action='store_true')
或
parser.add_argument('--istrue', action='store_false')
或者另一个实现方式:
def str2bool(x):
return x.lower() in ('true')
parser.add_argument('--istrue', type=str2bool, default=False)