Python Argparse不解析布尔参数?
我正在尝试制作一个如下的构建脚本:Python Argparse不解析布尔参数?,python,command-line,arguments,argparse,Python,Command Line,Arguments,Argparse,我正在尝试制作一个如下的构建脚本: import glob import os import subprocess import re import argparse import shutil def create_parser(): parser = argparse.ArgumentParser(description='Build project') parser.add_argument('--clean_logs', type=bool, default=True
import glob
import os
import subprocess
import re
import argparse
import shutil
def create_parser():
parser = argparse.ArgumentParser(description='Build project')
parser.add_argument('--clean_logs', type=bool, default=True,
help='If true, old debug logs will be deleted.')
parser.add_argument('--run', type=bool, default=True,
help="If true, executable will run after compilation.")
parser.add_argument('--clean_build', type=bool, default=False,
help="If true, all generated files will be deleted and the"
" directory will be reset to a pristine condition.")
return parser.parse_args()
def main():
parser = create_parser()
print(parser)
然而,无论我如何尝试传递参数,我只得到默认值。我总是得到名称空间(clean\u build=False,clean\u logs=True,run=True)
我试过:
python3 build.py --run False
python3 build.py --run=FALSE
python3 build.py --run FALSE
python3 build.py --run=False
python3 build.py --run false
python3 build.py --run 'False'
总是一样的。我遗漏了什么?您误解了
argparse
如何理解布尔参数
基本上,您应该使用action='store\u true'
或action='store\u false'
而不是默认值,但要理解的是,不指定参数将导致与操作相反的结果,例如
parser.add_argument('-x', type=bool, action='store_true')
将导致:
python3 command -x
将x
设置为True
和
python3 command
将x
设置为False
而action=store\u false
将起相反的作用
将
bool
设置为类型的行为与您期望的不一样,这是一个错误
当前行为的原因是
type
应该是可调用的,用作argument=type(argument)
bool('False')
的计算结果为True
,因此您需要为预期发生的行为设置不同的类型。我们使用action=“store\u True”
来处理此类问题:这是否回答了您的问题@艾迪奥。不,这个答案不能解释为什么arparse不是;t解析输入。我的问题不同。请尝试bool(“False”)
或bool(“False”)
。唯一返回False
的字符串是bool(“”
)。您必须编写自己的函数,将“False”或“No”等字符串识别为False
。内置的bool
不适合您。一个旧的答案是:最近的一个错误/问题发现distutils.util.strtobool可以将各种yes/no(仅限英语)单词解析为真/假值。