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

如何强制VS Code的Jupyter单元格用print输出而非display,与Python控制台一致?

解决VS Code Jupyter笔记本输出与Python控制台一致的问题

方案一:修改IPython格式化器强制使用repr输出

通过自定义IPython的文本格式化器,让所有对象的输出都调用repr()方法,和Python控制台的输出逻辑完全对齐。

  1. 将以下配置添加到VS Code的settings.json的jupyter.runStartupCommands中:
"jupyter.runStartupCommands": [
    "from IPython.core.interactiveshell import InteractiveShell",
    "InteractiveShell.ast_node_interactivity = 'all'",
    "from IPython.core.formatters import PlainTextFormatter",
    "plain_formatter = get_ipython().display_formatter.formatters['text/plain']",
    "plain_formatter.for_type(object, lambda obj, p, cycle: p.text(repr(obj)))"
]
  1. 重启VS Code的Jupyter内核后生效,此时运行int会输出<class 'int'>,和控制台完全一致。

方案二:使用IPython魔术命令快速切换

IPython内置的%repr魔术命令可以直接切换输出风格为plain模式,与控制台对齐:

  1. 在笔记本单元格中运行:
%repr plain
  1. 若要永久生效,将该命令加入settings.json的启动配置:
"jupyter.runStartupCommands": [
    "from IPython.core.interactiveshell import InteractiveShell",
    "InteractiveShell.ast_node_interactivity = 'all'",
    "%repr plain"
]

两种方案都能解决Jupyter美化输出的问题,让单元格输出和Python控制台的repr()输出完全一致。

内容的提问来源于stack exchange,提问作者Napping Lunar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 20:05:34