如何从堆栈跟踪中提取局部变量?

问题描述

事实证明,可以从回溯对象中提取变量。

要手动提取值

ipdb> !import sys
ipdb> !tb = sys.exc_info()[2]
ipdb> p tb.tb_next.tb_frame.f_locals
{'y': 0, 'x': 2}

更好的是,您可以使用异常来对该堆栈进行事后调试:

import sys

def boom(x, y):
    x / y

def main():
    x = 2
    y = 0
    boom(x, y)

if __name__ == '__main__':
    try:
        main()
    except Exception as e:
        # Most debuggers allow you to just do .post_mortem()
        # but see https://github.com/gotcha/ipdb/pull/94
        tb = sys.exc_info()[2]
        import ipdb; ipdb.post_mortem(tb)

这使我们直接进入有问题的代码

> /tmp/crash.py(4)boom()
      3 def boom(x, y):
----> 4     x / y
      5

ipdb> p x
2

解决方法

假设我有一个引发意外异常的函数,因此将其包装在ipdb中:

def boom(x,y):
    try:
        x / y
    except Exception as e:
        import ipdb; ipdb.set_trace()

def main():
    x = 2
    y = 0
    boom(x,y)

if __name__ == '__main__':
    main()

我可以向上移动堆栈以找出x和y的值:

$ python crash.py 
> /tmp/crash.py(6)boom()
      5     except Exception as e:
----> 6         import ipdb; ipdb.set_trace()
      7

ipdb> u
> /tmp/crash.py(11)main()
     10     y = 0
---> 11     boom(x,y)
     12

ipdb> p y
0

但是,在调试时,我只想将调试器放在顶层:

def boom(x,y):
    x / y

def main():
    x = 2
    y = 0
    boom(x,y)

if __name__ == '__main__':
    try:
        main()
    except Exception as e:
        import ipdb; ipdb.set_trace()

我可以显示回溯,但是无法查看函数内部的变量:

$ python crash.py 
> /tmp/crash.py(14)<module>()
     12         main()
     13     except Exception as e:
---> 14         import ipdb; ipdb.set_trace()

ipdb> !import traceback; traceback.print_exc(e)
Traceback (most recent call last):
  File "crash.py",line 12,in <module>
    main()
  File "crash.py",line 8,in main
    boom(x,y)
  File "crash.py",line 3,in boom
    x / y
ZeroDivisionError: integer division or modulo by zero
ipdb> d # I want to see what value x and y had!
*** Newest frame

发生异常时,异常对象显然仍具有对堆栈的引用。我可以访问x,并y在这里,尽管堆栈有解开?