来自命令行的 PyQt 程序 运行 未实时路由控制台输出

PyQt program running from command line not routing the console output in real time

大家好,我是 PyQt 的新手。 有人可以建议为什么下面的程序没有将 print.py 的标准输出实时填充到文本框 widget.This 当命令 line.If 为 运行 时存在问题我们是 运行 pycharm 中的相同代码,我们将获得实时输出。命令行执行会将数据作为块(大约 4K)显示到文本框。

from PyQt4 import QtGui,QtCore
import sys

class gui(QtGui.QMainWindow):
    def __init__(self):
        super(gui, self).__init__()
        self.initUI()

    def dataReady(self):
        cursor = self.output.textCursor()
        cursor.movePosition(cursor.End)
        cursor.insertText(str(self.process.readAll()))
        self.output.ensureCursorVisible()

    def initUI(self):
        # Layout are better for placing widgets
        layout = QtGui.QHBoxLayout()
        self.output = QtGui.QTextEdit()

        layout.addWidget(self.output)

        centralWidget = QtGui.QWidget()
        centralWidget.setLayout(layout)
        self.setCentralWidget(centralWidget)

        # QProcess object for external app
        self.process = QtCore.QProcess(self)
        # QProcess emits `readyRead` when there is data to be read
        self.process.readyRead.connect(self.dataReady)

        # Run program
        self.process.start('python', ['./print.py'])

#Function Main Start
def main():
    app = QtGui.QApplication(sys.argv)
    ui=gui()
    ui.show()
    sys.exit(app.exec_())
#Function Main END

if __name__ == '__main__':
    main()

这是 print.py

的代码
import time
n=10
while(n):
    print "Hello world"
    time.sleep(1)
    n = n-1

您应该在子进程中显式刷新 print.py 脚本(子脚本)运行 的输出缓冲区。 print 的默认行为是将输出发送到标准输出 (stdout)。因此,您应该在每个打印语句之后在子脚本中显式调用 sys.sydout.flush(),以确保子脚本的打印语句的内容及时提供给父脚本。