Python调试:获取调用函数的文件名和行号?

2024-04-27 04:18:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在用Python构建一个相当复杂的系统,在调试时,我经常将简单的print语句放在几个脚本中。为了保持概述,我通常还想打印出print语句所在的文件名和行号。我当然可以手动完成,或者用这样的方法:

from inspect import currentframe, getframeinfo
print getframeinfo(currentframe()).filename + ':' + str(getframeinfo(currentframe()).lineno) + ' - ', 'what I actually want to print out here'

上面印着:

filenameX.py:273 - what I actually want to print out here

为了让事情更简单,我想做一些事情,比如:

print debuginfo(), 'what I actually want to print out here'

所以我把它放在某个地方,试着做:

from debugutil import debuginfo
print debuginfo(), 'what I actually want to print out here'
print debuginfo(), 'and something else here'

不幸的是,我得到:

debugutil.py:3 - what I actually want to print out here
debugutil.py:3 - and something else here

它打印出我定义函数的文件名和行号,而不是我调用debuginfo()的行。这是显而易见的,因为代码位于debugutil.py文件中。

所以我的问题是:如何获取调用此debuginfo()函数的文件名和行号?欢迎所有提示!


Tags: topyhere文件名语句outwhatprint
3条回答

函数^{}返回frame records的列表,从调用者开始并移出,您可以使用该列表获取所需的信息:

from inspect import getframeinfo, stack

def debuginfo(message):
    caller = getframeinfo(stack()[1][0])
    print "%s:%d - %s" % (caller.filename, caller.lineno, message)

def grr(arg):
    debuginfo(arg)

grr("aargh")

输出

example.py:8 - aargh

把你发布的代码放到函数中:

from inspect import currentframe, getframeinfo

def my_custom_debuginfo(message):
    print getframeinfo(currentframe()).filename + ':' + str(getframeinfo(currentframe()).lineno) + ' - ', message

然后随心所欲地使用它:

# ... some code here ...
my_custom_debuginfo('what I actually want to print out here')
# ... more code ...

我建议您将该函数放在一个单独的模块中,这样您就可以在每次需要时重用它。

如果将跟踪代码放在另一个函数中,并从主代码中调用它,则需要确保从祖父母而不是父函数或跟踪函数本身获取堆栈信息

下面是一个3层深度系统的例子,进一步阐明我的意思。我的主函数调用一个跟踪函数,它调用另一个函数来完成这项工作。

######################################

import sys, os, inspect, time
time_start = 0.0                    # initial start time

def trace_libary_init():
    global time_start

    time_start = time.time()      # when the program started

def trace_library_do(relative_frame, msg=""):
    global time_start

    time_now = time.time()

        # relative_frame is 0 for current function (this one), 
        # 1 for direct parent, or 2 for grand parent.. 

    total_stack         = inspect.stack()                   # total complete stack
    total_depth         = len(total_stack)                  # length of total stack
    frameinfo           = total_stack[relative_frame][0]    # info on rel frame
    relative_depth      = total_depth - relative_frame      # length of stack there

        # Information on function at the relative frame number

    func_name           = frameinfo.f_code.co_name
    filename            = os.path.basename(frameinfo.f_code.co_filename)
    line_number         = frameinfo.f_lineno                # of the call
    func_firstlineno    = frameinfo.f_code.co_firstlineno

    fileline            = "%s:%d" % (filename, line_number)
    time_diff           = time_now - time_start

    print("%13.6f %-20s %-24s %s" % (time_diff, fileline, func_name, msg))

################################

def trace_do(msg=""):
    trace_library_do(1, "trace within interface function")
    trace_library_do(2, msg)
    # any common tracing stuff you might want to do...

################################

def main(argc, argv):
    rc=0
    trace_libary_init()
    for i in range(3):
        trace_do("this is at step %i" %i)
        time.sleep((i+1) * 0.1)         # in 1/10's of a second
    return rc

rc=main(sys.argv.__len__(), sys.argv)
sys.exit(rc)

这将打印如下内容:

$ python test.py 
    0.000005 test.py:39           trace_do         trace within interface func
    0.001231 test.py:49           main             this is at step 0
    0.101541 test.py:39           trace_do         trace within interface func
    0.101900 test.py:49           main             this is at step 1
    0.302469 test.py:39           trace_do         trace within interface func
    0.302828 test.py:49           main             this is at step 2

顶部的trace_library_do()函数是一个可以放入库中,然后从其他跟踪函数调用它的示例。相对深度值控制打印python堆栈中的哪个条目。

我展示了在该函数中提取一些其他有趣的值,比如函数开始的行号、堆栈总深度和文件的完整路径。我没有显示它,但是函数中的全局和局部变量也可以在inspect中使用,以及对下面所有其他函数的完整堆栈跟踪。上面我展示的信息已经足够多了,可以进行层次化的调用/返回计时跟踪。实际上,从这里开始创建自己的源代码级调试器的主要部分并没有那么远——而它基本上只是坐在那里等待使用。

我确信有人会反对我使用inspect结构返回数据的内部字段,因为很可能有一些访问函数会为您执行同样的操作。但我是通过在python调试器中单步执行这类代码发现它们的,而且它们至少在这里工作。我运行的是Python2.7.12,如果您运行的是不同的版本,那么您的结果可能非常好。

无论如何,我强烈建议您将inspect代码导入到自己的一些python代码中,并查看它能为您提供什么——特别是如果您可以在一个好的python调试器中单步完成代码。您将学到很多关于python如何工作的知识,并了解该语言的优点,以及幕后发生的事情。

带有时间戳的完整源代码级跟踪是增强您对代码所做工作的理解的一个很好的方法,特别是在动态实时环境中。这种类型的跟踪代码的好处是,一旦编写完成,就不需要调试器支持就可以看到它。

相关问题 更多 >