[PyQt] IORedirection

Source : IORedirection.zip

在PyQt程式撰寫過程中,我習慣使用terminal去執行來觀察一些debug訊息,而在一些程式設計的需求下,有時候我們必須將標準輸入資訊給導向至圖形介面輸出,這時候就必須將I/O給重新導向,在python裡要將standard output/error給導向至Qt的textEdit方法如下:

class OutLog:
    def __init__(self, edit, color=None):
        self.edit = edit
        self.color = color
        
    def write(self, msg):
        if self.color:
            tc = self.edit.textColor()
            self.edit.setTextColor(self.color)
            
        self.edit.insertPlainText(msg)
        
        if self.color:
            self.edit.setTextColor(tc)
            
            
class IOReDirectionClass(QtGui.QWidget):
    def __init__(self, parent = None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_IOReDirectionClass.Ui_IOReDirectionClass()
        self.ui.setupUi(self)
        
        sys.stdout = OutLog( self.ui.textEdit_output)
        sys.stderr = OutLog( self.ui.textEdit_output, QtGui.QColor(0,0,255))
        
        
    def onRedirectClicked(self):
        print "Standard Output"
        print >> sys.stderr, "Standard Error"
        print "\nYour python environment path:"
        for path in sys.path:
            print path
            
    def systemOutput(self):
        self.ui.textEdit_output.setText(sys.stdout)

簡單來說就是重寫stdout和stderr的write()函式,將stdout/stderr的message傳送到QtGui.QTextEdit裡顯示。這樣的技巧可以應用在一些網路程式顯示連線資訊的部份。

No comments:

Post a Comment

Orange - data analysis tool

Installation pip install orange3 Run orange python -m Orange.canvas