如何强制VS Code的Jupyter单元格用print输出而非display,与Python控制台一致?
解决VS Code Jupyter笔记本输出与Python控制台一致的问题
方案一:修改IPython格式化器强制使用repr输出
通过自定义IPython的文本格式化器,让所有对象的输出都调用repr()方法,和Python控制台的输出逻辑完全对齐。
- 将以下配置添加到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)))" ]
- 重启VS Code的Jupyter内核后生效,此时运行
int会输出<class 'int'>,和控制台完全一致。
方案二:使用IPython魔术命令快速切换
IPython内置的%repr魔术命令可以直接切换输出风格为plain模式,与控制台对齐:
- 在笔记本单元格中运行:
%repr plain
- 若要永久生效,将该命令加入
settings.json的启动配置:
"jupyter.runStartupCommands": [ "from IPython.core.interactiveshell import InteractiveShell", "InteractiveShell.ast_node_interactivity = 'all'", "%repr plain" ]
两种方案都能解决Jupyter美化输出的问题,让单元格输出和Python控制台的repr()输出完全一致。
内容的提问来源于stack exchange,提问作者Napping Lunar
相关产品推荐
相关产品推荐

