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.
问问题
9104 次
1 回答
3
我制作了一个开源 PyQt 自定义小部件库——其中一个是记录器类 (XLoggerWidget),另一个是完整的 Python 解释器 (XConsoleEdit)。它可以满足您的需求。
如果需要,可以在这里获取:http: //dev.projexsoftware.com/projects/projexui
您正在寻找的部分在 XConsoleEdit (projexui.widgets.xconsoleedit) 中,但它的一般要点是:
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 中内容的简化版本,但它是一般的想法,如果您不想下载代码,它仍然适用于您的目标。
在此示例中,您会注意到只有打印和错误日志被路由到编辑。如果你想将 Python 日志系统连接到编辑,你需要一些更复杂的东西,你定义一个 logging.Handler 并将它链接到你的小部件。
该代码可以在 projexui.widgets.xloggerwidget 中找到
它有点长而且更复杂,所以我不会在这里加载它......但如果你有任何问题,请告诉我。
于 2012-08-01T17:22:48.637 回答