如何从.py或.ipynb文件中编程执行指定Jupyter Notebook单元格
基于Papermill运行Notebook指定标签单元格方案
前置准备
- 给目标Notebook的单元格打上对应标签:公共依赖单元格(如导入库、加载数据)打
common标签,不同实验的单元格分别打专属标签(如exp_1、exp_2) - 安装所需依赖:
pip install papermill nbconvert nbformat jupyter
方案1:命令行快速实现
直接通过nbconvert过滤出带目标标签的单元格生成临时Notebook,再调用Papermill执行:
# 第一步:过滤保留带common和exp_1标签的单元格,生成临时Notebook jupyter nbconvert --to notebook \ --TagRemovePreprocessor.enabled=True \ --TagRemovePreprocessor.remove_cells_without_tags="['common', 'exp_1']" \ --allow-errors \ --stdout your_target_notebook.ipynb > temp_run.ipynb # 第二步:用Papermill执行临时Notebook,支持传参、保存执行结果 papermill temp_run.ipynb output_exp_1.ipynb -p learning_rate 0.001 -p epoch 50 # 可选:删除临时文件 rm temp_run.ipynb
方案2:Python脚本封装(更灵活)
可以封装为通用脚本,无需每次输入长命令,还可以直接对接其他工作流:
import nbformat import argparse from pathlib import Path from nbconvert.preprocessors import TagRemovePreprocessor import papermill as pm def run_tagged_cells(input_nb_path: str, target_tags: list, output_nb_path: str, parameters: dict = None, allow_errors: bool = True): # 读取原Notebook文件 with open(input_nb_path, 'r', encoding='utf-8') as f: nb = nbformat.read(f, as_version=4) # 配置白名单过滤规则,仅保留带指定标签的单元格 preprocessor = TagRemovePreprocessor() preprocessor.remove_cells_without_tags = target_tags preprocessor.enabled = True filtered_nb, _ = preprocessor.preprocess(nb, {}) # 生成临时过滤后的Notebook temp_path = Path("temp_filtered.ipynb") with open(temp_path, 'w', encoding='utf-8') as f: nbformat.write(filtered_nb, f) # 调用Papermill执行,支持参数注入 pm.execute_notebook( input_path=str(temp_path), output_path=output_nb_path, parameters=parameters or {}, progress_bar=True, allow_errors=allow_errors ) # 清理临时文件 temp_path.unlink(missing_ok=True) if __name__ == "__main__": # 命令行参数解析 parser = argparse.ArgumentParser(description="Execute Jupyter Notebook cells with specified tags via Papermill") parser.add_argument("--input", required=True, help="Path of the source notebook") parser.add_argument("--tags", required=True, nargs="+", help="Tags of cells to run, e.g. --tags common exp_1") parser.add_argument("--output", required=True, help="Path to save the executed notebook") parser.add_argument("--params", nargs="*", help="Execution parameters in key=value format, e.g. --params lr=0.001 epoch=50") args = parser.parse_args() # 解析传入参数 params = {} if args.params: for param in args.params: key, val = param.split("=", 1) params[key] = int(val) if val.isdigit() else val run_tagged_cells(args.input, args.tags, args.output, params)
命令行调用示例:
python run_tagged_notebook.py --input my_experiments.ipynb --tags common exp_2 --output output_exp2.ipynb --params lr=0.0005 epoch=100
注意事项
- 标签区分大小写,打标签时注意和调用时传入的参数保持一致
- 如果某部分单元格是所有实验的公共依赖,统一打公共标签即可,无需重复添加到每个实验的标签组
- 如需跳过错误继续执行,保留
allow_errors=True参数即可,不需要可手动关闭
内容的提问来源于stack exchange,提问作者riiily
相关产品推荐
相关产品推荐

