python argparse传入布尔参数false不生效

跑代码时,在命令行给python程序传入bool参数,但无法传入False,无论传入True还是False,程序里面都是True。下面是代码:

parser.add_argument("--preprocess", type=bool, default=True, help='run prepare_data or not')

高端解决方案

  1. 使用可选参数store_true,将上述代码改为:
    parse.add_argument("--preprocess", action='store_true', help='run prepare_data or not')
    
    在命令行执行py文件时,不加--preprocess,默认传入的preprocess参数为False
    如果加--preprocess,则传入的是True
  2. 还可以将上述代码改为:
    parse.add_argument("--preprocess", default='False', action='store_true', help='run prepare_data or not')
    
    和 1 中表达的意思完全相同。
    在命令行执行py文件时,不加--preprocess,默认传入的preprocess参数为False
    如果加--preprocess,则传入的是True
  3. 还可以将上述代码改为:
    parse.add_argument("--preprocess", default='True', action='store_true', help='run prepare_data or not')
    
    和 1 中表达的意思完全相反。
    在命令行执行py文件时,不加--preprocess,默认传入的preprocess参数为True
    如果加--preprocess,则传入的是False

产生的原因和较Low的解决方案

猜测可能的原因是数据类型导致的,传入的都是string类型,转为bool型时,由于是非空字符串,所以转为True

  1. 从这个角度去更改的话,由于type参数接收的是callable的参数类型来对我们接收的原始参数做处理,我们可以定义一个函数赋值给type参数,用它对原始参数做处理:
    parser.add_argument("--preprocess", type=str2bool, default='True', help='run prepare_data or not')
    
  2. 下面定义这个函数将str类型转换为bool型:
    def str2bool(str):
    	return True if str.lower() == 'true' else False
    

猜你喜欢

转载自blog.csdn.net/qyhaill/article/details/101778806
今日推荐