【问题标题】:Python optparse not seeing argumentPython optparse 没有看到参数
【发布时间】:2010-01-20 15:52:18
【问题描述】:

当我从命令行调用程序时,我试图将“-f nameofile”传递给程序。我从 python 站点文档中得到了这个,但是当我传递 '-f filename' 或 '--file=filename' 时,它会抛出我没有传递足够多的参数的错误。如果我通过 -h 程序会响应它应该如何响应并给我帮助。有任何想法吗?我想我忽略了一些简单的事情。任何和所有的帮助都很棒,谢谢,贾斯汀。

[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()

【问题讨论】:

  • 做一个:print args 看看 args 变量的值是什么
  • 明确什么是选项,什么是 OptionParser 的参数。

标签: python optparse


【解决方案1】:

您的问题可能是if len(args) != 1:。那是在寻找一个 additional 参数(即不是一个选项)。如果您删除该检查并查看您的 options 字典,您应该会看到 {'filename': 'blah'}

【讨论】:

    【解决方案2】:

    您的输入文件名不是程序的选项,而是一个参数:

    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】:

      从参数列表中解析选项后,检查是否传递了参数。这与 -f 的参数无关。听起来你只是没有通过这个论点。由于您实际上也没有使用此参数,因此您可能应该删除对 len(args) 的检查。

      【讨论】:

        【解决方案4】:

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

        if len(args) != 1:
        

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-11-22
          • 1970-01-01
          • 2016-06-05
          • 1970-01-01
          • 2012-04-22
          相关资源
          最近更新 更多