I have 5 processes p1,p2,...,p5
where I want to write some data to stdin of p1, pipe p1 output to p2 stdin and finally read the final result from output of p5.<
Maybe this can help:
import sys
import tempfile
from subprocess import Popen, PIPE
cmd = [sys.executable, '-c', 'print raw_input()']
# Using a temp file to give input data to the subprocess instead of stdin.write to avoid deadlocks.
with tempfile.TemporaryFile() as f:
f.write('foobar')
f.seek(0) # Return at the start of the file so that the subprocess p1 can read what we wrote.
p1 = Popen(cmd, stdin=f, stdout=PIPE)
p2 = Popen(cmd, stdin=p1.stdout, stdout=PIPE)
p3 = Popen(cmd, stdin=p2.stdout, stdout=PIPE)
# No order needed.
p1.stdout.close()
p2.stdout.close()
# Using communicate() instead of stdout.read to avoid deadlocks.
print p3.communicate()[0]
Output:
$ python test.py
foobar
Hope this can be hepfull.