【问题标题】:Python traceback Exception stack serialize as dictionary or list [closed]Python回溯异常堆栈序列化为字典或列表[关闭]
【发布时间】:2021-05-02 13:24:55
【问题描述】:

如何获取异常堆栈traceback.format_exc() 作为列表/字典,然后使用 json.dumps() 对其进行序列化?

【问题讨论】:

  • 您能补充更多细节吗?目前还不清楚(至少对我而言)你在追求什么。
  • @CristiFati 我想将整个堆栈编码为 JSON。
  • 是的,但是怎么做?你有例子吗?
  • @CristiFati 不,无法找到将其作为字典或列表获取的方法...
  • 这将返回一个列表,traceback.format_exception(*sys.exc_info())

标签: python python-3.x traceback


【解决方案1】:

上市[Python.Docs]: traceback - Print or retrieve a stack traceback

如果我的理解是正确的,那么你就是这样的:

>>> import os, traceback
>>>
>>> try: os.open()
... except: tb = traceback.format_exc()
... else: tb = None
...
>>> print(type(tb), tb)
<class 'str'> Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: open() missing required argument 'path' (pos 1)

>>> [i for i in x.split("\n") if i]
['Traceback (most recent call last):', '  File "<stdin>", line 2, in <module>', "NameError: name 'os' is not defined"]

一旦您有了异常回溯字符串,您现在可以按照您希望的任何方式对其进行操作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-30
    • 2010-11-04
    • 1970-01-01
    • 2016-03-15
    • 2015-07-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多