Determine whether STDIN is gzipped

Andreas Jung andreas at andreas-jung.com
Tue Jan 9 05:10:11 EST 2001


On Tue, Jan 09, 2001 at 10:36:04AM +0100, Carsten Gaebler wrote:
> Hi there!
> 
> I'm writing a program that reads its input data from STDIN. Now I'd like
> it to be able to determine whether the input data is gzipped or not and
> do the right thing automatically. This is my approach:
> 
> 
> import gzip, sys
> 
> f = gzip.GzipFile("", "rb", fileobj=sys.stdin)
> try:
>     f.readline() # raises exception if not gzipped
> except:
>     f = sys.stdin
> 
> while 1:
>     line = f.readline()
>     if not line: break
>     # do something with line
>
 
Something like the following should work (I assume we can read all
data from STDIN in one read() call):

 
import os,gzip,sys
from cStringIO import StringIO

SIO = StringIO(sys.stdin.read())

try:
	data = gzip.GzipFile('','r',fileobj=SIO).read()
except:
	data = SIO.getvalue()

print data



Andreas




More information about the Python-list mailing list