Python optparse没有看到参数

时间:2010-01-20 00:17:40

标签: 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 个答案:

答案 0 :(得分:2)

您的问题可能是if len(args) != 1:。那就是寻找一个附加的参数(即不是一个选项)。如果您删除该支票并查看options词典,则应该看到{'filename': 'blah'}

答案 1 :(得分:1)

解析参数列表中的选项后,检查是否传递了参数。这与-f的参数无关。听起来你只是没有传递这个论点。既然你实际上并没有使用这个参数,你应该只是删除对len(args)的检查。

答案 2 :(得分: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)

通常可以区分,因为选项通常具有合理的默认值,而参数则没有。

答案 3 :(得分:0)

您应该将'add_option()'方法中的'action'属性设置为'store',这会告诉optparse对象紧跟选项标志后存储参数,尽管这是默认行为。然后,该标志后面的值将存储在'options.filename'中,而不是存储在args中。我也认为

if len(args) != 1:

也是一个问题,如果len(args)大于或小于1,您将收到相同的消息。