余分な「ジャンク」データをデコンプレッサの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