Python optparse 无法识别参数
我想在命令行调用程序时,传递 '-f nameoffile' 这个参数。我是从 Python 的文档上看到这个的,但是当我传 '-f filename' 或者 '--file=filename' 时,程序却报错说我没有传递足够的参数。如果我传 -h,程序就会正常响应,并给我帮助信息。有没有什么想法?我觉得这可能是我忽略了什么简单的东西。任何帮助都非常感谢,谢谢,Justin。
[justin87@el-beasto-loco python]$ python openall.py -f chords.tar
Usage: openall.py [options] arg
openall.py: error: incorrect number of arguments
[justin87@el-beasto-loco python]$
#!/usr/bin/python
import tarfile
import os
import zipfile
from optparse import OptionParser
def check_tar(file):
if tarfile.is_tarfile(file):
return True
def open_tar(file):
try:
tar = tarfile.open(file)
tar.extractall()
tar.close()
except tarfile.ReadError:
print "File is somehow invalid or can not be handled by tarfile"
except tarfile.CompressionError:
print "Compression method is not supported or data cannot be decoded"
except tarfile.StreamError:
print "Is raised for the limitations that are typical for stream-like TarFile objects."
except tarfile.ExtractError:
print "Is raised for non-fatal errors when using TarFile.extract(), but only if TarFile.errorlevel== 2."
def check_zip(file):
if zipfile.is_zipfile(file):
return True
def open_zip(file):
try:
zip = zipfile.ZipFile(file)
zip.extractall()
zip.close()
#open the zip
print "GOT TO OPENING"
except zipfile.BadZipfile:
print "The error raised for bad ZIP files (old name: zipfile.error)."
except zipfile.LargeZipFile:
print "The error raised when a ZIP file would require ZIP64 functionality but that has not been enabled."
rules = ((check_tar, open_tar),
(check_zip, open_zip)
)
def checkall(file):
for checks, extracts in rules:
if checks(file):
return extracts(file)
def main():
usage = "usage: %prog [options] arg"
parser = OptionParser(usage)
parser.add_option("-f", "--file", dest="filename",
help="read data from FILENAME")
(options, args) = parser.parse_args()
if len(args) != 1:
parser.error("incorrect number of arguments")
file = options.filename
checkall(file)
if __name__ == '__main__':
main()
4 个回答
1
在从参数列表中解析出选项后,你需要检查一下是否传入了一个参数。这和-f这个参数没有关系。听起来你可能根本就没有传这个参数。而且你其实也并没有真正使用这个参数,所以你可能可以直接去掉对len(args)的检查。
2
你的问题可能出在这行代码 if len(args) != 1:
。这行代码是在检查是否有一个额外的参数(也就是说,不是选项)。如果你把这个检查去掉,然后看看你的 options
字典,你应该能看到 {'filename': 'blah'}
。
1
你的输入文件名不是程序的一个选项,而是一个参数:
def main():
usage = "Usage: %prog [options] FILE"
description = "Read data from FILE."
parser = OptionParser(usage, description=description)
(options, args) = parser.parse_args()
if len(args) != 1:
parser.error("incorrect number of arguments")
file = args[0]
checkall(file)
你通常可以通过一些简单的规则来区分它们,因为选项一般都有合理的默认值,而参数则没有。