Python traceback 异常堆栈序列化为字典或列表

Python traceback Exception stack serialize as dictionary or list

如何获取异常堆栈 traceback.format_exc() 作为 List/Dictionary 以便随后使用 json.dumps() 对其进行序列化?

清单[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"]

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