我相对较新的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中,以防出现问题[它不是&#39; t])然后使用verbose选项列出所有选项及其值:
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(&#34; is verbose?%s&#34;%options.verbose)显示为false),它仍会运行if块为verbose(如果options.verbose: )。我错过了一步吗?正如我所说,如果我将解析器留在主块中,并且argv作为main(sys.argv)输入,则会发生这种情况。切换到argparse会修复这个混乱,即使这应该在optparse中工作吗?你能帮忙的话,我会很高兴。 运行Python 2.7.5 +
答案 0 :(得分:3)
parser.add_option("-v", "--verbose",
action="store_true", dest="verbose", default="False",
help="Verbose prints enabled")
字符串"False"
是真实的,是一个非零长度的字符串。试一试:print(bool("False"))
。因此,verbose
的默认值是真实的。使用默认值False
,而不是"False"
。