python exception打印堆栈
时间: 2023-08-31 22:12:31 浏览: 70
在 Python 中,可以使用 `traceback` 模块打印异常的堆栈信息。
以下是一个示例代码:
```python
import traceback
try:
# some code that may raise an exception
raise Exception('This is an exception')
except Exception as e:
# print the exception and its stack trace
traceback.print_exc()
```
在上面的代码中,`try` 块中的某些代码可能会引发异常。如果发生异常,程序将跳转到 `except` 块,并将异常对象传递给 `e` 变量。
`traceback.print_exc()` 方法将打印异常和其堆栈跟踪。如果想要将堆栈跟踪写入日志文件,可以使用 `traceback.format_exc()` 方法,该方法返回一个字符串表示堆栈跟踪。例如:
```python
import traceback
try:
# some code that may raise an exception
raise Exception('This is an exception')
except Exception as e:
# write the exception and its stack trace to a log file
with open('error.log', 'w') as f:
f.write(traceback.format_exc())
```