有没有办法在一个目录中运行所有Jupyter笔记本?

2024-05-15 14:27:04 发布

您现在位置:Python中文网/ 问答频道 /正文

导言

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

我到底做了什么

我必须打开每一个,单击“重新启动内核并重新运行整个笔记本?”,等待几分钟,然后开始下一个

我想做什么

找到一种方法,只需“按下一个按钮”(它可以是脚本、命令或所有内容),出去散散步,然后回来阅读输出内容

提前谢谢


Tags: 方法命令目录脚本内容笔记本jupyter按钮
2条回答

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

脚本1.py:

print('This is the first script.')

脚本2.py:

print('This is the second script.')

脚本3.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实现这一点。 另见this answer

这是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
    )

相关问题 更多 >