How to redirect gzip output to Popen stdin

Viewed 276

How can I pass the result of decompressing by gzip into process stdin if I haven't file?

I found, that Popen constructor requires stdin argument to be the object with the fileno method. In python2.7 gzip hasn't decompress function. Also, why Popen can't accept file object without fileno?

I have tried this code

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)

But have the error:

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

Added: It's ok to use something different from Popen and/or subprocess

1 Answers

you can save it in a file and pass the file path to Popen constructor, i'm not sure if it works with BytesIO module.

You can follow this question on how to save the output to a file.

GLHF

Related