当前位置:网站首页>parser.parse_args 布尔值类型将False解析为True
parser.parse_args 布尔值类型将False解析为True
2022-07-02 06:25:00 【lwgkzl】
记录一个大坑,遇到好多次了,一直没长记性 ==!
问题
当我在代码中使用parser添加一个参数的时候, 将其设置成bool类型的,然后默认值为True。
parser.add_argument("--some_argument", default=True, type=bool)然而,当我在命令行中输入 --some_argument=False的时候, 代码跑出来some_argument这个参数还是True。
我怀疑是自己的编码姿势不对, 换了--some_argument=false(小写) --some_argument=0等,结果代码跑的时候some_arguemnt仍然是True值。
原因
在命令行中,输入的false,或者“0”或者“False”, 都被解析成了字符串,而字符串转成布尔类型之后是这样的:
>>> bool("false")
True
>>> bool("False")
True
>>> bool("0")
True
所以无论我们在命令行里面输入什么, 代码里面解析出来都是True。
解决方案
1. 简单有效, 从此不设置默认值为True的参数, 只设置默认值为False的参数。那么一般跑实验他默认就是False, 如果需要使得该参数的值变为True, 则只需要在命令行输入该参数=True就行了,这样该参数会被解析为True.
parser.add_argument("--some_argument", default=False, type=bool)2. 第二种就是使用 “store_true”这个设置, 默认效果和上面基本一致
parser.add_argument("--some_argument", action="store_true")如果想让该参数为True, 则在命令行中输入--some_argument, 不输入则默认为False。
边栏推荐
猜你喜欢
随机推荐
oracle apex ajax process + dy 校验
ARP攻击
中年人的认知科普
Check log4j problems using stain analysis
User login function: simple but difficult
Anti shake and throttling of JS
DNS attack details
Review of reflection topics
CAD二次开发 对象
ORACLE APEX 21.2安裝及一鍵部署
pySpark构建临时表报错
Oracle segment advisor, how to deal with row link row migration, reduce high water level
Ceaspectuss shipping company shipping artificial intelligence products, anytime, anywhere container inspection and reporting to achieve cloud yard, shipping company intelligent digital container contr
php中在二维数组中根据值返回对应的键值
外币记账及重估总账余额表变化(下)
Network security -- intrusion detection of emergency response
view的绘制机制(二)
sqli-labs通关汇总-page4
Yolov5 practice: teach object detection by hand
CRP实施方法论








