我试图创建一个python进程,读取一些输入,处理它并打印出结果.处理由子流程(斯坦福大学的NER)完成,对于ilustration,我将使用'cat'.我不确切知道NER会给出多少输出,所以我使用一个单独的线程来收集它并打印出来.以下示例说明.
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 …Run Code Online (Sandbox Code Playgroud)