如何将gzip输出重定向到Popen stdin

问题描述 投票:2回答:1

如果没有文件,如何将gzip的解压缩结果传递到stdin进程中?

[我发现,Popen构造函数要求stdin参数是使用fileno方法的对象。在python2.7中,gzip没有decompress功能。另外,为什么Popen如果没有fileno就不能接受文件对象?

我已经尝试过此代码

import subprocess
import gzip
import io

# To test with file
# with open('test.gz', 'rb') as f:
#    data = f.read()
data = b'...'

gz = gzip.GzipFile(mode='rb', fileobj=io.BytesIO(data))
subprocess.Popen(['cat'], stdin=gz)

但是有错误:

Traceback (most recent call last):
  File "test.py", line 9, in <module>
    subprocess.Popen(['cat'], stdin=gz)
  File "/usr/lib/python3.7/subprocess.py", line 728, in __init__
    errread, errwrite) = self._get_handles(stdin, stdout, stderr)
  File "/usr/lib/python3.7/subprocess.py", line 1347, in _get_handles
    p2cread = stdin.fileno()
  File "/usr/lib/python3.7/gzip.py", line 334, in fileno
    return self.fileobj.fileno()
io.UnsupportedOperation: fileno
python python-2.7 subprocess gzip
1个回答
0
投票

您可以将其保存在文件中,然后将文件路径传递给Popen构造函数,我不确定它是否可以与BytesIO模块一起使用。

关于如何将输出保存到文件,您可以遵循this问题。

GLHF

© www.soinside.com 2019 - 2024. All rights reserved.