2010-01-19 36 views
2

我正在尝试编写一个python程序,该程序最终将使用文件的命令行参数,确定它是否为tar或zip等文件,然后相应地提取它。我只是试图让焦油部分现在工作,我得到了多个错误。我正在检查的文件驻留在我的〜/目录中。任何想法都会很棒。第一个Python程序 - 多个错误

#!/usr/bin/python 

import tarfile 
import os 

def open_tar(file): 
    if tarfile.is_tarfile(file): 
     try: 
      tar = tarfile.open("file") 
      tar.extractall() 
      tar.close() 
     except ReadError: 
      print "File is somehow invalid or can not be handled by tarfile" 
     except CompressionError: 
      print "Compression method is not supported or data cannot be decoded" 
     except StreamError: 
      print "Is raised for the limitations that are typical for stream-like TarFile objects." 
     except ExtractError: 
      print "Is raised for non-fatal errors when using TarFile.extract(), but only if TarFile.errorlevel== 2." 

if __name__ == '__main__': 
    file = "xampp-linux-1.7.3a.tar.gz" 
    print os.getcwd() 
    print file 
    open_tar(file) 

以下是错误。如果我注释掉读取错误,我也会在下一个异常中出现同样的错误。

[email protected]:~$ python openall.py 
/home/tux 
xampp-linux-1.7.3a.tar.gz 
Traceback (most recent call last): 
    File "openall.py", line 25, in <module> 
    open_tar(file) 
    File "openall.py", line 12, in open_tar 
    except ReadError: 
NameError: global name 'ReadError' is not defined 
[email protected]:~$ 
+0

嗯,这真的很难让我们读。你可以看看页面右侧的格式提示吗?您可以使用'101010'按钮来正确设置代码和追溯消息的格式吗?如果我们无法阅读您的问题,我们无法提供帮助。 – 2010-01-19 17:06:27

+0

我正在尝试,我在块,我看到它的一切搞砸了。 – Justin 2010-01-19 17:07:29

+0

要将文本格式设置为堆栈溢出时的代码,请将所有行加上四个空格,这就是全部,不需要用任何标签围绕文本。点击帖子上的修改,查看我是如何更改格式的。还有一个方便的工具栏按钮,您可以在选择文本时使用,以及一个热键Ctrl + K。 – 2010-01-19 17:09:43

回答

10

你可以在你的错误很清楚地看到它指出

NameError: global name 'ReadError' is not defined 

ReadError不是全局蟒蛇名。如果您查看tarfile文档,您将看到ReadError是该模块异常的一部分。因此,在这种情况下,您会想要这样做:

except tarfile.ReadError: 
    # rest of your code 

而且您需要为其余的错误执行相同的操作。另外,如果所有这些错误都会产生相同的结果(某种错误信息,或通过),你可以简单地做:

except (tarfile.ReadError, tarfile.StreamError) # and so on 

而不是做他们每人在一个单独的线。这只是如果他们会给出同样的例外

+0

好的,谢谢。我知道这是说它是不确定的,我确定我必须用前缀。谢谢。 – Justin 2010-01-19 17:12:03

+0

添加停止错误。另一个错误是因为当我不需要这样做时,我有一个名为quoted的变量。 – Justin 2010-01-19 18:10:58

1

我想你可能需要tarfile.ReadError而不是ReadError?

1

好的。你所有的例外(ReadError,CompressionError等)都在tarfile模块中,所以你必须说except tarfile.ReadError而不仅仅是except ReadError

2

您需要使用except tarfile.ReadError或者使用from tarfile import is_tarfile, open, ReadError, CompressionError, etc.并将其放在open_tar函数内而不是全局。