回溯不处理多行函数调用吗?
许多函数长达数十甚至(恐怖)数百行。如果 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')