繁体   English   中英

Python BZ2模块顺序解压缩器:如何确定完整文件已成功解压缩的时间?

[英]Python BZ2 Module Sequential decompressor: How do I find out when the complete file has been successfully decompressed?

我正在使用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("\0") # 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM