2012-07-12 46 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