2

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

P. Dmitry
  • 1,123
  • 8
  • 26

1 Answers1

0

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

xhenrique
  • 153
  • 1
  • 8
  • I thought about using a temporary file. But it's a bit hacky – P. Dmitry Oct 09 '19 at 10:49
  • The error ```io.UnsupportedOperation: fileno``` reffers to the Type of variable that you are trying to use the ```fileno()``` function, it only works with fileObjects, he expecting something likely, not a io.BytesIO, as you are passing. I think you need to create the file in order to use the module. At least open it with ```with```, read the bytes into a file and pass the file variable to Popen. – xhenrique Oct 09 '19 at 10:55
  • Yes, I understand why does error exist. But the question is why `Popen` allows only file objects with `fileno` and is it possible somehow pass data to process without a file. Maybe without `Popen` or even without `subprocess` – P. Dmitry Oct 10 '19 at 05:34