Determine whether STDIN is gzipped

Carsten Gaebler cg at schlund.de
Tue Jan 9 04:36:04 EST 2001


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


The problem is that if STDIN is not gzipped I am missing the first few
bytes of the first line in the while loop, if STDIN is gzipped I am even
missing the whole first line, all because of the readline() in the try
block. Unfortunately f.seek(0) doesn't work for STDIN. Any hints?

Regards
Carsten.



More information about the Python-list mailing list