第一个Python程序 - 多个错误

时间:2010-01-19 17:03:39

标签: python

我正在尝试编写一个python程序,它最终将获取文件的命令行参数,确定它是否是tar或zip等文件,然后相应地将其解压缩。我只是试图让tar部分工作,我得到了多个错误。我正在检查的文件位于我的〜/目录中。任何想法都会很棒。

#!/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)

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

tux@crosnet:~$ 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
tux@crosnet:~$ 

4 个答案:

答案 0 :(得分:10)

您可以在错误中清楚地看到它的状态

NameError: global name 'ReadError' is not defined

ReadError不是全局python名称。如果查看tarfile文档,您会看到ReadError是该模块异常的一部分。所以在这种情况下,您可以这样做:

except tarfile.ReadError:
  # rest of your code

你需要对其余的错误做同样的事情。此外,如果所有这些错误都会产生相同的结果(某种错误消息或传递),您可以这样做:

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

而不是分别在单独的线上进行。只有当他们提供相同的例外时才会这样做

答案 1 :(得分:2)

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

答案 2 :(得分:1)

我认为您可能需要tarfile.ReadError而不仅仅是ReadError?

答案 3 :(得分:1)

好。您的所有例外情况(ReadErrorCompressionError等)都在tarfile模块中,因此您必须说except tarfile.ReadError而不是except ReadError。< / p>

相关问题