I need to start a Python script in Python and keep it up.
For argument purposes, say that there is a program called slave.py
if __name__=='__main__':
done = False
while not done:
line = raw_input()
print line
if line.lower() == 'quit' or line.lower() == 'q':
done = True
break
stringLen = len(line)
print "len: %d " % stringLen
The program "slave.py" receives a string, calculates the input length of the string and outputs the length to stdout with a print statement.
It should run until I give it a "quit" or "q" as an input.
Meanwhile, in another program called "master.py", I will invoke "slave.py"
# Master.py
if __name__=='__main__':
# Start a subprocess of "slave.py"
slave = subprocess.Popen('python slave.py', shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
x = "Hello world!"
(stdout, stderr) = slave.communicate(x)
# This works - returns 12
print "stdout: ", stdout
x = "name is"
# The code bombs here with a 'ValueError: I/O operation on closed file'
(stdout, stderr) = slave.communicate(x)
print "stdout: ", stdout
However, the slave.py program that I opened using Popen() only takes one communicate() call. It ends after that one communicate() call.
For this example, I would like to have slave.py keep running, as a server in a client-server model, until it receives a "quit" or "q" string via communicate. How would I do that with the subprocess.Popen() call?