繁体   English   中英

如何在函数中获取python异常回溯

[英]How to get python exception traceback in function

我有一个应该处理所有错误的函数:

def err(e):
    import traceback
    message = traceback.print_exc()
    print(message)

if __name__ == "__main__":
    try:
        1/0 # just sample
    except Exception as e:
        err(e)

但它会返回一个简短的错误,如下所示:

integer division or modulo by zero

但是我需要更多详细信息( traceback )来检查错误。

你传递的例外,你的功能,所以为什么要使用traceback ,你有e那里。 如果需要回溯,只需抓住e.__traceback__ traceback__:

import traceback

def err(e):   
    tb = e.__traceback__
    # print traceback
    traceback.print_tb(tb)

对于不依赖dunder的选项,可以使用sys.exc_info并保留回溯:

import traceback, sys

def err(e):
    *_, tb = sys.exc_info()    
    # print traceback
    traceback.print_tb(tb)

根据python文档:

traceback.print_exc([limit [,file]])

 This is a shorthand for print_exception(sys.exc_type, sys.exc_value, sys.exc_traceback, limit, file). (In fact, it uses 

sys.exc_info()以线程安全的方式而不是使用不推荐使用的变量来检索相同的信息。)

您实际上所做的只是打印出1/0产生的错误消息

如果要打印出个性化的错误消息,可以执行以下操作:

if __name__ == "__main__":
    try:
        1/0 # just sample
    except Exception as e:
        print 'This is the error I am expecting'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM