0
点赞
收藏
分享

微信扫一扫

在Python中,您可以使用`traceback`模块来获取traceback的内容。以下是一些方法: 1. 使用`traceback.format_exc()`¹: ```python impor

杰森wang 2024-01-16 阅读 25

在Python中,您可以使用`traceback`模块来获取traceback的内容。以下是一些方法:


1. 使用`traceback.format_exc()`¹:

```python

import traceback


try:

   1/0

except Exception:

   print(traceback.format_exc())

```

这将打印出完整的traceback。


2. 使用`sys.exc_info()`¹:

```python

import sys

import traceback


try:

   1/0

except Exception:

   print(sys.exc_info()[2])

```

这将打印出traceback对象。


3. 如果您只有异常对象,您可以使用`traceback.format_exception()`来获取traceback¹:

```python

import traceback


try:

   1/0

except Exception as e:

   print(''.join(traceback.format_exception(None, e, e.__traceback__)))

```

这将打印出与`traceback.format_exc()`相同的输出。


以上是一些获取traceback内容的方法,希望对您有所帮助!


源: 与必应的对话, 2024/1/16

(1) Catch and print full Python exception traceback without halting/exiting the program - Stack Overflow. https://stackoverflow.com/questions/3702675/catch-and-print-full-python-exception-traceback-without-halting-exiting-the-prog.

(2) traceback — Print or retrieve a stack traceback - Python. https://docs.python.org/3/library/traceback.html.

(3) python - What is the best way to get the traceback object for an exception? - Stack Overflow. https://stackoverflow.com/questions/76629564/what-is-the-best-way-to-get-the-traceback-object-for-an-exception.

(4) Tracing the Untraceable with Python Tracer - Python Pool. https://www.pythonpool.com/python-tracer/.

举报

相关推荐

0 条评论