Reputation: 359
I want File1.py
to return the error line in File2.py
File1.py:
def find_errors(file_path_of_File2):
print(f'the error is on line {}')
the error is on line 2
File2.py:
print('this is line 1')
print(5/0)
ZeroDivisionError: integer division or modulo by zero
Is this possible?
Upvotes: 2
Views: 135
Reputation: 6960
You can do it a little bit ugly with the traceback
module.
File1.py
print('this is line 1')
print(5/0)
File2.py
import sys
import traceback
try:
import test
except Exception as e:
(exc_type, exc_value, exc_traceback) = sys.exc_info()
trace_back = [traceback.extract_tb(sys.exc_info()[2])[-1]][0]
print("Exception {} is on line {}".format(exc_type, trace_back[1]))
output
this is line 1
Exception <type 'exceptions.ZeroDivisionError'> is on line 2
In this case, you will catch all exceptions raised during importing your file, then you will take the last one from the trace_back
.
Upvotes: 3