0

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?

Ealau
  • 61
  • 8

1 Answers1

0

You'll want to use the subprocess.Popen() function, which keeps the process alive.

Related S.O. question for reference:

Keep a subprocess alive and keep giving it commands? Python

Matt_G
  • 506
  • 4
  • 14
  • I'm using Popen(), and when I only have a single input, or multiple inputs before the outputs, it works fine. But when try to have a back-and-forth between the processes using the code above, they hang indefinitely. – Ealau Apr 26 '18 at 18:10
  • Popen is supposed to be used for the [Child Process](https://docs.python.org/2/library/subprocess.html#popen-constructor), not the parent. – Matt_G Apr 26 '18 at 18:14