我正在嘗試使讀取一些輸入,處理它並打印出結果的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。解決方案應該是平臺無關的。
有人曾經告訴過我雙管有問題,沒有提供好的解決方案。 –