【发布时间】:2016-08-06 00:16:01
【问题描述】:
我有一个包含 100 行的示例文件,我正在使用带有cat 的子进程读取它。但是,队列中的输出总是被截断。我怀疑这可能是由于cat 缓冲其输出,因为它检测到管道。
p = subprocess.Popen("cat file.txt",
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE,
shell=True,
bufsize=0)
我正在使用单独的线程从cat 的 stdout 和 stderr 管道中读取:
def StdOutThread():
while not p.stdout.closed and running:
line = ""
while not line or line[-1] != "\n":
r = p.stdout.read(1)
if not r:
break
line += r
pending_line["line"] = line
if line and line[-1] == "\n":
line = line[:-1]
if line:
queue.put(("out", line))
这些线程被启动并将它们读取的内容转储到队列中。当cat 处于活动状态时,主线程从这个队列中读取。
with CancelFunction(p.kill):
try:
stdout_thread = threading.Thread(target=StdOutThread)
stdout_thread.start()
while p.poll() is None:
ReadFromQueue()
while not queue.empty():
ReadFromQueue()
finally:
running = False
stdout_thread.join()
我考虑过使用 pexpect 来解决这个问题,但同时也想区分 pexpect 似乎不可能的 stdout 和 stderr。非常感谢您的帮助。
【问题讨论】:
标签: python multithreading multiprocessing cat