如何在Icecream输出中仅显示代码行号(无额外上下文)
解决Icecream仅显示调用行号的方案
自定义Icecream输出函数
Icecream的includeContext会附带文件名、函数名等多余信息,我们可以通过自定义输出函数,精准获取ic调用的行号:
import sys from icecream import ic def custom_ic_output(output_str): # 栈层级设为2,跳过Icecream内部调用栈,直接定位到ic的实际调用语句 call_line = sys._getframe(2).f_lineno print(f"[Line {call_line}] {output_str}") # 配置Icecream使用自定义输出逻辑 ic.configureOutput(outputFunction=custom_ic_output)
调用示例:
x = 10 ic(x) # 输出:[Line 8] x: 10
轻量替代方案:自制调试函数
如果觉得Icecream功能冗余,可以自己实现极简调试函数,直接获取行号和变量信息:
import sys import inspect def dbg(var): frame = sys._getframe(1) # 从代码上下文提取变量名 var_name = inspect.getframeinfo(frame).code_context[0].strip().split('(')[1].split(')')[0] line_num = frame.f_lineno print(f"[Line {line_num}] {var_name} = {var}")
调用示例:
y = "hello" dbg(y) # 输出:[Line 12] y = hello
内容的提问来源于stack exchange,提问作者Oliblish
相关产品推荐
相关产品推荐

