0

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() 呼び出しでそれを行うにはどうすればよいですか?

4

2 に答える 2

1

各入力行が既知の数の出力行を生成する場合、次のことができます。

import sys
from subprocess import Popen, PIPE

p = Popen([sys.executable, '-u', 'slave.py'], stdin=PIPE, stdout=PIPE)
def send(input):
    print >>p.stdin, input
    print p.stdout.readline(), # print input
    response = p.stdout.readline()
    if response:
        print response, # or just return it
    else: # EOF
        p.stdout.close()

send("hello world")
# ...
send("name is")
send("q")
p.stdin.close() # nothing more to send
print 'waiting'
p.wait()
print 'done'

そうしないと、出力を非同期で読み取るためにスレッドが必要になる場合があります。

于 2012-07-12T21:57:37.363 に答える
0

親のライフサイクル全体でスレーブを存続させるためにインデントする場合は、それをデーモン化できます。

http://code.activestate.com/recipes/278731-creating-a-daemon-the-python-way/

別の方法として、マルチプロセス API を見ることもできます。

http://docs.python.org/library/multiprocessing.html

...これにより、さまざまな子プロセスでスレッドのような処理が可能になります。

于 2012-07-12T21:20:50.600 に答える