python - 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,
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)
但是,无论我如何尝试传递参数,我都只能得到默认值。我总是得到Namespace(clean_build=False, clean_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_true'
oraction='store_false'
代替默认值,但要了解不指定参数会给您带来相反的操作,例如
parser.add_argument('-x', type=bool, action='store_true')
将造成:
python3 command -x
设置x
为True
和
python3 command
已x
设置为False
。
而action=store_false
会做相反的事情。
设置bool
为 type 的行为与您预期的不同,这是一个已知问题。
当前行为的原因type
是预期是一个可调用的,用作argument = type(argument)
. bool('False')
计算结果为True
,因此您需要为type
您期望发生的行为设置不同的值。