如何在 Python 中格式化回溯对象

发布于 2024-08-04 01:33:27 字数 96 浏览 7 评论 0原文

我有一个回溯对象,我想以调用 traceback.format_exc() 时获得的良好格式显示它。

有为此的内置函数吗?或者几行代码?

I have a traceback object that I want to show in the nice format I get when calling traceback.format_exc().

Is there a builtin function for this? Or a few lines of code?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

友谊不毕业 2024-08-11 01:33:27

format_exc() 实际上就是

etype, value, tb = sys.exc_info()
return ''.join(format_exception(etype, value, tb, limit))

这样,如果您准备好异常类型、值和回溯,那么这应该很容易。如果您只有例外,请注意 format_exception() 本质上是:

a_list = ['Traceback (most recent call last):\n']
a_list = a_list + format_tb(tb, limit)

其中 limit 默认为 None

format_exc() is really just

etype, value, tb = sys.exc_info()
return ''.join(format_exception(etype, value, tb, limit))

So if you have the exception type, value, and traceback ready, it should be easy. If you have just the exception, notice that format_exception() is essentially:

a_list = ['Traceback (most recent call last):\n']
a_list = a_list + format_tb(tb, limit)

where limit defaults to None.

却一份温柔 2024-08-11 01:33:27

在任何地方都找不到这个,所以我将其发布在这里,供未来的人和我未来的自己。

try:
  raise Exception('Not an Exception')
except Exception as err:
  msg = "".join(traceback.format_exception(type(err), err, err.__traceback__))
  print(msg)

这会获取您的异常并提供一个与 python 的默认异常 print/print_tb 格式相同的字符串

Couldn't find this anywhere, so I'm posting it here for future people and my future self.

try:
  raise Exception('Not an Exception')
except Exception as err:
  msg = "".join(traceback.format_exception(type(err), err, err.__traceback__))
  print(msg)

This takes your exception and provides a string formatted identically to python's default exception printer/print_tb

雨落星ぅ辰 2024-08-11 01:33:27

traceback 文档给出了一些示例和< a href="http://docs.python.org/library/traceback.html" rel="nofollow noreferrer">用于格式化回溯对象的整套函数。

traceback docs give few examples and whole set of functions for formatting traceback objects.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文