我希望 File1.py
返回 File2.py
中的错误行
File1.py:
def find_errors(file_path_of_File2):
print(f'the error is on line {}')
the error is on line 2
文件2.py:
print('this is line 1')
print(5/0)
ZeroDivisionError: integer division or modulo by zero
这可能吗?
你可以用 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
中获取最后一个异常。
我是一名优秀的程序员,十分优秀!