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

2024-10-02 22:24:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要用Python启动一个Python脚本并保持它的正常运行。在

为了便于论证,假设有一个名为从属.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

“计划”从属.py“接收字符串,计算字符串的输入长度 并用print语句将长度输出到stdout。在

它应该一直运行,直到我给它一个“quit”或“q”作为输入。在

同时,在另一个叫做硕士.py,我将调用从属.py““

^{pr2}$

但是从属.py我用Popen()打开的程序只接受一个communicate()调用。它在一个communicate()调用之后结束。在

对于这个例子,我想从属.py继续运行,作为客户机-服务器模型中的服务器,直到它通过通信接收到“quit”或“q”字符串。我该怎么做子流程.Popen()打电话?在


Tags: 字符串py服务器脚本leniflinelower
2条回答

如果每个输入行产生已知数量的输出行,则可以:

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。在

如果您缩进以使从属服务器在父生命周期中保持活动状态,则可以将其守护:

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

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

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

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

相关问题 更多 >