tar.extractall() 无法识别意外的 EOF
tar.extractall() does not recognize unexpected 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 3 中得到修复 -- 无论 errorlevel
设置如何,都会引发 OSError
。
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 3 中得到修复 -- 无论 errorlevel
设置如何,都会引发 OSError
。