gpt4 book ai didi

python - 如何收集 Python 子进程的输出

转载 作者:太空狗 更新时间:2023-10-29 21:56:51 24 4
gpt4 key购买 nike

我正在尝试创建一个 python 进程来读取一些输入、处理它并打印出结果。处理由一个子进程(斯坦福大学的 NER)完成,为了便于说明,我将使用“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 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。该解决方案应该与平台无关。

最佳答案

在末尾添加 th.join() 否则当主线程退出时,您可能会在线程处理完所有输出之前过早地终止线程:守护线程无法在主线程中存活(或删除th.setDaemon(True) 而不是 th.join()

关于python - 如何收集 Python 子进程的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30451599/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com