我希望File1.py
返回File2.py
中的错误行
File1.py:
def find_errors(file_path_of_File2):
print(f'the error is on line {}')
错误在第2行
File2.py:
print('this is line 1')
print(5/0)
ZeroDivisionError:整数除法或以零为模
这可能吗?
答案 0 :(得分:3)
您可以使用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]))
输出
this is line 1
Exception <type 'exceptions.ZeroDivisionError'> is on line 2
在这种情况下,您将捕获导入文件时引发的所有异常,然后从trace_back
中获取最后一个异常。