python – 在excepthook中打印原始异常
发布时间:2020-12-20 11:41:07 所属栏目:Python 来源:网络整理
导读:我正在设置sys.excepthook,以便我可以记录发生的每个异常.不要写入日志,而是使用以下示例: def excepthook(self,type_,value,traceback): print "n" print type_ print value print traceback print "n"sys.excepthook = self.excepthook 现在假设我创建
我正在设置sys.excepthook,以便我可以记录发生的每个异常.不要写入日志,而是使用以下示例:
def excepthook(self,type_,value,traceback): print "n" print type_ print value print traceback print "n" sys.excepthook = self.excepthook 现在假设我创建了一个类型错误,如下所示: print 3 + str(2) 没有被抓住,这进入了异常情况并正确打印出3个变量: <type 'exceptions.TypeError'> unsupported operand type(s) for + <traceback object at 0x02BAE800> 我想做的是,它还打印出发送到excepthook的完整异常(因此,在这种情况下,是一个TypeException).换句话说,我希望它也显示以下信息). Traceback (most recent call last): File "testcidnelite.py",line 13,in <module> print 3 + str(2) TypeError: unsupported operand type(s) for +: 'int' and 'str' 如果我添加以下行: raise 它会正确显示异常;但是,它也会在术语“加速”时显示错误: Error in sys.excepthook: Traceback (most recent call last): File "C:psi-test-automationSeleniumTestMethods2.py",line 145,in excepthook raise TypeError: exceptions must be old-style classes or derived from BaseException,not NoneType 改为: raise type_ 将打印出以下错误: Error in sys.excepthook: Traceback (most recent call last): File "C:psi-test-automationSeleniumTestMethods2.py",in excepthook raise type_ TypeError Original exception was: Traceback (most recent call last): File "testcidnelite.py",in <module> print 3 + str(2) TypeError: unsupported operand type(s) for +: 'int' and 'str' 我希望它只打印出第二个块(原始异常).这可能吗? 解决方法
您可以使用Python的traceback模块来格式化异常.
from traceback import format_exception def excepthook(self,traceback): print format_exception(type_,traceback) sys.excepthook = self.excepthook 查看官方documentation以获取更多信息和示例. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |