Debugging: Get filename and line number from which a function is called?(调试:获取从中调用函数的文件名和行号?)
本文介绍了调试:获取从中调用函数的文件名和行号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我目前正在用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
这篇关于调试:获取从中调用函数的文件名和行号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:调试:获取从中调用函数的文件名和行号?


基础教程推荐
猜你喜欢
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 包装空间模型 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01