我目前正在使用Icecream (https://github.com/gruns/icecream)打印变量和其他信息,以便进行调试和检查。我希望能够显示打印呼叫起源于哪里的行号,而不包括其他信息。如果有更好的选择,我不需要使用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)?
发布于 2022-11-30 09:01:57
我认为你可以为此使用“检查”库;
from inspect import currentframe
def get_line();
return currentframe().f_back_f_lineno
print("this is sample:", get_line())https://stackoverflow.com/questions/74624205
复制相似问题