调试:获取从中调用函数的文件名和行号? [英] Debugging: Get filename and line number from which a function is called?

查看:42
本文介绍了调试:获取从中调用函数的文件名和行号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在用Python构建一个相当复杂的系统,在调试时,我经常将简单的打印语句放在几个脚本中。为了保持概述,我通常还想打印出打印语句所在的文件名和行号。当然,我可以手动执行此操作,也可以使用以下命令:

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()函数的文件名和行号?

推荐答案

函数inspect.stack()返回frame records的列表,从调用者开始,然后移出,您可以使用该列表获取所需的信息:

from inspect import getframeinfo, stack

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

def grr(arg):
    debuginfo(arg)      # <-- stack()[1][0] for this line

grr("aargh")            # <-- stack()[2][0] for this line

输出

example.py:8 - aargh

这篇关于调试:获取从中调用函数的文件名和行号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆