有没有办法 运行 目录中的所有 Jupyter 笔记本?

Is there a way to run all Jupyter Notebooks inside a directory?

简介

我在一个目录中有很多 Jupyter 笔记本,我想 运行 全部查看它们的输出。

我实际上在做什么

我必须打开它们每个,点击“重新启动内核并重新运行整个笔记本?”, 等几分钟再去下一个。

我想做什么

想办法“按一个按钮”(可以是 脚本、命令或任何东西 ),出去走走,然后回来阅读什么是输出。

提前致谢!

您可以将每个想要 运行 的笔记本转换成 .py 文件,然后创建一个将它们作为模块导入的笔记本。像这样:

script1.py:

print('This is the first script.')

script2.py:

print('This is the second script.')

script3.py:

print('...and this is the last one!')

现在您将它们全部导入到一个脚本中(您可以在 Jupyter 中创建它):

import script1
import script2
import script3
# This is the first script.
# This is the second script.
# ...and this is the last one!

您可以使用 nbconvertpapermill 来实现。 另见

这是 papermill 中的示例:

使用 Anaconda 安装:

conda install -c conda-forge papermill

创建一个运行特定目录中所有笔记本的新笔记本:

import papermill as pm
from pathlib import Path

for nb in Path('./run_all').glob('*.ipynb'):
    pm.execute_notebook(
        input_path=nb,
        output_path=nb  # Path to save executed notebook
    )