【问题标题】:How to start a child process and use it as a server in Python?如何启动子进程并将其用作 Python 中的服务器?
【发布时间】:2012-07-13 06:34:36
【问题描述】:

我需要在 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”接收一个字符串,计算输入的字符串长度 并使用打印语句将长度输出到标准输出。

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

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

【问题讨论】:

  • 如果它是 Python 脚本,您可以将其更改为导入并将其用作库吗?
  • 你能一次将所有行都传递给 .communicate() 吗?

标签: python subprocess popen


【解决方案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

【讨论】:

  • 不,我需要该程序才能熬夜。因此,看起来我需要使用线程或多处理。
  • master.py 退出时,你想让'slave.py' 保持活力吗?如果你开始第二个master.py会发生什么?
【解决方案2】:

如果您打算让奴隶在父生命周期内保持活力,您可以将其守护:

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-21
    • 1970-01-01
    • 1970-01-01
    • 2013-09-18
    • 1970-01-01
    • 2015-03-12
    • 2016-02-21
    • 1970-01-01
    相关资源
    最近更新 更多