Shortcuts

Automatic notebook backups

While working with notebooks it is very common to…

In order to enable backup of notebooks copy the code below into ${HOME}/.jupyter/jupyter_notebook_config.py. You will need to restart the Jupyter server for this to take effect.

from pathlib import Path
import io
import os

_script_exporter = None

def post_save(model, os_path, contents_manager, **kwargs):
    """post-save hook for converting notebooks to .py scripts"""
    from nbconvert.exporters.script import ScriptExporter

    if model['type'] != 'notebook':
        return   # only do this for notebooks
    if os_path.endswith('.py'):
        return
    if 'Untitled' in os_path:
        return  # do not convert Untitled notebooks

    global _script_exporter

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

    log = contents_manager.log

    p = Path(os_path)

    for j in range(9):
        try:
            f = p.parent / f'{p.stem}.py~{8-j}~'
            f.rename(p.parent / f'{p.stem}.py~{9-j}~')
        except:
            pass

    f = p.parent / f'{p.stem}.py'
    try:
        f.rename(p.parent / f'{p.stem}.py~{1}~')
    except:
        pass

    script, resources = _script_exporter.from_filename(os_path)
    with io.open(f"{f}", 'w', encoding='utf-8') as f:
        f.write(script)

c.FileContentsManager.post_save_hook = post_save

Docs

Access comprehensive developer documentation for PyTorch

View Docs

Tutorials

Get in-depth tutorials for beginners and advanced developers

View Tutorials

Resources

Find development resources and get your questions answered

View Resources