自动将Jupyter Notebook转换为.py

时间:2019-08-06 10:12:37

标签: python bash automation jupyter-notebook ipython

我知道对此有一些疑问,但是我还没有发现足够强大的方法。

当前,我正在从终端使用创建.py的命令,然后将其移动到另一个文件夹:

jupyter nbconvert --to script '/folder/notebooks/notebook.ipynb' &&  \
mv ./folder/notebooks/*.py ./folder/python_scripts && \

然后,工作流将在笔记本中进行编码,并使用git status检查自上次提交以来发生了什么更改,创建可能nbconvert的潜在大量命令,然后全部移动。

我想使用类似!jupyter nbconvert --to script找到的in this answer,但是在.py本身中没有创建python文件的单元格。

因为如果出现该行,我的代码将永远无法正常工作。

那么,有没有适当的方法来解决这个问题?可以自动执行,而无需手动复制文件名,创建命令,执行然后重新启动的程序。

3 个答案:

答案 0 :(得分:4)

另一种方法是将Jupytext用作jupyter安装的扩展名(可以很容易地通过pip安装)。

Jupytext描述(请参见github页)

您是否一直希望Jupyter笔记本是纯文本文档? 希望您可以在自己喜欢的IDE中编辑它们吗?并弄清楚 版本控制时有意义的差异?那... Jupytext可能很好 成为您要寻找的工具!

它将使配对的笔记本与.py文件保持同步。然后,您仅需要移动.py文件或gitignore笔记本,例如可能的工作流程。

答案 1 :(得分:1)

您可以在笔记本文件的最后一个单元格中添加以下代码。

!jupyter nbconvert --to script mycode.ipynb
with open('mycode.py', 'r') as f:
    lines = f.readlines()
with open('mycode.py', 'w') as f:
    for line in lines:
        if 'nbconvert --to script' in line:
            break
        else:
            f.write(line)

它将生成.py文件,然后从其中删除此代码。您将得到一个干净的脚本,该脚本不再调用!jupyter nbconvert

答案 2 :(得分:0)

This是我所发现的最接近的想法,但我尚未尝试实现它:

   # A post-save hook to make a script equivalent whenever the notebook is saved (replacing the --script option in older versions of the notebook):

import io
import os
from notebook.utils import to_api_path

_script_exporter = None

def script_post_save(model, os_path, contents_manager, **kwargs):
    """convert notebooks to Python script after save with nbconvert

    replaces `jupyter notebook --script`
    """
    from nbconvert.exporters.script import ScriptExporter

    if model['type'] != 'notebook':
        return

    global _script_exporter

    if _script_exporter is None:
        _script_exporter = ScriptExporter(parent=contents_manager)

    log = contents_manager.log

    base, ext = os.path.splitext(os_path)
    script, resources = _script_exporter.from_filename(os_path)
    script_fname = base + resources.get('output_extension', '.txt')
    log.info("Saving script /%s", to_api_path(script_fname, contents_manager.root_dir))

    with io.open(script_fname, 'w', encoding='utf-8') as f:
        f.write(script)

c.FileContentsManager.post_save_hook =脚本_post_save

此外,this似乎对github上的某些用户有效,因此我将其放在此处以供参考:

import os
from subprocess import check_call

def post_save(model, os_path, contents_manager):
    """post-save hook for converting notebooks to .py scripts"""
    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)
相关问题