我目前正在用 Python 构建一个相当复杂的系统,当我调试时,我经常将简单的打印语句放在几个脚本中。为了保持概览,我经常还想打印出 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() 函数的文件名和行号?
最佳答案
函数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
关于python - 调试:获取调用函数的文件名和行号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24438976/