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

时间:2018-04-11 05:00:43

标签: python pyqt stdout pyqtgraph

我试图在我的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> 

1 个答案:

答案 0 :(得分: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) 

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