前言
今天在写程序的时候发现argparse在接收命令行bool类型的值时出现问题:
命令行输入为:
python BiLSTM_run.py --is_train False
发现程序仍然运行is_train=True
的代码,设置default为false:
parse.add_argument('--is_train', default=False, type=bool, help='is training state or not ')
仍然没有用,上网查阅资料后发现,是argparse
的问题,其在处理bool
类型的参数的时候并不能自动转换参数类型。虽然我们指定了其类型为bool
,但无论我们在命令行中给这个参数传入什么值(如True
,False
等),is_train
的值总是为True
。
解决方法
parse.add_argument("--is_train",action="store_true",help="is training state or not")
这样的话,当不输入--is_train
的时候,默认为False
;输入--is_train
的时候,才会触发True
值。
也可以写作:
parse.add_argument("--is_train",action="store_false",help="is training state or not")
这样,不输入--is_train
的时候,默认为True
;输入--is_train
的时候,为False
值。
目前只记录一个解决方法,留自用。
参考链接:https://blog.youkuaiyun.com/a15561415881/article/details/106088831