2012-07-04 50 views
0

我正在使用bz2.BZ2Decompressor类来顺序解压缩bz2压缩数据流。我的流可能包含截断的压缩数据。我需要能够区分完整文件解压缩和只解压部分文件的情况。有什么办法可以确定吗?Python BZ2模块顺序解压缩程序:如何找出完整文件成功解压的时间?

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

回答

1

您可以通过向解压缩程序的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 
+0

虽然这会的工作,我不想这样做。我希望有某种方式来获得解压缩器的当前状态。看起来像在Python中没有办法得到那个。 – AnkurVj