我需要在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()调用?
如果它是一个Python脚本,你可以改变它来导入和使用它作为一个库,而不是? – jfs 2012-07-12 21:59:07
可能你通过所有线路一下子.communicate()? – jfs 2012-07-12 22:00:09