如何启动子进程并将其用作Python中的服务器?

时间:2012-07-12 21:14:31

标签: python subprocess popen

我需要在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。

它应该运行,直到我给它一个“退出”或“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程序只接受一次communic()调用。它在一个communication()调用之后结束。

对于这个例子,我希望slave.py继续运行,作为客户端 - 服务器模型中的服务器,直到它通过通信接收“退出”或“q”字符串。我如何使用subprocess.Popen()调用?

2 个答案:

答案 0 :(得分: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'

否则您可能需要threads to read the output asynchronously

答案 1 :(得分:0)

如果你在父生命周期中缩进以保持奴隶活着,你可以将它守护:

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

或者您可以查看多进程API:

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

...允许在不同的子进程上进行类似线程的处理。