0

我们的 python 项目中使用了一个简单的 AssertTrue 函数,我想修改它提供的输出以打印调用它的代码语句。代码看起来像这样:

1 import traceback
2
3 def AssertTrue(expr, reason=None):
4     print traceback.format_stack()[-2]
5
6 AssertTrue(1 == 2,
7         reason='One is not equal to two')

输出:

File "/tmp/fisken.py", line 7, in <module>
  reason='One is not equal to two')

我想知道为什么 traceback.format_stack 只给了我第 7 行的代码。语句从第 6 行开始,我想在输出中看到的表达式也在同一行。回溯不处理多行函数调用吗?

(不要介意有更好的方法来执行 AssertTrue(...)。我只是想知道为什么 traceback.format_stack (和 .extract_stack)的行为不像我预期的那样)

4

1 回答 1

2

回溯不处理多行函数调用吗?

许多函数长达数十甚至(恐怖)数百行。如果 traceback 确实打印了整个函数,那么堆栈跟踪将变得难以理解。所以我想你所看到的是试图保持清洁和最小化。

我收集了一些类似问题的答案:

考虑到它检查只能获取整个函数的源(如果源在路径上可用),我可以为您提供:

import traceback
import inspect
import gc

def giveupthefunc(frame):
    code  = frame.f_code
    globs = frame.f_globals
    functype = type(lambda: 0)
    funcs = []
    for func in gc.get_referrers(code):
        if type(func) is functype:
            if getattr(func, "func_code", None) is code:
                if getattr(func, "func_globals", None) is globs:
                    funcs.append(func)
                    if len(funcs) > 1:
                        return None
    return funcs[0] if funcs else None


def AssertTrue(expr, reason=None):
    print traceback.format_stack()[-2]
    frame = inspect.currentframe().f_back
    func = giveupthefunc(frame)
    if func:
        source = inspect.getsourcelines(func)
        i = source[1]
        for line in source[0]:
            print i, ":", line,
            i += 1



def my_fun():
    AssertTrue(1 == 2,
             reason='One is not equal to two')

my_fun()

产生:

/Library/Frameworks/Python.framework/Versions/2.7/bin/python /Users/xxxx/Documents/PycharmProjects/scratchpad/test.py
  File "/Users/xxxx/Documents/PycharmProjects/scratchpad/test.py", line 35, in my_fun
    reason='One is not equal to two')

33 : def my_fun():
34 :     AssertTrue(1 == 2,
35 :              reason='One is not equal to two')
于 2012-07-17T10:19:22.093 回答