Can I redirect the stdout in python into some sort of string buffer?

前端 未结 9 1549
野趣味
野趣味 2020-11-22 06:23

I\'m using python\'s ftplib to write a small FTP client, but some of the functions in the package don\'t return string output, but print to stdout.

9条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 06:55

    Just to add to Ned's answer above: you can use this to redirect output to any object that implements a write(str) method.

    This can be used to good effect to "catch" stdout output in a GUI application.

    Here's a silly example in PyQt:

    import sys
    from PyQt4 import QtGui
    
    class OutputWindow(QtGui.QPlainTextEdit):
        def write(self, txt):
            self.appendPlainText(str(txt))
    
    app = QtGui.QApplication(sys.argv)
    out = OutputWindow()
    sys.stdout=out
    out.show()
    print "hello world !"
    

提交回复
热议问题