从异常对象中提取完整跟踪



我遵循这个答案并实现了以下内容:

def B():
try:
raise Exception()
except Exception as e:
traceback_ob = e.__traceback__
import traceback
traceback_str = ''.join(traceback.format_exception(etype=type(e), value=e, tb=traceback_ob))
print(traceback_str)
def A():
B()
A()

输出为:

Traceback (most recent call last):
File "/path/bespoke_traceback.py", line 3, in B
raise Exception()
Exception

我需要有完整的跟踪,所以在字符串中包括A-我如何实现这一点?

具体地说,我需要这个字符串,而不仅仅是打印出来的。

您可以将format_exception函数与format_stack组合以获得以前的帧:

import traceback
def B():
try:
raise Exception("error")
except Exception as e:
exception = traceback.format_exception(type(e), value=e, tb=e.__traceback__)
stack = traceback.format_stack()
# exception already holds the last (current) frame - we just want to add the previous frames
exception[1:1] = stack[:-1]
traceback_str = ''.join(exception)
print(traceback_str)
def A():
B()
A()

将给出:

Traceback (most recent call last):
File "test.py", line 19, in <module>
A()
File "test.py", line 17, in A
B()
File "test.py", line 5, in B
raise Exception("error")
Exception: error

我个人的方法:(很抱歉使用了一个文件,但这似乎是唯一的解决方案(抱歉,如果有点复杂

from threading import Thread
import sys
import os
def B():
raise Exception()

def A():
B()
def catch_error(f):
# redirect stderr (where errors are printed) to a temporary file
# tried StringIO but it only showed part of the exception
sys.stderr = open('temp', 'w')
# run it in a thread so that the script doesn't stop after the error
t = Thread(target=A) 
t.start()
t.join()
# close the file and return stderr back to normal
sys.stderr.close()
sys.stderr = sys.__stderr__
# get error string from the file and then delete it
s = open('temp', 'r').read()
os.remove('temp')
# remove some lines concerning the threading module
lines = s.split('n')
[lines.pop(2) for i in range(4)]
lines.pop(0)
# join the lines and return
return 'n'.join(lines)
print(catch_error(A))

输出:

Traceback (most recent call last):
File "C:UserslenovoAminWorkspacetest.py", line 9, in A
B()
File "C:UserslenovoAminWorkspacetest.py", line 6, in B
raise Exception()
Exception

只需使用日志记录模块就可以实现回溯,而不需要其他模块:

对于同一个文件,异常回溯将来自immediate类。如果是从不同文件调用,logger.exception将打印整个回溯

检查以下示例:

import logging
logger = logging.getLogger(__name__)
def B():
try:
raise Exception()
except Exception as e:
logger.exception("Error",stack_info=True)
def A():
B()
A()

最新更新