如何在冰淇淋打印输出中显示代码行号(没有额外的上下文)?



我目前正在使用冰淇淋(https://github.com/gruns/icecream)打印变量和其他信息用于调试和审查目的。我希望能够显示行号,其中打印呼叫起源于,不包括额外的信息。如果有更好的选择,我不需要用冰淇淋。

下面的代码可以产生如下输出:

1 - from icecream import ic
2 - test = 'hello'
3 - ic(test)

ic| test: 'hello'

这很好,我可以随心所欲地调整前缀,但我还希望能够包括生成输出的行号。Icecream有一个函数可以做到这一点,但它也输出了一堆我不感兴趣的其他信息(见下文)。

1 - from icecream import ic
2 - ic.configureOutput(prefix=f'Debug | ', includeContext=True)
3 - test = 'hello'
4 - ic(test)

Debug | test.py:4 in <module>- test: 'hello'

似乎没有一种原生的方式来只显示行号(在上面的例子中是4)而不显示其他信息(文件名和父函数)。我能做的是在前缀编辑器中包含一些代码来获取行号,但这只是给我提供了ic.configureOutput()函数的行号,我认为这是有意义的,因为这是发出行号请求的函数。

1 - from icecream import ic
2 - import sys
3 - def line_number():
4 -     return sys._getframe().f_back.f_lineno
5 - ic.configureOutput(prefix=f'Debug:{line_number()} | ')
6 - test = 'hello'
7 - ic(test)

Debug:5 | test: 'hello'

是否有一种方法(或完全其他方法)来获得上述输出,但使行号(在上面的示例中为第5行)是发起调用的脚本中的实际行号(在上面的示例中为7)?

我想你可以使用"inspect">

from inspect import currentframe
def get_line();
return currentframe().f_back_f_lineno
print("this is sample:", get_line())

最新更新