Welcome, guest | Sign In | My Account | Store | Cart

Using gzip and StringIO module, then controllable gzipped stream.

Python, 26 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# gzipout.py
from gzip import GzipFile
from StringIO import StringIO

sio = StringIO()
gzf = GzipFile(fileobj=sio, mode='wb')
gzf.write(sys.stdin.read())
gzf.close()

# Output gzipped stream.
sys.stdout.write(sio.getvalue())

# It is performed as follows for trying operation on shell.
# $ cat textfile | python gzipout.py | zcat

# Moreover, since socket object used for network programming
# cannot do seek(), it is once copied to StringIO.

# gzipin.py
from gzip import GzipFile
from StringIO import StringIO

gzstream = open('gzipped.gz', 'rb')
sio = StringIO(gzstream)
gz = GzipFile(fileobj=sio, mode='rb')
print gz.read()

It must be useful to the time of wanting to treat stream compressed by mod_gzip of Apache, and the data compression of transmission programs.

I found exmaple code for mod_python http://www.modpython.org in CVS use like this tip. See also http://cvs.apache.org/viewcvs.cgi/httpd-python/examples/gzipfilter.py?rev=1.1&content-type=text/vnd.viewcvs-markup