python - tar.extractall() 无法识别意外的 EOF

标签 python tar eof

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/

相关文章:

python - Django - error_403() 得到了一个意外的关键字参数 'exception'

python - 最佳实践 - 观看目录的最佳方式是什么

linux - 找到 *.tar 然后提取并删除文件

c - 读入输入,然后读入c编程中的每个字符

json - React Native fetch 返回错误 : JSON Unexpected EOF

Python遍历嵌套字典

python AST : How to get the children of a node

用于 tar 目录中特定文件的 bash 脚本

python - 获取解压后的 .tar.gz 文件的文件夹名称

c - 操作系统如何识别文本文件的结尾?