【发布时间】:2020-07-14 21:51:09
【问题描述】:
我正在尝试制作这样的构建脚本:
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'
总是一样的。我错过了什么?
【问题讨论】:
-
我们使用
action="store_true"来处理这种问题:docs.python.org/3.8/library/argparse.html#action -
这能回答你的问题吗? Parsing boolean values with argparse
-
@IdeaO。不,那个答案并不能解释为什么 arparse 不解析输入。我的问题不同。
-
试试
bool("False")或bool("FALSE")。返回False的唯一字符串是bool("")。您必须编写自己的函数,将“False”或“No”等字符串识别为False。内置的bool不会为您执行此操作。
标签: python command-line arguments argparse