在进程完成之前,Python 脚本无法读取 Popen 输出(在 Windows 上)

标签 python windows python-2.7 tkinter subprocess

我有一个 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/

相关文章:

python - Django - CSS 文件未在生产中加载(调试 : False)

windows - Microsoft.VsHub.Server.HttpHostx64.exe 消耗大量资源并导致 Visual Studio 2015 崩溃

python - 在 python3.x 中标记化

python - 如何强制在 Mac OsX.6 中为单个 shell session 使用 python 2.6_64bit?

python - Django 测试。状态 200 和 302

windows - 如何将批处理输出写入文本光标?

c++ - Win32API : How to request embedded windows event notifications out to a parent window

Python __super黑魔法失败了

python - PyUSB 1.0 : NotImplementedError: Operation not supported or unimplemented on this platform

Python:增加数组索引