Python で Python スクリプトを開始し、それを維持する必要があります。
議論のために、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
プログラム "slave.py" は、文字列を受け取り、入力された文字列の長さを計算し、その長さを print ステートメントで stdout に出力します。
入力として「quit」または「q」を指定するまで実行する必要があります。
一方、「master.py」という別のプログラムで、「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
ただし、Popen() を使用して開いた slave.py プログラムは、1 回の communicate() 呼び出ししか必要としません。その 1 回の communicate() 呼び出しの後に終了します。
この例では、クライアント サーバー モデルのサーバーとして、通信を介して "quit" または "q" 文字列を受信するまで、slave.py を実行し続けたいと考えています。subprocess.Popen() 呼び出しでそれを行うにはどうすればよいですか?