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))
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(etype=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 16, in <module>
A()
File "test.py", line 14, in A
B()
File "test.py", line 5, in B
raise Exception("error")
Exception: error
推荐阅读
- python - 主题建模 LDA 的列表索引超出范围
- c# - 在 Visual Studio 中创建 C# 模板时,我的 using 指令被移出命名空间,导致我的标头出现问题
- azure-api-management - Azure API 管理 - 使用 Azure CLI 将标头和查询参数添加到 APIM 操作
- python - 我的 WaveNet 中的张量维数与 PyTorch cross_entropy 函数不兼容
- html - 在表格内分页的最佳方法
- java - 索引多维数组
- javascript - 如何从 React 应用程序外部触发 React 函数
- database - 使用 influxDB 中的其他两个查询过滤第一个查询的数据
- javascript - DOM Clobbering 及其工作原理
- sql - 相当于查询 django