2015-05-26 33 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()會如何幫助。原因如下: –

相關問題