我有一个 Python GUI 应用程序,它使用 subprocess.Popen 调用来调用另一个 Python 脚本。我的 GUI 中有一个 Tkinter 文本框,我想在其中显示子进程的输出。在 OS X 上,这可以完美地工作,但在 Windows 7 上,直到子进程完成运行后,输出才会显示在文本框中。如何在 Windows 上实时打印输出?
启动子进程的代码:
p = Popen(command, stdout=PIPE, stderr=STDOUT, bufsize=1, close_fds=ON_POSIX)
t = Thread(target=read_and_print, args=(p, log_output))
t.daemon = True
t.start()
将输出打印到文本框的函数。这是在单独的线程中运行的,以便在子进程执行时 GUI 不会挂起。
def read_and_print(process, textarea):
out = process.stdout
for line in iter(out.readline, b''):
textarea.insert(END, line)
textarea.see(END)
#this triggers an update of the text area, otherwise it doesn't update
textarea.update_idletasks()
最佳答案
问题是在 Windows 上运行的 Python 将 STDERR 保存在缓冲区中,直到命令完成运行(!?)。
解决方案是告诉 Python 在不使用 -u
标志缓冲其输出的情况下运行。这使得我传递给 subprocess.Popen
["python", "-u", "myprogram.py"]
而不是
["python", "myprogram.py"]
关于在进程完成之前,Python 脚本无法读取 Popen 输出(在 Windows 上),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27432727/