How can I make sure that I print out the actual line that failed without including the whole traceback? The traceback might be too long for me too print it all.
This code only prints the error in function a and b, but I want to see that the actual error occurred in function d.
import traceback
def a():
try:
return b();
except:
print traceback.format_exc(2)
def b():
return c();
def c():
return d();
def d():
x = 1/0
a()
You can do something like this:
import sys
import traceback
def a():
try:
return b();
except:
_, _, tb = sys.exc_info()
print traceback.format_list(traceback.extract_tb(tb)[-1:])[-1]
Or format the string yourself as you like:
import sys
import traceback
def a():
try:
return b();
except:
_, _, tb = sys.exc_info()
filename, lineno, funname, line = traceback.extract_tb(tb)[-1]
print '{}:{}, in {}\n {}'.format(filename, lineno, funname, line)
sys.exc_info()
This function returns a tuple of three values that give information about the exception that is currently being handled (...) If no exception is being handled anywhere on the stack, a tuple containing three None values is returned. Otherwise, the values returned are (type, value, traceback).
traceback.extract_tb(traceback[, limit])
Return a list of up to limit “pre-processed” stack trace entries extracted from the traceback object traceback. It is useful for alternate formatting of stack traces. If limit is omitted or None, all entries are extracted. A “pre-processed” stack trace entry is a quadruple (filename, line number, function name, text) representing the information that is usually printed for a stack trace. The text is a string with leading and trailing whitespace stripped; if the source is not available it is None.
traceback.format_list(list)
Given a list of tuples as returned by extract_tb() or extract_stack(), return a list of strings ready for printing. Each string in the resulting list corresponds to the item with the same index in the argument list. Each string ends in a newline; the strings may contain internal newlines as well, for those items whose source text line is not None.
import traceback
If you just want to just display the traceback:
print(traceback.format_exc())
If you want to extract values like function_name, line_number, error description etc from the traceback:
error_type, error, tb = sys.exc_info()
filename, lineno, func_name, line = traceback.extract_tb(tb)[-1]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With