Skip to main content
 首页 » 编程设计

python之如何获取python异常发生的实际行号

2025年05月04日15tuyile006

我的文件 decorators.py

中有以下 python 装饰器
def catch_exceptions(function):                                           #Line #1 
    @wraps(function)                                                      #Line #2 
    def decorator(*args, **kwargs):                                       #Line #3 
        try:                                                              #Line #4 
            return function(*args, **kwargs)                              #Line #5 
        except Exception as e:                                            #Line #6 
            exc_type, exc_obj, exc_tb = sys.exc_info()                    #Line #7 
            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]  #Line #8 
            print "E=%s, F=%s, L=%s" % (str(e), fname, exc_tb.tb_lineno)  #Line #9 
    return decorator                                                      #Line #10 

在另一个文件 my_file.py 中,我像这样使用 catch_exceptions 装饰器:

from decorators import catch_exceptions                                   #Line #1 
@catch_exceptions                                                         #Line #2 
def my_method()                                                           #Line #3 
    print (10/0 - 5/0)                                                    #Line #4 

当我运行它时,我得到以下输出:

E=integer division or modulo by zero, F=decorators.py, L=5 

与其将异常位置报告为 decorators.py,第 5 行,我如何让它报告异常最初发生位置的实际文件和行号?那将是 my_file.py 中的第 4 行。

请您参考如下方法:

您可能需要查看traceback 模块

import traceback 
 
try: 
    function_that_raises_exception() 
except Exception: 
    traceback.print_exc() 

它将打印整个堆栈跟踪。