Last active
March 3, 2020 07:30
-
-
Save agalea91/734143ab076b612a58d152d1c306c2d9 to your computer and use it in GitHub Desktop.
Jupyter Config file with post-save hooks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# File path: | |
# ~/.jupyter/jupyter_notebook_config.py | |
import os | |
from subprocess import check_call | |
import datetime | |
import re | |
def timestamped_file(fname): | |
return bool(re.match('.*\d{4}-\d{2}-\d{2}\.ipynb', fname)) | |
def post_save(model, os_path, contents_manager): | |
""" | |
Post save hooks: | |
- Dumpy .py and .html and datestamped versions of notebook | |
Assumed folder structure: | |
├── notebooks | |
├── src | |
├── py | |
├── html | |
└── archive | |
""" | |
if model['type'] != 'notebook': | |
# Do nothing if not a notebook | |
return | |
d, fname = os.path.split(os_path) | |
if timestamped_file(fname): | |
# Do nothing for timestamped files (archived notebooks) | |
return | |
# Post-save hook for converting notebooks to .py scripts | |
py_path = os.path.join(d, '..', 'py') | |
if not os.path.exists(py_path): | |
os.makedirs(py_path) | |
html_path = os.path.join(d, '..', 'html') | |
if not os.path.exists(html_path): | |
os.makedirs(html_path) | |
check_call(['jupyter', 'nbconvert', '--to', 'python', '--output-dir', py_path, '--TemplateExporter.exclude_input_prompt=True', fname], cwd=d) | |
check_call(['jupyter', 'nbconvert', '--to', 'html', '--output-dir', html_path, fname], cwd=d) | |
# Post-save hook for saving datestamped versions of the notebooka | |
archive_path = os.path.join(d, '..', 'archive') | |
if not os.path.exists(archive_path): | |
os.makedirs(archive_path) | |
date = datetime.datetime.now().strftime('%Y-%m-%d') | |
fname_timestamped = '{}_{}.ipynb'.format(os.path.splitext(fname)[0], date) | |
fpath = os.path.join(archive_path, fname_timestamped) | |
check_call(['cp', os_path, fpath]) | |
c.FileContentsManager.post_save_hook = post_save |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment