import traceback
def fun(a,b):
    return a/b
try:
    fun(1,0)
except Exception as e:
    traceback.print_exc()
    #或者得到堆栈字符串信息
    info = traceback.format_exc()
    print(info)
    traceback.print_exc()

日志输出如下

:\python3.7.5\python.exe D:/code/flask_demo/bb.py
Traceback (most recent call last):
  File "D:/code/flask_demo/bb.py", line 5, in <module>
    fun(1,0)
  File "D:/code/flask_demo/bb.py", line 3, in fun
    return a/b
ZeroDivisionError: division by zero

Traceback (most recent call last):
  File "D:/code/flask_demo/bb.py", line 5, in <module>
    fun(1,0)
  File "D:/code/flask_demo/bb.py", line 3, in fun
    return a/b
ZeroDivisionError: division by zero
Traceback (most recent call last):
  File "D:/code/flask_demo/bb.py", line 5, in <module>
    fun(1,0)
  File "D:/code/flask_demo/bb.py", line 3, in fun
    return a/b
ZeroDivisionError: division by zero

Process finished with exit code 0
stack = traceback.extract_stack()

print(stack)

print(len(stack))

invoked =stack[-2][-2]

print(invoked)

child_method = getattr(self, invoked)
desc =
print(child_method.func.doc )