在QTextEdit小部件中复制stdout,stderr

时间:2013-11-08 09:14:11

标签: python-2.7 pyqt stdout pyside stderr

我的PySide计划已经困难了好几天了。我不认为这个问题难以置信,因为那里有答案。我遇到的问题似乎都不适合我。

我希望“监听”文件对象stdout和stderr,并在我的PySide程序运行时将内容输出到QText Edit小部件。现在,我已经意识到这个问题(或者类似的东西)之前已经被问过了,但就像我说的那样,由于某种原因无法让它为我工作,其他大多数其他解决方案都基于我能做到的那个'工作,所以对我来说这几天非常令人沮丧。这个解决方案(OutLog)包含在我下面的代码片段中,以防你们其中一个人可以看到我的拙劣实现。

要记住的事情:

1我在Windows 7上做这个(duuuh,da,da,duh)

2我正在使用eclipse并从IDE内部运行它(duh,da,da,duh,DUUUUH:如果建议适用于命令行或IDE,那将非常方便)

3我真的只想在程序运行时将stdout和stderr的输出复制到小部件。对于这种情况,逐行发生将是一个梦想,但即使它在一个循环结束时出现作为一个块或其他东西,这将是晶圆厂。

4哦,关于OutLog,有人可以告诉我,如果在 init 中将self.out设置为'None',这个类实际上可以工作吗?我的意思是,self.out 总是一个NoneType对象,对吧???

任何帮助都会受到赞赏,即使它只是指向我可以找到更多信息的地方。我一直在努力建立自己的解决方案(我有点像一个虐待狂),但我发现很难找到关于这些对象如何工作的相关信息。

无论如何,抱怨过来。这是我的代码:

#!/usr/bin/env python
import sys
import logging
import system_utilities

log = logging.getLogger()
log.setLevel("DEBUG")
log.addHandler(system_utilities.SystemLogger())

import matplotlib
matplotlib.use("Qt4Agg")
matplotlib.rcParams["backend.qt4"] = "PySide"
import subprocess
import plot_widget

from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure

from PySide import QtCore, QtGui


class MainWindow(QtGui.QMainWindow):
    """This is the main window class and displays the primary UI when launched.
    Inherits from QMainWindow.
    """

    def __init__(self):
        """Init function. 
        """
        super(MainWindow, self).__init__()
        self.x = None
        self.y = None
        self.data_plot = None
        self.plot_layout = None
        self.terminal = None
        self.setup_plot()
        self.setup_interface()

    def  setup_plot(self):
        """Member function to setup the graph window in the main UI.
        """

        #Create a PlotWidget object
        self.data_plot = plot_widget.PlotWidget()

        #Create a BoxLayout element to hold PlotWidget
        self.plot_layout = QtGui.QVBoxLayout()
        self.plot_layout.addWidget(self.data_plot)


    def setup_interface(self):
        """Member function to instantiate and build the composite elements of the 
        UI."""

        #Main widget houses layout elements (Layout cannot be placed directly in a QMainWindow).
        central_widget = QtGui.QWidget()
        test_splitter = QtGui.QSplitter(QtCore.Qt.Vertical)
        button_splitter = QtGui.QSplitter(QtCore.Qt.Horizontal)

        #UI BoxLayout elements
        central_layout = QtGui.QVBoxLayout()
        #button_layout = QtGui.QHBoxLayout()

        #UI PushButton elements
        exit_button = QtGui.QPushButton("Close")
        run_button = QtGui.QPushButton("Run...")

        #UI Text output
        self.editor = QtGui.QTextEdit()
        self.editor.setReadOnly(True)
        self.terminal = QtGui.QTextBrowser()
        self.terminal.setReadOnly(True)


        #UI PushButton signals
        run_button.clicked.connect(self.run_c_program)
        run_button.clicked.connect(self.data_plot.redraw_plot)
        exit_button.clicked.connect(QtCore.QCoreApplication.instance().quit)

        #Build the UI from composite elements
        central_layout.addLayout(self.plot_layout)
        central_layout.addWidget(self.editor)
        button_splitter.addWidget(run_button)
        button_splitter.addWidget(exit_button)
        test_splitter.addWidget(button_splitter)
        test_splitter.addWidget(self.terminal)
        test_splitter.setCollapsible(1, True)
        central_layout.addWidget(test_splitter)
        central_widget.setLayout(central_layout)
        self.setCentralWidget(central_widget)


        self.show()

class OutLog:
    def __init__(self, edit, out=None, color=None):
        """(edit, out=None, color=None) -> can write stdout, stderr to a
        QTextEdit.
        edit = QTextEdit
        out = alternate stream ( can be the original sys.stdout )
        color = alternate color (i.e. color stderr a different color)
        """
        self.edit = edit
        self.out = None
        self.color = color

    def write(self, m):
        if self.color:
            tc = self.edit.textColor()
            self.edit.setTextColor(self.color)

        self.edit.moveCursor(QtGui.QTextCursor.End)
        log.debug("this is m {}".format(m))
        self.edit.insertPlainText( m )

        if self.color:
            self.edit.setTextColor(tc)

        if self.out:
            self.out.write(m)




def main():


    app = QtGui.QApplication(sys.argv)

    log.debug("Window starting.")
    window = MainWindow()
    sys.stdout = OutLog(window.terminal, sys.stdout)
    sys.stderr = OutLog(window.terminal, sys.stderr, QtGui.QColor(255,0,0))
    window.show()

    sys.exit(app.exec_())
    log.info("System shutdown.")


if __name__ == '__main__':
    main()

“帮助我欧比万......”

先谢谢你们(和加尔斯: - ))

2 个答案:

答案 0 :(得分:5)

似乎您需要做的就是使用包装器对象覆盖sys.stderrsys.stdout,无论何时写入输出都会发出信号。

下面是一个演示脚本,应该或多或少地做你想要的。请注意,包装器类不会从sys.stdout/sys.stderr恢复sys.__stdout__/sys.__stderr__,因为后者对象可能与被替换的对象不同。

import sys
from PyQt4 import QtGui, QtCore

class OutputWrapper(QtCore.QObject):
    outputWritten = QtCore.pyqtSignal(object, object)

    def __init__(self, parent, stdout=True):
        QtCore.QObject.__init__(self, parent)
        if stdout:
            self._stream = sys.stdout
            sys.stdout = self
        else:
            self._stream = sys.stderr
            sys.stderr = self
        self._stdout = stdout

    def write(self, text):
        self._stream.write(text)
        self.outputWritten.emit(text, self._stdout)

    def __getattr__(self, name):
        return getattr(self._stream, name)

    def __del__(self):
        try:
            if self._stdout:
                sys.stdout = self._stream
            else:
                sys.stderr = self._stream
        except AttributeError:
            pass

class Window(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        widget = QtGui.QWidget(self)
        layout = QtGui.QVBoxLayout(widget)
        self.setCentralWidget(widget)
        self.terminal = QtGui.QTextBrowser(self)
        self._err_color = QtCore.Qt.red
        self.button = QtGui.QPushButton('Test', self)
        self.button.clicked.connect(self.handleButton)
        layout.addWidget(self.terminal)
        layout.addWidget(self.button)
        stdout = OutputWrapper(self, True)
        stdout.outputWritten.connect(self.handleOutput)
        stderr = OutputWrapper(self, False)
        stderr.outputWritten.connect(self.handleOutput)

    def handleOutput(self, text, stdout):
        color = self.terminal.textColor()
        self.terminal.setTextColor(color if stdout else self._err_color)
        self.terminal.moveCursor(QtGui.QTextCursor.End)
        self.terminal.insertPlainText(text)
        self.terminal.setTextColor(color)

    def handleButton(self):
        if QtCore.QTime.currentTime().second() % 2:
            print('Printing to stdout...')
        else:
            sys.stderr.write('Printing to stderr...\n')

if __name__ == '__main__':

    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.setGeometry(500, 300, 300, 200)
    window.show()
    sys.exit(app.exec_())

<强> NB

应尽早创建OutputWrapper的实例,以确保需要sys.stdout/sys.stderr的其他模块(例如logging模块)在必要时使用包装版本。

答案 1 :(得分:0)

self.out = None可能是拼写错误,应该是self.out = out。这样,您可以看到控制台中打印的任何内容。这是确保代码打印任何内容的第一步。

接下来是您需要了解哪个输出正在重定向。子进程获得自己的stdio,因此父进程stdout的任何重定向都不会产生任何影响。

使用子进程获取stdio并非易事。我建议从subprocess.communicate()开始,它将所有输出作为单个字符串。这通常足够好。

相关问题