Catch any exception and print or log traceback with variable values
Asked Answered
W

3

8

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.

Weaner answered 2/1, 2012 at 14:53 Comment(0)
I
9

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
Involuntary answered 2/1, 2012 at 15:1 Comment(0)
U
1

As the best practice you should avoid adding dubug info in your output or exceptions, there are tools to help you with that with a single line of code. Here's an example:

enter image description here

Have a look at some related packages. For simple usage you might pick traceback-with-variables (pip install traceback-with-variables), here is it's postcard

enter image description here

Or try tbvaccine, or better-exceptions, or any other package

Ultrastructure answered 30/10, 2020 at 8:28 Comment(1)
H
0

IPython has a built-in option to include variable values in Tracebacks.

Just run your script as follows:

ipython --InteractiveShell.xmode=Verbose script.py

You will get a full traceback, code context, and the values of relevant variables.

Heptode answered 11/11, 2022 at 2:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.