跑代码时,在命令行给python程序传入bool参数,但无法传入False,无论传入True还是False,程序里面都是True。下面是代码:
parser.add_argument("--preprocess", type=bool, default=True, help='run prepare_data or not')
高端解决方案
- 使用可选参数store_true,将上述代码改为:
在命令行执行py文件时,不加parse.add_argument("--preprocess", action='store_true', help='run prepare_data or not')
--preprocess
,默认传入的preprocess参数为False
;
如果加--preprocess
,则传入的是True
。 - 还可以将上述代码改为:
和 1 中表达的意思完全相同。parse.add_argument("--preprocess", default='False', action='store_true', help='run prepare_data or not')
在命令行执行py文件时,不加--preprocess
,默认传入的preprocess参数为False
;
如果加--preprocess
,则传入的是True
。 - 还可以将上述代码改为:
和 1 中表达的意思完全相反。parse.add_argument("--preprocess", default='True', action='store_true', help='run prepare_data or not')
在命令行执行py文件时,不加--preprocess
,默认传入的preprocess参数为True
;
如果加--preprocess
,则传入的是False
。
产生的原因和较Low的解决方案
猜测可能的原因是数据类型导致的,传入的都是string类型,转为bool型时,由于是非空字符串,所以转为True
。
- 从这个角度去更改的话,由于
type
参数接收的是callable
的参数类型来对我们接收的原始参数做处理,我们可以定义一个函数赋值给type
参数,用它对原始参数做处理:parser.add_argument("--preprocess", type=str2bool, default='True', help='run prepare_data or not')
- 下面定义这个函数将str类型转换为bool型:
def str2bool(str): return True if str.lower() == 'true' else False