保存时将笔记本 (.ipynb) 导出为 .py 文件

pla*_*nne 2 ipython-notebook jupyter

我目前正在使用 Jupyter IPython Notebook。我想将我的笔记本置于版本控制之下。

这就是为什么当我保存并检查笔记本(.ipynb 文件)时,我希望更改也保存并同步到同一文件夹中的相应 python 脚本(.py 文件)中。(见下图)

我的文件

它与我使用的 Jupyter 版本有关吗?还是我必须编辑 config_file?

谢谢

Mad*_*ava 5

您需要在配置目录中创建 jupyter_notebook_config.py。

如果不存在,请从主目录执行以下命令:./jupyter notebook --generate-config

在此文件中添加粘贴以下代码:

import os
from subprocess import check_call

c = get_config()

def post_save(model, os_path, contents_manager):
    """post-save hook for converting notebooks to .py and .html files."""
    if model['type'] != 'notebook':
        return # only do this for notebooks
    d, fname = os.path.split(os_path)
    check_call(['ipython', 'nbconvert', '--to', 'script', fname], cwd=d)
    check_call(['ipython', 'nbconvert', '--to', 'html', fname], cwd=d)

c.FileContentsManager.post_save_hook = post_save
Run Code Online (Sandbox Code Playgroud)

然后,您需要重新启动 jupyter 服务器,然后就可以了!

  • 在新版本的 jupyter 中,您将收到警告:_“不推荐使用子命令 'ipython nbconvert' 并将在未来版本中删除。您可能希望在未来使用 'jupyter nbconvert'。”_ 因此用 `ipython` 代替 `jupyter ` 在代码中。见 /sf/answers/2054613641/ (2认同)