我目前正在用 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() 函数的文件名和行号?
原文由 kramer65 发布,翻译遵循 CC BY-SA 4.0 许可协议
函数
inspect.stack()
返回一个 帧记录 列表,从调用者开始向外移动,你可以用它来获取你想要的信息:输出: