Python:从标准输入读取gzip

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

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


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

场景 1:

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

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

# python3 my_script.py

场景 2:

我想从标准输入读取压缩内容。因此,我cat gzip 压缩文件作为以下脚本的输入。

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

最佳答案

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

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

关于Python:从标准输入读取gzip,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53245314/

相关文章:

python - 如何使用python将数据转储到Json文件中

python - seek and tell 可以在 Python 中使用 UTF-8 编码的文档吗?

python - 加载表单后如何运行函数 Kivy

python - 如何使用 python 控制台修复 import keras 错误

python - 如何匹配数据框中列之间的值

python - 如何从 ruamel.yaml 转储的输出中删除 2 个空格?

Java 将 ISO-8859-1 转换为 UTF-8

python %s 格式说明符因 utf-8 值而失败

python - 在 INSTALLED_APPS 添加 "dependencies references nonexistent parent node"后出现 'pinax.notifications' 错误

python - 导入错误 : No module named _ssl