Can I use open gzip file with Popen in Python?

I have a small command line tool that reads from stdin. On the command line, I would run ...

./foo < bar 

or...

 cat bar | ./foo 

With gziped file I can run

 zcat bar.gz | ./foo 

in Python I can do ...

 Popen(["./foo", ], stdin=open('bar'), stdout=PIPE, stderr=PIPE) 

but i can't do

 import gzip Popen(["./foo", ], stdin=gzip.open('bar'), stdout=PIPE, stderr=PIPE) 

I need to run

 p0 = Popen(["zcat", "bar"], stdout=PIPE, stderr=PIPE) Popen(["./foo", ], stdin=p0.stdout, stdout=PIPE, stderr=PIPE) 

Am I doing something wrong? Why can't I use gzip.open ('bar') as the stdin argument for Popen?

+6
python scripting subprocess
source share
1 answer

Because the "stdin" and "stdout" subprocess accept a file descriptor (which is a number), which is an operating system resource. This is masked by the fact that if you pass an object, the subprocess module checks to see if the object has a fileno attribute, and if it does, it will use it.

The 'gzip' object is not an operating system operation. An open file is a socket, it is a pipe. A Gzip object is an object that provides the read () and write () methods, but not the fileno attribute.

You can look at the communication () subprocess method, although you can use it.

+4
source share

All Articles