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

标签 python debugging line-numbers inspect

我目前正在用 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/

相关文章:

python - 匹配文件中的行,例如 grep -f

python - Tarjan 在 python 中的强连接组件算法不起作用

ios - XCODE 8.2 错误地检测到锁定的设备

javascript - 轻量级 Bug 报告 javascript 表单?

python - 如何从 Pandas HDF 存储中读取 nrows?

python - 环境不一致,请仔细检查套餐方案-cvxopt

python - 检查在 Python 中打开了哪些文件

css - 如何使用 Yeoman 的 Grunt.js 文件启用 SASS lineNumbers?

C# 异常行号始终为零 (0)

python - 使用 cElementTree : dealing with errors and line number in the file 在 python 中解析 XML 文件