Python logging module used in GUI - chicken and egg problem during start-up sequence

Frank Aune Frank.Aune at broadpark.no
Tue Oct 16 16:17:35 PDT 2007


Hello,

Ive got a wx app which has a log widget, and when creating the frame, I 
redirecting stdout to this widget using the python logging module. I cannot 
redirect messages to this widget before the frame is created, and effectively 
I cannot log messages appearing during the start-up sequence.

To me this seems like a classical chicken and egg problem, and I'm looking for 
comments, suggestions and improvements to the following solution:

class OutputWindowStream(logging.Handler):
    def __init__(self):
        logging.Handler.__init__(self)
        self.textbox = None
        self.buffer = []
 
    def setTextBox(self, textbox):
        """
        textbox presents the instance of textctrl in the mainframe
        Method is called after frame is up and running
        """
        self.textbox = textbox

    def shouldFlush(self):
        if self.textbox:
            return True
        else:
            return False
    
    def emit(self, record):
        self.buffer.append(record)
        if self.shouldFlush():
            self.flush()

    def flush(self):
        """
        Thread safe flush method which schedule the
        textbox update after a wx main loop ends
        """
        for record in self.buffer:
            msg = self.format(record)
            wx.CallAfter(self.textbox.AppendText, msg+'\n')
        self.buffer = []

    def close(self):
        self.flush()
        self.textbox = None
        logging.Handler.close(self)
    




More information about the wxpython-users mailing list