簡體   English   中英

如何啟動子進程並將其用作Python中的服務器?

[英]How to start a child process and use it as a server in Python?

我需要在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”接收一個字符串,計算該字符串的輸入長度,並使用打印語句將該長度輸出到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程序僅進行一次communication()調用。 它在一次communication()調用之后結束。

對於此示例,我希望slave.py繼續作為客戶端-服務器模型中的服務器運行,直到通過通信接收到“ quit”或“ q”字符串為止。 我該如何使用subprocess.Popen()調用?

如果每個輸入線產生已知數量的輸出線,則可以:

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'

否則,您可能需要線程來異步讀取輸出

如果縮進以使奴隸在父生命周期中保持活動狀態,則可以將其守護進程:

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

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

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

...允許對不同的子進程進行類似線程的處理。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM