如何将捕获的异常(其描述和堆栈跟踪)转换为外部使用的str ?
try:
method_that_can_raise_an_exception(params)
except Exception as e:
print(complete_exception_description(e))
如何将捕获的异常(其描述和堆栈跟踪)转换为外部使用的str ?
try:
method_that_can_raise_an_exception(params)
except Exception as e:
print(complete_exception_description(e))
当前回答
如果您希望在未处理异常时获得相同的信息,可以这样做。执行import trace,然后:
try:
...
except Exception as e:
print(traceback.print_tb(e.__traceback__))
我使用的是Python 3.7。
其他回答
您也可以考虑使用内置的Python模块cgitb,以获得一些非常好的、格式化良好的异常信息,包括局部变量值、源代码上下文、函数参数等。
例如这段代码…
import cgitb
cgitb.enable(format='text')
def func2(a, divisor):
return a / divisor
def func1(a, b):
c = b - 5
return func2(a, c)
func1(1, 5)
我们得到这个异常输出…
ZeroDivisionError
Python 3.4.2: C:\tools\python\python.exe
Tue Sep 22 15:29:33 2015
A problem occurred in a Python script. Here is the sequence of
function calls leading up to the error, in the order they occurred.
c:\TEMP\cgittest2.py in <module>()
7 def func1(a, b):
8 c = b - 5
9 return func2(a, c)
10
11 func1(1, 5)
func1 = <function func1>
c:\TEMP\cgittest2.py in func1(a=1, b=5)
7 def func1(a, b):
8 c = b - 5
9 return func2(a, c)
10
11 func1(1, 5)
global func2 = <function func2>
a = 1
c = 0
c:\TEMP\cgittest2.py in func2(a=1, divisor=0)
3
4 def func2(a, divisor):
5 return a / divisor
6
7 def func1(a, b):
a = 1
divisor = 0
ZeroDivisionError: division by zero
__cause__ = None
__class__ = <class 'ZeroDivisionError'>
__context__ = None
__delattr__ = <method-wrapper '__delattr__' of ZeroDivisionError object>
__dict__ = {}
__dir__ = <built-in method __dir__ of ZeroDivisionError object>
__doc__ = 'Second argument to a division or modulo operation was zero.'
__eq__ = <method-wrapper '__eq__' of ZeroDivisionError object>
__format__ = <built-in method __format__ of ZeroDivisionError object>
__ge__ = <method-wrapper '__ge__' of ZeroDivisionError object>
__getattribute__ = <method-wrapper '__getattribute__' of ZeroDivisionError object>
__gt__ = <method-wrapper '__gt__' of ZeroDivisionError object>
__hash__ = <method-wrapper '__hash__' of ZeroDivisionError object>
__init__ = <method-wrapper '__init__' of ZeroDivisionError object>
__le__ = <method-wrapper '__le__' of ZeroDivisionError object>
__lt__ = <method-wrapper '__lt__' of ZeroDivisionError object>
__ne__ = <method-wrapper '__ne__' of ZeroDivisionError object>
__new__ = <built-in method __new__ of type object>
__reduce__ = <built-in method __reduce__ of ZeroDivisionError object>
__reduce_ex__ = <built-in method __reduce_ex__ of ZeroDivisionError object>
__repr__ = <method-wrapper '__repr__' of ZeroDivisionError object>
__setattr__ = <method-wrapper '__setattr__' of ZeroDivisionError object>
__setstate__ = <built-in method __setstate__ of ZeroDivisionError object>
__sizeof__ = <built-in method __sizeof__ of ZeroDivisionError object>
__str__ = <method-wrapper '__str__' of ZeroDivisionError object>
__subclasshook__ = <built-in method __subclasshook__ of type object>
__suppress_context__ = False
__traceback__ = <traceback object>
args = ('division by zero',)
with_traceback = <built-in method with_traceback of ZeroDivisionError object>
The above is a description of an error in a Python program. Here is
the original traceback:
Traceback (most recent call last):
File "cgittest2.py", line 11, in <module>
func1(1, 5)
File "cgittest2.py", line 9, in func1
return func2(a, c)
File "cgittest2.py", line 5, in func2
return a / divisor
ZeroDivisionError: division by zero
我定义了以下helper类:
import traceback
class TracedExeptions(object):
def __init__(self):
pass
def __enter__(self):
pass
def __exit__(self, etype, value, tb):
if value :
if not hasattr(value, 'traceString'):
value.traceString = "\n".join(traceback.format_exception(etype, value, tb))
return False
return True
我以后可以这样使用:
with TracedExeptions():
#some-code-which-might-throw-any-exception
之后可以像这样消耗它:
def log_err(ex):
if hasattr(ex, 'traceString'):
print("ERROR:{}".format(ex.traceString));
else:
print("ERROR:{}".format(ex));
(背景:我很沮丧,因为使用承诺和异常一起,不幸的是将异常在一个地方引发到另一个地方的on_rejected处理程序,因此很难从原始位置获得回溯)
如果你的目标是让异常和stacktrace消息看起来与python抛出错误时完全一样,那么以下代码在python 2+3中都适用:
import sys, traceback
def format_stacktrace():
parts = ["Traceback (most recent call last):\n"]
parts.extend(traceback.format_stack(limit=25)[:-2])
parts.extend(traceback.format_exception(*sys.exc_info())[1:])
return "".join(parts)
# EXAMPLE BELOW...
def a():
b()
def b():
c()
def c():
d()
def d():
assert False, "Noooh don't do it."
print("THIS IS THE FORMATTED STRING")
print("============================\n")
try:
a()
except:
stacktrace = format_stacktrace()
print(stacktrace)
print("THIS IS HOW PYTHON DOES IT")
print("==========================\n")
a()
它的工作原理是从堆栈中删除最后一个format_stacktrace()调用,并加入其余的调用。当运行时,上面的示例给出以下输出:
THIS IS THE FORMATTED STRING
============================
Traceback (most recent call last):
File "test.py", line 31, in <module>
a()
File "test.py", line 12, in a
b()
File "test.py", line 16, in b
c()
File "test.py", line 20, in c
d()
File "test.py", line 24, in d
assert False, "Noooh don't do it."
AssertionError: Noooh don't do it.
THIS IS HOW PYTHON DOES IT
==========================
Traceback (most recent call last):
File "test.py", line 38, in <module>
a()
File "test.py", line 12, in a
b()
File "test.py", line 16, in b
c()
File "test.py", line 20, in c
d()
File "test.py", line 24, in d
assert False, "Noooh don't do it."
AssertionError: Noooh don't do it.
对于使用Python-3的用户
使用回溯模块和异常。__traceback__可以提取堆栈跟踪,如下所示:
使用traceback.extract_stack()获取当前堆栈跟踪 删除最后三个元素(因为它们是堆栈中的条目,使我找到了调试函数) 使用traceback.extract_tb()从异常对象中追加__traceback__ 使用traceback.format_list()格式化整个内容
import traceback
def exception_to_string(excp):
stack = traceback.extract_stack()[:-3] + traceback.extract_tb(excp.__traceback__) # add limit=??
pretty = traceback.format_list(stack)
return ''.join(pretty) + '\n {} {}'.format(excp.__class__,excp)
一个简单的演示:
def foo():
try:
something_invalid()
except Exception as e:
print(exception_to_string(e))
def bar():
return foo()
当我们调用bar()时,我们得到以下输出:
File "./test.py", line 57, in <module>
bar()
File "./test.py", line 55, in bar
return foo()
File "./test.py", line 50, in foo
something_invalid()
<class 'NameError'> name 'something_invalid' is not defined
如果你想将你的回溯转换为dict的列表(适用于python > 3.5):
from traceback import TracebackException
def list_traceback(exc_value: BaseException):
result = list()
# get previous fails, so errors are appended by order of execution
if exc_value.__context__:
result += list_traceback(exc_value.__context__)
# convert Exception into TracebackException
tbe = TracebackException.from_exception(exc_value)
# get stacktrace (cascade methods calls)
error_lines = list()
for frame_summary in tbe.stack:
summary_details = {
'filename': frame_summary.filename,
'method' : frame_summary.name,
'lineno' : frame_summary.lineno,
'code' : frame_summary.line
}
error_lines.append(summary_details)
# append error, by order of execution
result.append({"error_lines": error_lines,
"type" : tbe.exc_type.__name__,
"message" : str(tbe)})
return result
这将是结果(一个例子):
[
{
"error_lines": [
{
"filename": "/home/demo/file2.py",
"method": "do_error_2",
"lineno": 18,
"code": "a=1/0"
}
],
"type": "ZeroDivisionError",
"message": "division by zero"
},
{
"error_lines": [
{
"filename": "/home/demo/file_main.py",
"method": "demo2",
"lineno": 50,
"code": "file2.DEMO().do_error_2()"
},
{
"filename": "/home/demo/file2.py",
"method": "do_error_2",
"lineno": 20,
"code": "raise AssertionError(\"Raised inside the except, after division by zero\")"
}
],
"type": "AssertionError",
"message": "Raised inside the except, after division by zero"
}
]