我目前正在用 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
file.
所以我的问题实际上是:如何获取调用此 debuginfo() 函数的文件名和行号?