How to send a var to stdin of an external software

Bryan Olson fakeaddress at
Thu Mar 13 17:31:09 CET 2008

Benjamin Watine wrote:
> And if somebody need it : to get the stdout in a var (myNewVar), not in 
> the shell :
> cat = subprocess.Popen('cat', shell = True, stdin = subprocess.PIPE, 
> stdout=subprocess.PIPE)
> cat.stdin.write(myVar)
> cat.stdin.close()
> cat.wait()
> myNewVar =
> Is it correct ?

No, not really. It is prone to deadlock. The external program might
work by iteratively reading a little input and writing a little
output, as 'cat' almost surely does. If the size of myVar exceeds
the buffer space in cat and the pipes, you get stuck.

Your Python program can block at "cat.stdin.write(myVar)", waiting
for cat to read from its input pipe, while cat blocks at a write
to its output stream, waiting for you to start reading and freeing
up buffer space. Pipe loops are tricky business.

Popular solutions are to make either the input or output stream
a disk file, or to create another thread (or process) to be an
active reader or writer.


More information about the Python-list mailing list