如何在Jupyter Notebook 7+中永久折叠所有代码?
强制永久折叠Jupyter Notebook代码的解决方案
方案1:自定义CSS样式(全局生效)
- 定位Jupyter配置目录(默认路径为
~/.jupyter/custom/,不存在则手动创建) - 在该目录下新建
custom.css文件,写入以下样式代码:
/* 强制隐藏所有代码单元格的输入区域 */ div.input_area { display: none !important; } /* 可选配置:保留折叠控制按钮,方便临时恢复查看 */ div.cell > div.input { display: flex; justify-content: flex-end; } div.cell > div.input > div.input_area { display: none !important; }
- 重启Jupyter Notebook后,所有代码单元格的输入区域会被强制隐藏,点击单元格也不会触发显示。若需临时查看代码,可注释CSS代码后重启服务。
方案2:JupyterLab专用扩展(适配新版环境)
- 安装
jupyterlab-code-fold扩展,在终端执行以下命令:
pip install jupyterlab-code-fold jupyter lab build
- 启动JupyterLab后,进入设置面板开启「永久折叠所有代码」选项,或自定义快捷键设置默认折叠状态,确保点击单元格不会展开代码。
方案3:修改笔记本元数据(单文件生效)
- 打开目标笔记本,点击菜单栏
Edit > Edit Notebook Metadata - 在弹出的JSON编辑器中,为每个代码单元格的元数据添加折叠锁定配置:
{ "cells": [ { "cell_type": "code", "metadata": { "collapsed": true, "editable": false }, // 单元格原有内容保持不变 } ] }
- 保存元数据后,代码单元格会保持折叠状态,且无法通过点击展开(
editable: false限制了编辑操作)。如需修改代码,将editable改回true即可。
方案4:适配新版的自定义JS脚本
- 在Jupyter配置目录的
custom文件夹下新建custom.js文件,写入以下代码:
document.addEventListener('DOMContentLoaded', function() { // 隐藏已加载的代码输入区域 const hideInputAreas = () => { document.querySelectorAll('.input_area').forEach(area => { area.style.display = 'none'; }); }; // 初始执行一次 hideInputAreas(); // 监听新单元格添加事件,自动隐藏新增代码单元格 const observer = new MutationObserver((mutations) => { mutations.forEach(mutation => { mutation.addedNodes.forEach(node => { if (node.classList?.contains('cell')) { const inputArea = node.querySelector('.input_area'); inputArea && (inputArea.style.display = 'none'); } }); }); }); observer.observe(document.querySelector('.notebook'), { childList: true, subtree: true }); });
- 重启Jupyter后,脚本会自动隐藏所有现有及新增的代码单元格,点击单元格不会触发显示。
内容的提问来源于stack exchange,提问作者Arthur
相关产品推荐
相关产品推荐

