RealTime从子程序输出到pyQT Widget的stdout

时间:2014-02-27 13:01:09

标签: python subprocess pyqt4

您好我已经看到在这个问题上已经有很多问题,但是他们似乎都没有回答我的问题。

如下面的链接我甚至尝试了winpexpect,因为我正在使用Windows,但它看起来似乎对我有用。 Getting realtime output from ffmpeg to be used in progress bar (PyQt4, stdout)

我正在使用subprocess.Popen运行一个子程序,并希望在pyQt Widget中看到实时结果。目前它在pyQt小部件中显示结果,但仅在子命令完成执行后才显示。我需要知道是否有办法让我们可以将子进程的输出实时输入到窗口中。请参阅下面的代码,我尝试了所有这些。

import sys
import os
from PyQt4 import QtGui,QtCore
from threading import Thread
import subprocess
#from winpexpect import winspawn



class EmittingStream(QtCore.QObject):
    textWritten = QtCore.pyqtSignal(str)

    def write(self, text):
        self.textWritten.emit(str(text))

class gui(QtGui.QMainWindow):

    def __init__(self):
    # ...
        super(gui, self).__init__()
    # Install the custom output stream
        sys.stdout = EmittingStream(textWritten=self.normalOutputWritten)
        self.initUI()

    def normalOutputWritten(self, text):
        cursor = self.textEdit.textCursor()
        cursor.movePosition(QtGui.QTextCursor.End)
        cursor.insertText(text)
        self.textEdit.ensureCursorVisible()

    def callProgram(self):

        command="ping 127.0.0.1"
        #winspawn(command)
              py=subprocess.Popen(command.split(),stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
        result,_=py.communicate()
        for line in result:
            print line
        print result


    def initUI(self):
        self.setGeometry(100,100,300,300)
        self.show()

        self.textEdit=QtGui.QTextEdit(self)
        self.textEdit.show()
        self.textEdit.setGeometry(20,40,200,200)

        print "changing sys.out"
        print "hello"

        thread = Thread(target = self.callProgram)
        thread.start()


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

if __name__ == '__main__':
    main()

2 个答案:

答案 0 :(得分:23)

QProcesssubprocess非常相似,但在(Py)Qt代码中使用会更方便。因为它利用信号/插槽。此外,它以异步方式运行该进程,因此您没有使用QThread

我已修改(并清理)了QProcess的代码:

import sys
from PyQt4 import QtGui,QtCore

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 callProgram(self):
        # run the process
        # `start` takes the exec and a list of arguments
        self.process.start('ping',['127.0.0.1'])

    def initUI(self):
        # Layout are better for placing widgets
        layout = QtGui.QHBoxLayout()
        self.runButton = QtGui.QPushButton('Run')
        self.runButton.clicked.connect(self.callProgram)

        self.output = QtGui.QTextEdit()

        layout.addWidget(self.output)
        layout.addWidget(self.runButton)

        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)

        # Just to prevent accidentally running multiple times
        # Disable the button when process starts, and enable it when it finishes
        self.process.started.connect(lambda: self.runButton.setEnabled(False))
        self.process.finished.connect(lambda: self.runButton.setEnabled(True))


#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() 

答案 1 :(得分:1)

这里是对PyQt5可接受答案的改编。

import sys

# On Windows it looks like cp850 is used for my console. We need it to decode the QByteArray correctly.
# Based on https://forum.qt.io/topic/85064/qbytearray-to-string/2
import ctypes
CP_console = "cp" + str(ctypes.cdll.kernel32.GetConsoleOutputCP())

from PyQt5 import QtCore, QtGui, QtWidgets

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

    def dataReady(self):
        cursor = self.output.textCursor()
        cursor.movePosition(cursor.End)

        # Here we have to decode the QByteArray
        cursor.insertText(str(self.process.readAll().data().decode(CP_console)))
        self.output.ensureCursorVisible()

    def callProgram(self):
        # run the process
        # `start` takes the exec and a list of arguments
        self.process.start('ping',['127.0.0.1'])

    def initUI(self):
        # Layout are better for placing widgets
        layout = QtWidgets.QVBoxLayout()
        self.runButton = QtWidgets.QPushButton('Run')
        self.runButton.clicked.connect(self.callProgram)

        self.output = QtWidgets.QTextEdit()

        layout.addWidget(self.output)
        layout.addWidget(self.runButton)

        centralWidget = QtWidgets.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)

        # Just to prevent accidentally running multiple times
        # Disable the button when process starts, and enable it when it finishes
        self.process.started.connect(lambda: self.runButton.setEnabled(False))
        self.process.finished.connect(lambda: self.runButton.setEnabled(True))


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

if __name__ == '__main__':
    main()