Python 2.7 从子程序到pyQT4小部件的实时输出

Python 2.7 从子程序到pyQT4小部件的实时输出,python-2.7,pyqt4,Python 2.7,Pyqt4,我正在尝试将标准输出从子程序重定向到QTextBrowser小部件。(Python 2.7,窗口7,pyQT4) 这是子程序,它将位于可执行文件中: #test.py import time print ("ABC") time.sleep(1) print ("DEF") time.sleep(1) print ("GHI") time.sleep(1) print ("JKL") 我的pyQT4程序: from PyQt4 import QtGui import subprocess,

我正在尝试将标准输出从子程序重定向到QTextBrowser小部件。(Python 2.7,窗口7,pyQT4)

这是子程序,它将位于可执行文件中:

#test.py
import time

print ("ABC")
time.sleep(1)
print ("DEF")
time.sleep(1)
print ("GHI")
time.sleep(1)
print ("JKL")
我的pyQT4程序:

from PyQt4 import QtGui
import subprocess, time, os, sys
from subprocess import Popen, PIPE
class GUI (QtGui.QWidget):
    def __init__(self):
        ...
        self.initUI()

    def initUI(self):
        ...
        self.edit = QtGui.QTextBrowser()
        grid.addWidget (self.edit, 7, 0, 5, 7)

    def run(self):
        p = Popen (['C:\\...\\test.exe'], stdout=PIPE, stderr=subprocess.STDOUT)
        while True:
            line = p.stdout.readline()
            if not line:
                break
            self.append_edit('>>>' + line)

    def append_edit(self, string):
        self.edit.append(string)
def main():
    app = QtGui.QApplication(sys.argv)
    upgrade = GUI()
    sys.exit (app.exec_())
我上面的程序将等待子程序完成运行,然后将所有内容打印到小部件中。我想要的是,当子程序运行时,程序将
ABC
然后
DEF
等输出到小部件中,间隔1秒

编辑:我可以将子流程输出到cmd,但是,如果我将其打印到QTextBrowser中,它将无法工作

我已经看到很多关于这个问题的问题,但似乎没有一个能回答我的问题

提前谢谢

编辑:我还是python新手。我认为这可能就是问题所在:通过添加
QtGui.QApplication.processEvents()

所以当我在程序中点击run时,它不是先打印出来然后等待1秒,而是总共等待3秒,然后在打印之前和之后都打印出来。是什么导致了这个问题


编辑:即使我的代码中有
QtGui.QApplication.processEvents()
,我仍然有同样的问题。在将输出显示到QTextBrowser之前,它将运行整个子程序。

不幸的是,运行时问题的可能重复是我程序中的另一个错误,但子进程仍然存在相同的问题。在
Popen
之后,
p.stdout.readline()
在哪里添加
processEvents
调用,和
self.append\u edit('>>>'+行)
我很惊讶输出超过了“ABC”。我的理解是,您的无止境循环readline首先返回“ABC”,然后返回“break”,因为此时管道应该是空的。
def initUI(self):
    ...
    running = QtGui.QPushButton('Run')
    running.clicked.connect(self.run)
def run(self):
    time.sleep(1)
    append_edit('Before')
    time.sleep(2)
    append_edit('After')