I'm trying to use subproccess.Popen to allow two Python programs to more or less have a conversation. I want to be able to send input from the parent to the child, receive the child's response, and then based on that response, send a new input. subprocess.communicate() closes the process after one I/O interaction. Is it possible to leave the same subprocess open for multiple I/Os? Currently, my code hangs.
Parent code:
from __future__ import print_function
import subprocess
import sys
try:
p = subprocess.Popen(['python','childprocess.py'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
bufsize=1,
universal_newlines=True)
except Exception as e:
print("Error: "+str(e))
sys.exit(-1)
p.stdin.write('This is the first input\n')
p.stdin.flush()
print(p.stdout.readline())
p.stdin.write('This is the second input\n')
print(p.stdout.readline())
Child code:
input_one = raw_input()
print "Input One: ",input_one
input_two = raw_input()
print "Input Two: ",input_two
In this case, I can just give the two inputs and then read the two outputs, but if I wanted to be able to use the child output to inform the parent input (e.g. a number guesser), can I do that with subprocess?