如何将记录器输出重定向到PyQt文本小部件

时间:2014-06-28 18:16:07

标签: python pyqt

Redirecting Output in PyQt上发布的代码同时做了两件好事:它利用logging模块很好地格式化邮件,并将标准stdoutstderr重定向到QT QTextBrowser小部件。 但我希望QTextBrowser能够接收运行代码中的所有打印输出。特别是我想重定向来自logger的格式正确的消息。 理想的解决方案将重定向每个记录器。输出到QTextBrowser(而不只是stdoutstderr)。事实上,如果我不得不在两个人之间做出选择,我宁愿重定向记录器的消息而不是stdoutstderr消息.... 以下是用于打印格式化消息的命令:

logger.debug('debug message')
logger.info('info message')
logger.warning('warning message')
logger.error('error message')

以下是代码: enter image description here

======

import sys
from PyQt4 import QtCore, QtGui
import logging
logger = logging.getLogger(__name__)

class XStream(QtCore.QObject):
    _stdout = None
    _stderr = None
    messageWritten = QtCore.pyqtSignal(str)
    def flush( self ):
        pass
    def fileno( self ):
        return -1
    def write( self, msg ):
        if ( not self.signalsBlocked() ):
            self.messageWritten.emit(unicode(msg))

    @staticmethod
    def stdout():
        if ( not XStream._stdout ):
            XStream._stdout = XStream()
            sys.stdout = XStream._stdout
        return XStream._stdout

    @staticmethod
    def stderr():
        if ( not XStream._stderr ):
            XStream._stderr = XStream()
            sys.stderr = XStream._stderr
        return XStream._stderr

class MyDialog(QtGui.QDialog):
    def __init__( self, parent = None ):
        super(MyDialog, self).__init__(parent)

        self._console = QtGui.QTextBrowser(self)
        self._button  = QtGui.QPushButton(self)
        self._button.setText('Test Me')

        layout = QtGui.QVBoxLayout()
        layout.addWidget(self._console)
        layout.addWidget(self._button)
        self.setLayout(layout)

        XStream.stdout().messageWritten.connect( self._console.insertPlainText )
        XStream.stderr().messageWritten.connect( self._console.insertPlainText )

        self._button.clicked.connect(self.test)

    def test( self ):
        print 'printing LINE 1'
        print 'printing LINE 2'
        logger.debug('debug message')
        logger.info('info message')
        logger.warning('warning message')
        logger.error('error message')
        # error out something
        print blah

if ( __name__ == '__main__' ):
    # logging.basicConfig()
    # logging.basicConfig(filename='example.log',level=logging.DEBUG)
    logging.basicConfig(level=logging.DEBUG)

    app = None
    if ( not QtGui.QApplication.instance() ):
        app = QtGui.QApplication([])

    dlg = MyDialog()
    dlg.show()

    if ( app ):
        app.exec_()

以后张贴::完整的工作示例::由达诺先生解决

import sys
from PyQt4 import QtCore, QtGui
import logging

class QtHandler(logging.Handler):
    def __init__(self):
        logging.Handler.__init__(self)
    def emit(self, record):
        record = self.format(record)
        if record: XStream.stdout().write('%s\n'%record)
        # originally: XStream.stdout().write("{}\n".format(record))


logger = logging.getLogger(__name__)
handler = QtHandler()
handler.setFormatter(logging.Formatter("%(levelname)s: %(message)s"))
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)


class XStream(QtCore.QObject):
    _stdout = None
    _stderr = None
    messageWritten = QtCore.pyqtSignal(str)
    def flush( self ):
        pass
    def fileno( self ):
        return -1
    def write( self, msg ):
        if ( not self.signalsBlocked() ):
            self.messageWritten.emit(unicode(msg))
    @staticmethod
    def stdout():
        if ( not XStream._stdout ):
            XStream._stdout = XStream()
            sys.stdout = XStream._stdout
        return XStream._stdout
    @staticmethod
    def stderr():
        if ( not XStream._stderr ):
            XStream._stderr = XStream()
            sys.stderr = XStream._stderr
        return XStream._stderr

class MyDialog(QtGui.QDialog):
    def __init__( self, parent = None ):
        super(MyDialog, self).__init__(parent)

        self._console = QtGui.QTextBrowser(self)
        self._button  = QtGui.QPushButton(self)
        self._button.setText('Test Me')

        layout = QtGui.QVBoxLayout()
        layout.addWidget(self._console)
        layout.addWidget(self._button)
        self.setLayout(layout)

        XStream.stdout().messageWritten.connect( self._console.insertPlainText )
        XStream.stderr().messageWritten.connect( self._console.insertPlainText )

        self._button.clicked.connect(self.test)

    def test( self ):
        logger.debug('debug message')
        logger.info('info message')
        logger.warning('warning message')
        logger.error('error message')
        print 'Old school hand made print message'

if ( __name__ == '__main__' ):
    app = None
    if ( not QtGui.QApplication.instance() ):
        app = QtGui.QApplication([])
    dlg = MyDialog()
    dlg.show()
    if ( app ):
        app.exec_()

2 个答案:

答案 0 :(得分:10)

您可以创建自定义logging.Handler并将其添加到logger

import logging
logger = logging.getLogger(__name__)

class QtHandler(logging.Handler):

    def __init__(self):
        logging.Handler.__init__(self)

    def emit(self, record):
        record = self.format(record)
        XStream.stdout().write("{}\n".format(record))

handler = QtHandler()
handler.setFormatter(logging.Formatter("%(levelname)s: %(message)s"))
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)

然后移除logging.basisConfig(level=logging.DEBUG)块中的if __name__ == "__main__":行。您将看到您的日志消息仅显示在对话框中。

答案 1 :(得分:2)

dano给出的答案适用于2.7.x,但不适用于3.x。

要获得@dano在3.4.3中提供的代码,我必须对print语句进行明显的更改,并将XStream类中的write()方法从self.messageWritten.emit(unicode(msg))更改为{{1} }。那个unicode电话只是把对话放在那里,然后好好地盯着我看。