保存时将笔记本(.ipynb)导出为.py文件 [英] Export a notebook (.ipynb) as a .py file upon saving

查看:322
本文介绍了保存时将笔记本(.ipynb)导出为.py文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm currently working with Jupyter IPython Notebook.I would like to put my notebook under version control.

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

That's why, when I save and checkpoint a Notebook (.ipynb file), I would like the changes to also be saved and synchronized in the corresponding python script (.py file) in the same folder. (see picture below)

我的文件

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

Does it have something to do with the version of Jupyter I am using? Or do I have to edit a config_file?

谢谢

推荐答案

您需要在config-dir中创建jupyter_notebook_config.py.

You need to create jupyter_notebook_config.py in your config-dir.

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

if doesn't exists, execute below command from home directory : ./jupyter notebook --generate-config

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

Add paste following code in this file :

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

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

You will then need to restart your jupyter server and there you go!

这篇关于保存时将笔记本(.ipynb)导出为.py文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆