2012-07-12 40 views
0

我需要在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打印聲明。

它應該運行,直到我給它一個「跳槽」或「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程序只需要一個溝通( )電話。它在通信()調用之後結束。

對於這個例子,我想有slave.py保持運行,如在客戶端 - 服務器模型的服務器,直到它收到一個「跳槽」或「Q」的字符串通過通信。我怎麼用subprocess.Popen()調用?

+0

如果它是一個Python腳本,你可以改變它來導入和使用它作爲一個庫,而不是? – jfs 2012-07-12 21:59:07

+0

可能你通過所有線路一下子.communicate()? – jfs 2012-07-12 22:00:09

回答

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

+0

不,我需要的程序熬夜。因此,它看起來像我需要使用線程或多處理。 – SQA777 2012-07-13 00:07:04

+0

你想'slave.py'在'master.py'退出時保持活躍狀態​​嗎?如果你啓動第二個'master.py'會怎麼樣? – jfs 2012-07-13 01:49:35