gpt4 book ai didi

Python optparse - 选项未被读取为错误

转载 作者:太空宇宙 更新时间:2023-11-04 01:18:58 24 4
gpt4 key购买 nike

我是 Python 的新手,并且在玩 optparse。我有这样的解析器功能:

def parse(argv):
"""Option parser, returns the options leave the args."""
version = '0.1'
usage = 'Usage: %prog [options] -f|--file <FILENAME>'
parser = optparse.OptionParser(usage=usage,version="%prog: v.{}".format(version))
parser.add_option("-m", "--mock",
action="store_true", dest="fake", default=False,
help="Mock the file and export to stdout")
parser.add_option("-t", "--test",
action="store_true", dest="test", default=False,
help="Test the file against RocketAnalysis.m after completion")
parser.add_option("-d", "--dir",
dest="save_dir", default=os.getcwd(), metavar="DIR",
help="Change save directory to DIR [Default: current dir]")
parser.add_option("-f", "--file-name",
dest="filename", default=None, metavar="FILENAME",
help="FILENAME to create variables under [ REQUIRED ]")
parser.add_option("-v", "--verbose",
action="store_true", dest="verbose", default="False",
help="Verbose prints enabled")
parser.add_option("-q", "--quiet",
action="store_true", dest="quiet", default="False",
help="Turns on quiet mode with no prints or feedback except errors")
parser.add_option("-c", "--clober",
action="store_true", dest="clobber", default="False",
help="Clobber FILENAME and re-write")
(options, args) = parser.parse_args()
return options

我从 main 调用它(我也将它包含在 main 中,以防出现问题[不是]),然后使用详细选项列出所有选项及其值:

    options = parse(argv)
file_path = "{}/{}".format(options.save_dir,options.filename)
print("Is verbose? %s" % options.verbose)
if options.verbose:
opts_dic = vars(options)
print("Options set:")
for k, v in opts_dic.iteritems():
print("\t{} : {}".format(k, v))
print("\tFile path set to: {}".format(file_path))

结果:

./create_stage.py -f this.txt
Is verbose? False
Options set:
verbose : False
fake : False
quiet : False
clobber : False
filename : this.txt
save_dir : /home/silas/Documents/ksp/ksp-octave
test : False
File path set to: /home/silas/Documents/ksp/ksp-octave/this.txt

因此,即使它知道 verbose 是 false(print("Is verbose? %s"% options.verbose) 显示 false),它仍然运行 if block 以获得 verbose (if options.verbose:)。我错过了一些步骤吗?正如我所说,如果我也将解析器留在主 block 中,并且 argv 作为 main(sys.argv) 输入,就会发生这种情况。切换到 argparse 会解决这个问题吗,即使这应该在 optparse 中工作?你能帮忙的话,我会很高兴。运行 Python 2.7.5+

最佳答案

parser.add_option("-v", "--verbose",
action="store_true", dest="verbose", default="False",
help="Verbose prints enabled")

字符串 "False" 是真实的,是一个非零长度的字符串。试试看:print(bool("False"))。所以 verbose 的默认值是真实的。使用默认值 False,而不是 "False"

关于Python optparse - 选项未被读取为错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22565997/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com