PySide and python logging

2019-04-11 11:00发布

I want to use PySide to create a simple application just to output from python logging.

def mpm_print():
    print 'OK'

def mpm_log():
   log.info('OK')

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

        self.initUI()
        mpm_print()
        mpm_log()

    def initUI(self):

        font = QtGui.QFont()
        font.setFamily("Courier")
        font.setFixedPitch(True)
        font.setPointSize(10)

        self.qtxt = QtGui.QTextEdit(self)
        self.qtxt.resize(self.size())
        self.qtxt.setReadOnly(True)
        self.qtxt.setFont(font)

        self.resize(640, 512)
        self.setWindowTitle('Efficient Algorithms Lab')

        self.show()

I would like to know:

  • How can I redirect stdout to write to the QTextEdit ?
  • How can I write a logging.Handler to log to QTextEdit ?

Thanks

标签: python qt pyside
1条回答
放我归山
2楼-- · 2019-04-11 11:39

This is copy-pasted from PyQt mailing-list, but should be applicable to PySide

This should do what you want.

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)
        self.edit.insertPlainText( m )

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

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

Example usage:

import sys
sys.stdout = OutLog( edit, sys.stdout)
sys.stderr = OutLog( edit, sys.stderr, QtGui.QColor(255,0,0) )
查看更多
登录 后发表回答