Skip to content

Instantly share code, notes, and snippets.

@chobits
Created April 12, 2012 07:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save chobits/2365451 to your computer and use it in GitHub Desktop.
Save chobits/2365451 to your computer and use it in GitHub Desktop.
python: hook exception handler
import sys
def my_excepthook(exc_type, exc_value, tb):
print 'My Excepthook:'
# traceback display: see tb_printinternal from cpython source
print ' Traceback (most recent call last):'
while tb:
filename = tb.tb_frame.f_code.co_filename
name = tb.tb_frame.f_code.co_name
lineno = tb.tb_lineno
print ' File "%.500s", line %d, in %.500s' %(filename, lineno, name)
tb = tb.tb_next
# Exception type and value
print ' %s: %s' %(exc_type.__name__, exc_value)
def divide_zero():
1 / 0 # raise ZeroDivisionError
def f():
divide_zero()
if __name__ == '__main__':
sys.excepthook = my_excepthook
f()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment