So I want to pop up a modal dialog on error.
Tried setting sys.stderr to an object with a
write method that pops up a dialog. The problem
with that is write() gets called several times
per exception - I don't see how to get my new
sys.stderr object to figure out when it's time
to show the message.
So then I found sys.excepthook. The problem with
that was that I was too stoopid to figure out how
to get a readable error message from the parameters
passed to excepthook.
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
--
David C. Ullrich
Hi David,
Take a look at the traceback module. The excepthook gets called with
an exception type, instance, and traceback object. The traceback module
is good at turning these things into strings.
Jean-Paul
Thanks.
> Jean-Paul
--
David C. Ullrich
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 <ni...@craig-wood.com> -- http://www.craig-wood.com/nick