Skip to content

Instantly share code, notes, and snippets.

@agalea91
Last active October 13, 2021 00:28
Show Gist options
  • Save agalea91/d7fd457e514c0b6aa0daee6ae06a9b29 to your computer and use it in GitHub Desktop.
Save agalea91/d7fd457e514c0b6aa0daee6ae06a9b29 to your computer and use it in GitHub Desktop.
Jupyter Config file with post-save hook for saving Notebook as Python script
# 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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment