【发布时间】:2021-07-26 21:39:49
【问题描述】:
我正在尝试通过''.join(traceback.format_stack()) 格式化和获取来自 sys.exc_info 的信息,但没有运气,关于如何将 sys.esc_info 中的所有信息转换为字符串的任何建议。我最终需要将所有这些信息写入一个表中。
【问题讨论】:
标签: python logging error-handling
我正在尝试通过''.join(traceback.format_stack()) 格式化和获取来自 sys.exc_info 的信息,但没有运气,关于如何将 sys.esc_info 中的所有信息转换为字符串的任何建议。我最终需要将所有这些信息写入一个表中。
【问题讨论】:
标签: python logging error-handling
使用sys.exc_info() 获取异常三元组。要从跟踪中获取字符串,请使用traceback.format_tb()。
#!/usr/bin/env python
import sys
import traceback
try:
raise RuntimeError("This is an error")
except:
exception_type, exception_value, trace = sys.exc_info()
print(f"Exception type: {exception_type}") # <class 'RuntimeError'>
print(f"Exception value: {exception_value}") # This is an error
trace_string = "".join(traceback.format_tb(trace))
print(f"Stack trace:\n{trace_string}")
# File "/home/pierre/stackoverflow.py", line 5, in <module>
# raise RuntimeError("This is an error")
【讨论】: