在 PyQt 中重定向输出 [英] Redirecting Output in PyQt

查看:56
本文介绍了在 PyQt 中重定向输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 QApplication,有很多类和函数,它在控制台上显示了很多标准输出.我想将此标准输出和标准错误重定向到 QTextBrowser(这也是 QApplication 的一部分).是否有任何调整来做到这一点.

I have a QApplication, with a lot of classes and functions, which displays a lot of stdout on the console. I want to redirect this stdout and stderr to a QTextBrowser(this is also part of the QApplication). Is there any tweak to do this.

推荐答案

我制作了一个开源 PyQt 自定义小部件库 - 其中一个是记录器类(XLoggerWidget),另一个是完整的 Python 解释器(XConsole 编辑).它可以满足您的需求.

I have made a library of open-source PyQt custom widgets - one of which is a logger class (XLoggerWidget) and another of which is a full Python interpreter (XConsoleEdit). It does what you're looking for.

如果需要,您可以在此处获取:http://dev.projexsoftware.com/projects/projexui

You can get it here if you want: http://dev.projexsoftware.com/projects/projexui

您正在寻找的部分在 XConsoleEdit (projexui.widgets.xconsoleedit) 中,但它的一般要点是:

The part you're looking for is in the XConsoleEdit (projexui.widgets.xconsoleedit), but the general gist of it is:

import logging
import sys

from PyQt4.QtCore import QObject,
                         pyqtSignal

from PyQt4.QtGui import QDialog, 
                        QVBoxLayout, 
                        QPushButton, 
                        QTextBrowser,
                        QApplication

logger = logging.getLogger(__name__)

class XStream(QObject):
    _stdout = None
    _stderr = None

    messageWritten = 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(QDialog):
    def __init__( self, parent = None ):
        super(MyDialog, self).__init__(parent)

        # setup the ui
        self._console = QTextBrowser(self)
        self._button  = QPushButton(self)
        self._button.setText('Test Me')

        # create the layout
        layout = QVBoxLayout()
        layout.addWidget(self._console)
        layout.addWidget(self._button)
        self.setLayout(layout)

        # create connections
        XStream.stdout().messageWritten.connect( self._console.insertPlainText )
        XStream.stderr().messageWritten.connect( self._console.insertPlainText )

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

    def test( self ):
        # print some stuff
        print 'testing'
        print 'testing2'

        # log some stuff
        logger.debug('Testing debug')
        logger.info('Testing info')
        logger.warning('Testing warning')
        logger.error('Testing error')

        # error out something
        print blah

if ( __name__ == '__main__' ):
    logging.basicConfig()

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

    dlg = MyDialog()
    dlg.show()

    if ( app ):
        app.exec_()

这是 XConsoleEdit 中内容的简化版本,但它的总体思路应该仍然适用于您不想下载代码的情况.

This is a simplified version of whats in the XConsoleEdit, but its the general idea and should still work for what you're going for if you don't want to download the code.

在这个例子中,你会注意到只有打印和错误日志被路由到编辑.如果你想将 Python 日志系统连接到编辑,你需要一些更复杂的东西,你定义一个 logging.Handler 并将它链接到你的小部件.

In this example tho, you'll notice that only the print and error logs are routed through to the edit. If you want to connect the Python logging system to the edit, you'll need something a little more complex where you define a logging.Handler and link it to your widget.

该代码将在 projexui.widgets.xloggerwidget 中找到

That code would be found in projexui.widgets.xloggerwidget

它有点长,也更复杂,所以我不打算在这里加载它...但是如果您对此有任何疑问,请告诉我.

Its a bit longer and more complex, so I'm not going to load it up here...but if you have any questions about it, let me know.

这篇关于在 PyQt 中重定向输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆