Python tarfile
库没有检测到损坏的 tar。
user@host$ wc -c good.tar
143360 good.tar
user@host$ head -c 130000 good.tar > cut.tar
user@host$ tar -tf cut.tar
...
tar: Unexpected EOF in archive
tar: Error is not recoverable: exiting now
非常好,命令行工具可以识别意外的 EOF。
user@host$ python
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
>>> import tarfile
>>> tar=tarfile.open('cut.tar')
>>> tar.extractall()
不太好。 Python 库解码文件,但不引发异常。
如何使用 Python 库检测意外的 EOF?我想避开 subprocess
模块。
参数 errorlevel
没有帮助。我尝试了 errorlevel=1 和 errorlevel=2。
最佳答案
我写了一个解决方法。它适用于我的 tar 文件。我想它不支持可以存储在 tar 文件中的所有类型的对象。
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, unicode_literals, print_function
import os
import tarfile
class TarfileWhichRaisesOnEOF(tarfile.TarFile):
def extractall(self, path=".", members=None):
super(TarfileWhichRaisesOnEOF, self).extractall(path, members)
if members is None:
members = self
for tarinfo in members:
if not tarinfo.isfile():
continue
file=os.path.join(path, tarinfo.name)
size_real=os.path.getsize(file)
if size_real!=tarinfo.size:
raise tarfile.ExtractError('Extracting %s: Size does not match. According to tarinfo %s and on disk %s' % (
tarinfo, tarinfo.size, size_real))
关于python - tar.extractall() 无法识别意外的 EOF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30302204/