0

I'm trying to redirect the sys.stdout stream to a wx.TextCtrl widget. I've managed to get the stream to redirect but apparently some messages get writted twice. Hopefully somebody can explain this to me.

I'm using python 2.7.5 with wx 2.8.12.1, running from IPython 1.1.0.

import sys
import wx


class Example(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, 1, title='Example', size=(500, 500))

        console = Console(self)
        sys.stdout = console

    # Restore default stdout stream
    def __del__(self):
        Destroy()

    def Destroy(self):
        sys.stdout = sys.__stdout__


class Console(wx.TextCtrl):
    def __init__(self, parent):
        self.txtctrl = wx.TextCtrl(parent, style=wx.TE_MULTILINE | wx.TE_AUTO_SCROLL | wx.TE_RICH2)

    def write(self, message):        
        self.txtctrl.AppendText('>>> ')
        self.txtctrl.AppendText(message)


def main():
    app = wx.App()

    frame = Example()
    frame.Center()
    frame.Show()

    app.MainLoop()

if __name__ == '__main__':
    main()
tdelaney
  • 73,364
  • 6
  • 83
  • 116
JustMe
  • 237
  • 4
  • 7
  • This shouldn't be happening. Are you sure that the lines aren't written twice without output redirection? – tjohnson Mar 14 '16 at 18:46
  • that's what I thought too but when I run "print('This is a test')" the TextCtrl will display ">>> This is a test>>> " – JustMe Mar 14 '16 at 21:23
  • Try adding to the beginning of your `write` function: `if not len(message): return` – tjohnson Mar 14 '16 at 22:14
  • perfect, got it sorted now. It seems to be a separate newline character, which I filtered out using `if message == '\n'`. Thanks for the tip! – JustMe Mar 14 '16 at 22:59
  • Be aware that wx.Frame inherits "Destroy()" from wx.Window. Your subclass "Example()" which sub-classes wx.Frame overrides the inherited "Destroy()" method. – DevPlayer May 25 '17 at 20:15

0 Answers0