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
这篇关于调试:获取从中调用函数的文件名和行号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
编程基础网
本文标题为:调试:获取从中调用函数的文件名和行号?
基础教程推荐
猜你喜欢
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
