5

I am trying to debug python code, I want to pin point the line number in which error occurs. As per the posts found asked here the code gives the line no of the function being called. eg

    if __name__ == '__main__':
        try:
            foo()
        except:
            <the code to print line no when error occurs>

But it gives me the line no of foo(), Please help to find the exact line no in which error occurs.

Thanks,

Community
  • 1
  • 1
someone
  • 104
  • 2
  • 10

1 Answers1

5

You have to use the third return value of sys.exc_info() they call exc_tb in your example. Instead of using exc_tb.tb_lineno, you can browse the traceback object using traceback.extract_tb(exc_tb). The repr look like :

*** extract_tb:
[('<doctest...>', 10, '<module>', 'lumberjack()'),
 ('<doctest...>', 4, 'lumberjack', 'bright_side_of_death()'),
 ('<doctest...>', 7, 'bright_side_of_death', 'return tuple()[0]')]

I suppose the line you are looking for is the last line of the structure. I haven't tested but this should do :

import sys, os, traceback

try:
    raise NotImplementedError("No error")
except Exception as e:
    exc_type, exc_obj, exc_tb = sys.exc_info()
    tb = traceback.extract_tb(exc_tb)[-1]
    print(exc_type, tb[2], tb[1])
Diane M
  • 1,503
  • 1
  • 12
  • 23