Search code examples
pythonpython-3.xutf-8gzipstdin

Python: read gzip from stdin


How do I read gzipped content from stdin line-by-line?


I have a gzipped file a.gz in current directory containing UTF-8 content.

Scenario 1:

Using gzip.open(filename) works. I can print the unzipped lines.

with gzip.open('a.gz', 'rt') as f:
    for line in f:
        print(line)

# python3 my_script.py

Scenario 2:

I want to read gzipped content from stdin. So I cat the gzipped file as the input for the below script.

with gzip.open(sys.stdin, mode='rt') as f:
    for line in f:
        print(line)

# cat a.gz | python3 script.py

But for approach 2, I get the error below:

Traceback (most recent call last):
  File "script.py", line 71, in <module>
    for line in f:
  File "....../python3.6/gzip.py", line 289, in read1
    return self._buffer.read1(size)
  File "....../python3.6/_compression.py", line 68, in readinto
    data = self.read(len(byte_view))
  File "....../python3.6/gzip.py", line 463, in read
    if not self._read_gzip_header():
  File "....../python3.6/gzip.py", line 406, in _read_gzip_header
    magic = self._fp.read(2)
  File "....../python3.6/gzip.py", line 91, in read
    self.file.read(size-self._length+read)
  File "....../python3.6/codecs.py", line 321, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte

Solution

  • You want to open sys.stdin.buffer, not sys.stdin, because the latter transparently decodes the bytes into strings. This works for me:

    with gzip.open(sys.stdin.buffer, mode='rt') as f:
        for line in f:
            print(line)