gpt4 book ai didi

python - 如何从 python (2.5) 中的 subprocess.Popen 获取 'real-time' 信息

转载 作者:IT老高 更新时间:2023-10-28 20:35:43 28 4
gpt4 key购买 nike

我想通过以下方式使用子流程模块:

  1. 创建一个可能需要很长时间才能执行的新进程。
  2. 捕获stdout(或stderr,或可能两者兼有,一起或单独)
  3. 处理来自子进程传入的数据,可能会在接收到的每一行上触发事件(在 wxPython 中说),或者只是暂时将它们打印出来。

我已经使用 Popen 创建了进程,但是如果我使用communicate(),一旦进程终止,数据就会立即向我涌来。

如果我创建一个单独的线程来执行 myprocess.stdout 的阻塞 readline()(使用 stdout = subprocess.PIPE)我在进程终止之前,也不要使用此方法获得任何行。 (不管我设置为 bufsize)

有没有一种方法可以解决这个问题,并且在多个平台上运行良好?

最佳答案

使用似乎不起作用的代码进行更新(无论如何在 Windows 上)

class ThreadWorker(threading.Thread):
def __init__(self, callable, *args, **kwargs):
super(ThreadWorker, self).__init__()
self.callable = callable
self.args = args
self.kwargs = kwargs
self.setDaemon(True)

def run(self):
try:
self.callable(*self.args, **self.kwargs)
except wx.PyDeadObjectError:
pass
except Exception, e:
print e



if __name__ == "__main__":
import os
from subprocess import Popen, PIPE

def worker(pipe):
while True:
line = pipe.readline()
if line == '': break
else: print line

proc = Popen("python subprocess_test.py", shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE)

stdout_worker = ThreadWorker(worker, proc.stdout)
stderr_worker = ThreadWorker(worker, proc.stderr)
stdout_worker.start()
stderr_worker.start()
while True: pass

关于python - 如何从 python (2.5) 中的 subprocess.Popen 获取 'real-time' 信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/874815/

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