异常(Python)中的堆栈跟踪中的locals()和globals()

时间:2013-10-22 09:42:22

标签: python exception stack-trace

虽然堆栈跟踪在Python中很有用,但大多数情况下问题根源的数据都缺失了 - 有没有办法确保至少将locals()(以及可能的globals())添加到打印的堆栈跟踪中?

4 个答案:

答案 0 :(得分:10)

您可以安装自己的异常挂钩并从那里输出所需内容:

import sys, traceback

def excepthook(type, value, tb):
    traceback.print_exception(type, value, tb)

    while tb.tb_next:
        tb = tb.tb_next

    print >>sys.stderr, 'Locals:',  tb.tb_frame.f_locals
    print >>sys.stderr, 'Globals:', tb.tb_frame.f_globals

sys.excepthook = excepthook

def x():
    y()

def y():
    foo = 1
    bar = 0

    foo/bar

x()

要在追溯中从每个帧打印变量,请将上面的循环更改为

    while tb:
        print >>sys.stderr, 'Locals:',  tb.tb_frame.f_locals
        print >>sys.stderr, 'Globals:', tb.tb_frame.f_globals
        tb = tb.tb_next

答案 1 :(得分:2)

这是潘多拉盒子。印刷形式的数值可能非常大;在堆栈跟踪中打印所有本地因很容易因错误输出而导致出现新问题。这就是为什么在Python中没有实现这一点。

在小例子中,我。即如果您知道您的值不是太大而无法正确打印,您可以自己沿着追溯步骤:

import sys
import traceback

def c():
  clocal = 1001
  raise Exception("foo")

def b():
  blocal = 23
  c()

def a():
  alocal = 42
  b()

try:
  a()
except Exception:
  frame = sys.exc_info()[2]
  formattedTb = traceback.format_tb(frame)    
  frame = frame.tb_next
  while frame:
    print formattedTb.pop(0), '\t', frame.tb_frame.f_locals
    frame = frame.tb_next

输出将是这样的:

  File "/home/alfe/tmp/stacktracelocals.py", line 19, in <module>
    a()
        {'alocal': 42}
  File "/home/alfe/tmp/stacktracelocals.py", line 16, in a
    b()
        {'blocal': 23}
  File "/home/alfe/tmp/stacktracelocals.py", line 12, in b
    c()
        {'clocal': 1001}

当然,你可以在他的回答中建议你自己安装除了钩子之外的thg435。

答案 2 :(得分:1)

如果您还不知道,请使用pdb验尸功能:

x = 3.0
y = 0.0
print x/y
def div(a, b):
    return a / b
print div(x,y)
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-3-d03977de5fc3> in div(a, b)
      1 def div(a, b):
----> 2     return a / b

ZeroDivisionError: float division

import pdb
pdb.pm()
> <ipython-input-3-148da0dcdc9e>(2)div()
      0     return a/b

ipdb> l
      1 def div(a,b):
----> 2     return a/b

ipdb> a
3.0
ipdb> b
0.0

等。

当然,有些情况下你确实需要打印。你可以更好地检测代码(通过try / except)打印出你正在调试的特定奇怪异常的额外信息,而不是把它放在一切,尽管如此,imho。

答案 3 :(得分:0)

尝试使用traceback-with-variables软件包。

用法:

from traceback_with_variables import traceback_with_variables

def main():
    ...
    with traceback_with_variables():
        ...your code...

例外:

Traceback with variables (most recent call last):
  File "./temp.py", line 7, in main
    return get_avg_ratio([h1, w1], [h2, w2])
      sizes_str = '300 200 300 0'
      h1 = 300
      w1 = 200
      h2 = 300
      w2 = 0
  File "./temp.py", line 10, in get_avg_ratio
    return mean([get_ratio(h, w) for h, w in [size1, size2]])
      size1 = [300, 200]
      size2 = [300, 0]
  File "./temp.py", line 10, in <listcomp>
    return mean([get_ratio(h, w) for h, w in [size1, size2]])
      .0 = <tuple_iterator object at 0x7ff61e35b820>
      h = 300
      w = 0
  File "./temp.py", line 13, in get_ratio
    return height / width
      height = 300
      width = 0
builtins.ZeroDivisionError: division by zero

安装:

pip install traceback-with-variables