Skip to content

Instantly share code, notes, and snippets.

@sixtenbe
Created September 1, 2011 08:43
Show Gist options
  • Save sixtenbe/1185733 to your computer and use it in GitHub Desktop.
Save sixtenbe/1185733 to your computer and use it in GitHub Desktop.
WXpython excepthook
import wx
import sys
import traceback
class Mainframe(wx.Frame):
def __init__(self, parent, id = wx.ID_DEFAULT, title = "The title", **kwargs):
sys.excepthook = self.excepthook
super(Mainframe, self).__init__(parent, id, title, *args, **kwargs)
#wx graphics code here
self.Fit()
self.GetBestSize()
self.Show(True)
def excepthook(self, etype, value, tb):
"""
This excepthook, when bound will catch all unhadled exceptions logging
them to file and also creating a wx MessageDialog to notify the user of
the error.
"""
message = '\nUncaught exception:\n'
message += ''.join(traceback.format_exception(etype, value, tb))
with open('error.log', 'a') as log:
log.write(message)
d = wx.MessageDialog(self, "{0!s}: {1!s}".format(etype.__name__, value)
, "Unhandled exception", wx.OK | wx.ICON_ERROR)
d.ShowModal()
d.Destroy()
def installThreadExcepthook():
"""
Workaround for sys.excepthook thread bug
From
http://spyced.blogspot.com/2007/06/workaround-for-sysexcepthook-bug.html
(https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1230540&group_id=5470).
Call once from __main__ before creating any threads.
If using psyco, call psyco.cannotcompile(threading.Thread.run)
since this replaces a new-style class method.
"""
init_old = threading.Thread.__init__
def init(self, *args, **kwargs):
init_old(self, *args, **kwargs)
run_old = self.run
def run_with_except_hook(*args, **kw):
try:
run_old(*args, **kw)
except (KeyboardInterrupt, SystemExit):
raise
except:
sys.excepthook(*sys.exc_info())
self.run = run_with_except_hook
threading.Thread.__init__ = init
if __name__ == "__main__":
installThreadExcepthook()
app = wx.App(False)
frame = Mainframe(None)
app.MainLoop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment