Python 从异常对象提取完整跟踪
我遵循并实施了以下措施:Python 从异常对象提取完整跟踪,python,Python,我遵循并实施了以下措施: 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))
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
我需要有完整的跟踪,所以在字符串中包含一个-我如何才能做到这一点
具体地说,我需要一个字符串,而不只是打印出来。您只需使用日志模块即可实现回溯,无需其他模块: 对于同一文件,异常回溯将来自立即类。如果是从不同的文件调用,
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()
我个人的做法:(很抱歉使用文件,但它似乎是唯一的解决方案)
抱歉,如果有点复杂的话
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:\Users\lenovo\Amin\Workspace\test.py", line 9, in A
B()
File "C:\Users\lenovo\Amin\Workspace\test.py", line 6, in B
raise Exception()
Exception
您可以将函数与结合起来以获得前面的帧:
导入回溯
def B():
尝试:
引发异常(“错误”)
例外情况除外,如e:
异常=回溯。格式\u异常(etype=type(e),value=e,tb=e.。\uuuu回溯\uuuuu)
stack=回溯。格式\u stack()
#异常已保存最后一个(当前)帧-我们只想添加以前的帧
异常[1:1]=堆栈[:-1]
回溯_str=''.join(异常)
打印(回溯)
定义A():
B()
()
将提供:
回溯(最近一次呼叫最后一次):
文件“test.py”,第16行,在
()
文件“test.py”,第14行,在
B()
文件“test.py”,B中第5行
引发异常(“错误”)
例外:错误
尝试在A()
通话中添加trackback。这是否回答了您的问题?这给出了与问题中完全相同的输出…@Tomerikoo addstack\u info=True
在异常调用中。检查更新的答案我已经编辑了这个问题-我需要它的字符串,而不仅仅是打印出来的-我可以从记录器中获取吗?同样可以通过回溯来实现。print_stack()
,不需要日志记录
,但它不是预期的输出…效果非常好