Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display source code causing an exception in Python

How to retrieve the line of code (not the line number) that causes an exception?

This is an attempt.

import sys, inspect
try:
    1 / 0
except Exception as e:
    exc_type, exc_obj, exc_tb = sys.exc_info()
    code = str(inspect.getsourcelines(exc_tb.tb_frame.f_code))        

print(code)

It returns the first line of the script, not the line that causes the exception.

(['import sys, inspect\n'], 1)
like image 525
xagg Avatar asked Sep 16 '25 10:09

xagg


1 Answers

Below codes works, but it is inflexible. Someone else may have better solution.

import sys, inspect
try:
    y = 2
    a = 1 / 0
except Exception as e:
    exception_occr_at_file = inspect.trace()[0][1]
    line_no = inspect.trace()[0][2]
    code = inspect.trace()[0][4]

print(exception_occr_at_file)
print(line_no)
print(code)

#Ouput:
C:\Users\jianc\Desktop\test\test_print.py
4
['    a = 1 / 0\n']
like image 192
Sphinx Avatar answered Sep 18 '25 01:09

Sphinx