How do you send Stdout to a TextCtrl? The wxWindows docs alludes to how to do it in C++, but it doesn't say anything on how to do it in wxPython. And, really, it's easier than it should be.

Really, there are three steps:

  1. Create a TextCtrl.

  2. Set sys.stdout equal to the TextCtrl. Now your output will go to the TextCtrl.

  3. When you are done with the window, set sys.stdout back (the wiki syntax seems to make it impossible to write double underscores outside of code blocks, see the end of the code below for how to set sys.stdout back).

This is handy in Windows, when you have no idea where Stdout goes.

Changing where sys.stderr is pretty much the same thing.

Here is some simple example code.

   1 import wx
   2 import sys, time
   4 class LogWindow(wx.TextCtrl):
   5     def __init__ (self):
   6         frame = wx.Frame(None,-1, "Standard out", size=(200,200))
   7         frame.Show(True)
   9         self.parent = frame
  11         wx.TextCtrl.__init__(self,self.parent,size=self.parent.GetClientSize(), style=wx.TE_MULTILINE|wx.TE_READONLY|wx.HSCROLL)
  13         sys.stdout = self
  15         print "this is in Stdout!!!!"
  16         for i in range(10):
  17             print i
  18             wx.Yield()
  19             time.sleep(1)
  21         print "All done!"
  23 class MainApp(wx.App):
  24     def OnInit(self):
  25         log = LogWindow()
  26         log.parent.Show(True)
  27         self.SetTopWindow(log.parent)
  28         return True
  30 if __name__ == '__main__':
  31     app = MainApp(0)
  32     app.MainLoop()
  33     sys.stdout = sys.__stdout__

One issue with the above approach is that the user may encounter an exception if a secondary thread attempts to print.

StdouttoTextCtrl (last edited 2008-03-11 10:50:29 by localhost)

NOTE: To edit pages in this wiki you must be a member of the TrustedEditorsGroup.