Python BZ2 模块顺序解压缩器:如何知道完整文件何时成功解压缩



我正在使用bz2.BZ2Decompressor类按顺序解压缩bz2压缩数据流。我的流可能包含截断的压缩数据。我需要能够区分解压缩完整文件的情况和仅解压缩部分文件的情况。有什么办法可以确定吗?

详细地说,我提供给解压缩函数的数据流可能是也可能不是完整的 bz2 压缩文件。它可能会被截断。当我使用这个函数时,它会将它能够使用数据解压缩的任何数量返回给我。它没有告诉我是否到达了流的尽头。我如何确定相同?仅当找到流末尾有其他数据时,才会引发EOFError。所以这对我没有帮助。

您可以通过将

一些额外的"垃圾"数据传递给解压缩程序的decompress()方法来检测您的数据流是否完整。如果流已完成,它将引发EOFError。如果流仍在运行,它可能不会引发异常,因为解压缩程序将假定垃圾是截断流的一部分。

下面是一些示例代码:

import bz2
def decompress(stream):
    decompressor = bz2.BZ2Decompressor()
    # this generator decompresses the data from the iterable stream
    results = "".join(decompressor.decompress(data) for data in stream)
    # now we test to see if it was a complete BZ2 stream
    try:
        decompressor.decompress("") # try adding a "junk" null character
    except EOFError: # the stream was complete!
        return results
    except IOError: # the junk may cause an IOError if it hits a BZ2 header
        pass
    # if we reach this point here, the stream was incomplete
    print "Incomplete stream!"
    return None # you may or may not want to throw away the partial results

最新更新