pythontraceback

Catch any exception and print or log traceback with variable values


When I catch unexpected error with sys.excepthook:

import sys
import traceback

def handleException(excType, excValue, trace):
    print 'error'
    traceback.print_exception(excType, excValue, trace)

sys.excepthook = handleException

h = 1
k = 0

print h/k

This is the output I get:

error
Traceback (most recent call last):
   File "test.py", line 13, in <module>
      print h/k
ZeroDivisionError: integer division or modulo by zero

How can I include variable values (h, k, ...) in traceback similar to cgitb? When I include cgitb the result is the same.


Solution

  • By looking at the source of cgitb.py, you should be able to use something like this:

    import sys
    import traceback
    import cgitb
    
    def handleException(excType, excValue, trace):
        print 'error'
        cgitb.Hook(format="text")(excType, excValue, trace)
    
    sys.excepthook = handleException
    
    h = 1
    k = 0
    
    print h/k