金魚亭日常

読書,ガジェット,競技プログラミング

Jupyter notebook でscript とhtmlを同時保存する

ここ

www.svds.com

に乗ってるやつだけど,公式ドキュメントの方にも乗っていたのでそちらを使うことにした.

File save hooks — Jupyter Notebook 4.2.1 documentation

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 `ipython 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)
    py_fname = base + '.py'
    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 = script_post_save

これだとscriptしか保存してくれないので,見よう見まねで改変.

File save hooks of jupyter. Export script and HTML ...

これを,~/.jupyterに保存するとnotebookが保存されると同時に同じ場所にscriptとhtmlができる.

全体が同じ設定になるので本当はgitレポジトリ単位でやりたいけど,とりあえずはこれで.