使用 traceback 库
import traceback
try:
pass #要捕获异常的代码块
except Exception as a:
print(a)
traceback.print_exc()
或者使用 cgitb
def func(a, b):
return a / b
if __name__ == '__main__':
import cgitb
cgitb.enable(format='text')
import sys
import traceback
func(1, 0)
运行之后就会得到详细的数据:
A problem occurred in a Python script. Here is the sequence of
function calls leading up to the error, in the order they occurred.
/Users/samchi/Documents/workspace/tracebacktest/teststacktrace.py in <module>()
4 import cgitb
5 cgitb.enable(format='text')
6 import sys
7 import traceback
8 func(1, 0)
func = <function func>
/Users/samchi/Documents/workspace/tracebacktest/teststacktrace.py in func(a=1, b=0)
2 return a / b
3 if __name__ == '__main__':
4 import cgitb
5 cgitb.enable(format='text')
6 import sys
a = 1
b = 0
traceback 和 cgitb 详解 请参考 https://blog.csdn.net/lengxingxing_/article/details/56317838