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

如何通过Python脚本为.ipynb文件添加代码单元格并运行

给Jupyter Notebook添加代码单元格并运行的实现方法

方法1:使用官方nbformat库(推荐)

Jupyter官方提供的nbformat库专门用于处理Notebook文件的解析、修改和生成,能严格遵循Notebook格式规范,避免手动操作JSON的潜在错误。

步骤:

  1. 安装依赖:
pip install nbformat nbconvert
  1. 编写Python脚本(main.py):
import nbformat
from nbconvert.preprocessors import ExecutePreprocessor
import os

# 读取目标Notebook文件
nb = nbformat.read('notebook.ipynb', as_version=4)

# 定义需要添加的代码内容
code_snippets = [
    "import numpy as np",
    "print('新增代码单元格执行成功')",
    "df = pd.DataFrame({'col1': [1,2,3]})"
]

# 创建代码单元格并添加到Notebook末尾
for snippet in code_snippets:
    code_cell = nbformat.v4.new_code_cell(source=snippet)
    nb.cells.append(code_cell)

# 若要插入到指定位置(比如第2个单元格之后),用insert方法:
# nb.cells.insert(2, code_cell)

# 保存修改后的Notebook
nbformat.write(nb, 'modified_notebook.ipynb')

# 运行修改后的Notebook
exec_processor = ExecutePreprocessor(timeout=600, kernel_name='python3')
try:
    # 指定工作路径,确保Notebook能正确加载本地文件
    exec_processor.preprocess(nb, {'metadata': {'path': os.getcwd()}})
    # 保存运行后的结果(包含输出)
    nbformat.write(nb, 'executed_notebook.ipynb')
    print("Notebook修改并运行完成")
except Exception as e:
    print(f"运行过程出错: {str(e)}")

方法2:直接操作JSON结构(适合简单场景)

Jupyter Notebook本质是JSON格式文件,可直接用Python的json库读取修改,再通过nbconvert命令运行。但需注意严格遵循Notebook的结构规范,否则可能导致文件损坏。

代码示例:

import json
import subprocess

# 读取Notebook的JSON内容
with open('notebook.ipynb', 'r', encoding='utf-8') as f:
    nb_json = json.load(f)

# 定义要添加的代码单元格
new_code_cell = {
    "cell_type": "code",
    "execution_count": None,
    "metadata": {},
    "outputs": [],
    "source": "import matplotlib.pyplot as plt\nplt.plot([1,2,3])"
}

# 将新单元格添加到现有列表末尾
nb_json['cells'].append(new_code_cell)

# 保存修改后的Notebook
with open('modified_notebook.ipynb', 'w', encoding='utf-8') as f:
    json.dump(nb_json, f, indent=2)

# 用nbconvert运行(你已熟悉的方式)
subprocess.run([
    'jupyter', 'nbconvert', '--to', 'notebook', '--execute',
    '--inplace', 'modified_notebook.ipynb'
], check=True)

注意事项:

  • 若需插入到指定位置,使用列表的insert方法替换append即可
  • 运行时确保目标kernel(如python3)在当前环境中存在
  • 建议修改后保存为新文件,避免覆盖原Notebook导致数据丢失

内容的提问来源于stack exchange,提问作者Pranav Gor

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 18:55:24