第一个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 个回答
1
好的。你所有的异常情况(比如 ReadError
、CompressionError
等)都在 tarfile
这个模块里,所以你需要写成 except tarfile.ReadError
,而不是简单地写 except ReadError
。
2
你需要使用 except tarfile.ReadError
,或者你也可以用 from tarfile import is_tarfile, open, ReadError, CompressionError, etc.
这个方式,把它放在 open_tar 函数里面,而不是放在全局范围。
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
而不是把它们每个都写在单独的一行。这只是针对它们会产生相同的异常的情况。