2015-05-26 34 views
7

我正在尝试使读取一些输入,处理它并打印出结果的python进程。处理由一个子进程(斯坦福大学的NER)完成,因为我将使用'猫'。我不知道NER会给出多少输出,所以我使用一个单独的线程来收集所有内容并将其打印出来。以下示例说明。如何从Python子进程收集输出

import sys 
import threading 
import subprocess 

# start my subprocess 
cat = subprocess.Popen(
    ['cat'], 
    shell=False, stdout=subprocess.PIPE, stdin=subprocess.PIPE, 
    stderr=None) 


def subproc_cat(): 
    """ Reads the subprocess output and prints out """ 
    while True: 
     line = cat.stdout.readline() 
     if not line: 
      break 
     print("CAT PROC: %s" % line.decode('UTF-8')) 

# a daemon that runs the above function 
th = threading.Thread(target=subproc_cat) 
th.setDaemon(True) 
th.start() 

# the main thread reads from stdin and feeds the subprocess 
while True: 
    line = sys.stdin.readline() 
    print("MAIN PROC: %s" % line) 
    if not line: 
     break 
    cat.stdin.write(bytes(line.strip() + "\n", 'UTF-8')) 
    cat.stdin.flush() 

这似乎很好,当我用键盘输入文本。但是,如果我尝试将输入输入到我的脚本中(cat file.txt | python3 my_script.py),似乎会出现赛车状况。有时我会得到适当的输出,有时候不会,有时会锁定。任何帮助,将不胜感激!

我在运行Ubuntu 14.04,python 3.4.0。解决方案应该是平台无关的。

+0

有人曾经告诉过我双管有问题,没有提供好的解决方案。 –

回答

2

末添加th.join()否则你可能会杀死线程已经处理了所有的输出过早前在主线程退出:守护线程没有生存的主线程(或删除th.setDaemon(True),而不是th.join())。

+0

Doh,这么简单,我错过了。谢谢! :D 但是我会保留另一个线程作为守护进程,但是我会在主循环之后休眠主​​线程,让其他线程有时间输出结果。 –

+0

@FlorijanStamenkovićtime.sleep()在这里是错误的。如果子进程可能停滞,你可以将'timeout'参数传递给'th.join()'。 – jfs

+0

J.F.,感谢您的评论。我不确定我了解join()会如何帮助。原因如下: –

相关问题