Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python traceback, show line where error occurred even if not showing complete traceback

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()
like image 612
user984003 Avatar asked Oct 04 '22 04:10

user984003


2 Answers

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.

like image 119
Pavel Anossov Avatar answered Oct 21 '22 05:10

Pavel Anossov


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]
like image 21
Aseem Avatar answered Oct 21 '22 05:10

Aseem