sys.excepthack...

Nick Craig-Wood nick at craig-wood.com
Thu May 15 04:30:03 EDT 2008


David C. Ullrich <dullrich at sprynet.com> wrote:
>  Becoming a fan of wxPython, but I can't stand
>  what it does with error messsages 
[snip]
>  So I want to pop up a modal dialog on error.
[snip]
>  Came up with a ridiculous hack involving both sys.stderr
>  and sys.excepthook. Works exactly the way I want.
>  Seems ridiculous - what's the right way to do this?
> 
>  Ridiculous_hack.py:
> 
>  import sys
>  import wx
> 
>  def hook(*args):
>    try:
>      sys.__excepthook__(*args)
>    finally:
>      printer.Show()
> 
>  class ErrorDisplay:
>    def __init__(self):
>      self.buffer = ''
>    def write(self, text):
>      self.buffer = self.buffer + text
> 
>    def Show(self): 
>        wx.MessageDialog(None, str(self.buffer), 
>                        'Error:',wx.OK).ShowModal()
>        self.buffer = ''
> 
>  printer = ErrorDisplay()
>  sys.stderr = printer
>  sys.excepthook = hook

Here is how I've done it in the past.  It is a complete runnable
example :-

------------------------------------------------------------
#!/usr/bin/python

import wx
import sys
from traceback import format_exception

class TestApp(wx.Frame):
    """Test error handling"""

    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, -1, title, size=(200,200))
        sys.excepthook = self.OnException
        button = wx.Button(self, wx.NewId(), "Produce Error")
        self.Bind(wx.EVT_BUTTON, self.OnClick)
        self.Show(True)

    def OnException(self, type, value, traceback):
        """
        Called on OnException
        """
        error_text = "".join(format_exception(type, value, traceback))
        wx.MessageDialog(None, error_text, 'Custom Error:', wx.OK).ShowModal()

    def OnClick(self, evt):
        "Click with a deliberate mistake"
        adsfsfsdf

if __name__ == "__main__":
    app = wx.PySimpleApp()
    frame = TestApp(None, -1, "Test")
    app.MainLoop()
------------------------------------------------------------

-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list