Python:从stdin中读取gzip

时间:2018-11-11 02:24:13

标签: python python-3.x utf-8 gzip stdin

如何逐行从stdin中读取压缩的内容?


我在当前目录中有一个压缩的文件a.gz,其中包含UTF-8内容。

场景1:

使用gzip.open(filename)可行。我可以打印未压缩的行。

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

# python3 my_script.py

方案2:

我想从stdin中读取压缩后的内容。因此,我cat将压缩后的文件作为以下脚本的输入。

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

# cat a.gz | python3 script.py

但是对于方法2,我得到以下错误:

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

1 个答案:

答案 0 :(得分:3)

您要打开sys.stdin.buffer而不是sys.stdin,因为后者会透明地将字节解码为字符串。这对我有用:

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