0

由于inputraw_input()停止程序运行,我想使用一个子进程来运行这个程序......

while True: print raw_input()

并得到它的输出。

这是我的阅读计划:

import subprocess
process = subprocess.Popen('python subinput.py', stdout=subprocess.PIPE, stderr=subprocess.PIPE) 
while True:
    output=process.stdout.read(12)
    if output=='' and process.poll()!=None:
        break
    if output!='':
        sys.stdout.write(output)
        sys.stdout.flush()

当我运行它时,子进程退出的速度几乎和它开始时一样快。我怎样才能解决这个问题?

4

3 回答 3

1

我认为问题在于子进程没有直接连接到stdoutand stdin,因此无法接收键盘输入。大概 raw_input() 正在引发异常。

如果这是一个实际问题而不是实验,我建议您使用诸如 curses 或 pygame 之类的库来处理您的输入。如果您正在尝试并想自己做,那么我想您将不得不查看线程而不是子进程,尽管尝试这样做是一件相当复杂的事情,因此您肯定会遇到其他问题。

于 2012-06-11T04:30:21.997 回答
1

恐怕它不会这样工作。

您假设,这subprocess将附加您的控制台(您的特殊情况stdin)。这不起作用,该模块只有两个选项用于指定:PIPESTDOUT.

当没有指定任何内容时,子进程将无法使用相应的流——它的输出将无处可去,或者它不会收到任何输入。raw_input()由于EOF而结束。

要走的路是在“主”程序中输入您的输入,并在子流程中完成工作。

编辑:

这是一个例子multiprocessing

from multiprocessing import Process, Pipe
import time

def child(conn):
    while True:
        print "Processing..."
        time.sleep(1)
        if conn.poll(0):
            output = conn.recv()
            print output
        else:
            print "I got nothing this time"

def parent():
    parent_conn, child_conn = Pipe()
    p = Process(target=child, args=(child_conn,))
    p.start()
    while True:
        data = raw_input()
        parent_conn.send(data)
    # p.join() - you have to find some way to stop all this...
    # like a specific message to quit etc.


if __name__ == '__main__':
    parent()

当然,您需要找到一种方法来阻止这种合作,从而使其更加强大。在我的示例中,两个进程都在同一个文件中,但您可以以不同的方式组织它。

此示例适用于 Linux,您可能在 Windows 上遇到管道问题,但应该完全可以解决。

“处理”是您想要做其他事情的部分,而不仅仅是等待来自父级的数据。

于 2012-06-11T04:38:06.483 回答
0

好吧,尝试不同的架构。您可以使用zeromq.

  1. Producer 生产所有项目(这里是通过 stdout 发送的输出)并通过zmq.

  2. 消费者应该监听生产者正在广播的端口号并相应地处理它们。

这是示例http://code.saghul.net/implementing-a-pubsub-based-application-with

Note

使用geventmultiprocessing生成这些进程。

您将拥有master负责产卵producerconsumer

于 2012-06-11T06:30:31.490 回答