You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 08:10:32