您可以通過向解壓縮程序的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