将文本附加到stdout并将其传递给QTextBrowser

问题描述 投票:0回答:1

我试图在我的PyQt(pyqtgraph)应用程序中显示stdout和stderr。如果我按照Ferdinand Beyer对这个question的回答,我能够这样做。

但是,当我尝试通过更改write()函数内的文本在stdout之前附加时间戳

new_text = '{}> {}'.format(time.strftime('%X'), old_text)

我在stdout消息之前和之后得到了时间戳。我对这种行为感到困惑,并且无法弄清楚它为什么会发生以及如何防止它。

更新:我的代码直接:

from pyqtgraph.Qt import QtGui,QtCore
from pyqtgraph.dockarea import DockArea,Dock
import pyqtgraph as pg
import sys
import time

app = QtGui.QApplication([])
win = QtGui.QMainWindow()
win.resize(300,300)
area = DockArea()
win.setCentralWidget(area)
d1 = Dock("cmd output", size=(300,300))
area.addDock(d1)

w1 = pg.LayoutWidget()
gui_cmd_bw = QtGui.QTextBrowser()
w1.addWidget(gui_cmd_bw,0,0)

d1.addWidget(w1)

class EmittingStream(QtCore.QObject):

    textWritten = QtCore.pyqtSignal(str)

    def write(self, text):
        self.textWritten.emit(str(text))        

def normalOutputWritten(text):
    """Append text to the QTextEdit."""
    # this works without problems.
    #gui_cmd_bw.insertPlainText(text)
    timestamp = '{}> '.format(time.strftime('%X'))
    # this adds timestamp before and after the stdout
    gui_cmd_bw.insertPlainText(timestamp+text)
    # this produces similar result
    #gui_cmd_bw.append(timestamp+text)

# cmd output to application browser
sys.stdout = EmittingStream(textWritten=normalOutputWritten)
sys.stderr = EmittingStream(textWritten=normalOutputWritten)

win.show()
if __name__ == '__main__':    
    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
        print('stdout text')        
        QtGui.QApplication.instance().exec_()

最终输出如下所示:

14:15:16> stdout text
14:15:16> 
python pyqt stdout pyqtgraph
1个回答
0
投票

我找到了解决问题的快速解决方法,这对我来说已经足够了。

由于print()函数为每个输出调用sys.stdout.write()两次,我添加条件来检查此输出是否为空。

def normalOutputWritten(text):
    """Append text to the QTextEdit."""       
    timestamp = '{}> '.format(time.strftime('%X'))    

   if len(text)>1:
        text = timestamp+text

   gui_cmd_bw.insertPlainText(text) 

这将删除第二个时间戳。当然,一个符号输出中将缺少时间戳。

© www.soinside.com 2019 - 2024. All rights reserved.