您可以通过向解压缩程序的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
虽然这会的工作,我不想这样做。我希望有某种方式来获得解压缩器的当前状态。看起来像在Python中没有办法得到那个。 – AnkurVj