簡體   English   中英

從子程序到 pyQT 小部件的標准輸出的實時輸出

[英]RealTime output from a subprogram to stdout of a pyQT Widget

嗨,我看到已經有很多關於這個問題的問題,但似乎沒有一個能回答我的問題。

根據下面的鏈接,我什至在使用 windows 時嘗試了 winpexpect,但是它似乎對我有用。 從 ffmpeg 獲取實時輸出以用於進度條(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()

QProcess是非常相似的subprocess ,但它更方便(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() 

這是對 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() 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM