ipython/ipython — pull request #6896 by minrk (2014-11-11 03:37:00+00:00)
Title: Proposal: add pre/post-save hooks

We may not want to do this so close to 3.0, but it's a mitigation of the removed `--script` flag, so I thought it was worth discussing. Hooks are Python functions that are passed the model, path, and content_manager. I started with two hooks:

- `ContentsManager.pre_save_hook` runs on the path and model with content. This one can be used for things like stripping output that people don't like adding to VCS noise.
- `FileContentsManager.post_save_hook` runs on the filesystem path and model without content. This one can be used to replace `--script` with a call to nbconvert.

An example `ipython_notebook_config.py` that does both of these things:

A pre-save hook for stripping output:

```python

def scrub_output_pre_save(model, **kwargs):
"""scrub output before saving notebooks"""
# only run on notebooks
if model['type'] != 'notebook':
return
# only run on nbformat v4
if model['content']['nbformat'] != 4:
return

model['content']['metadata'].pop('signature', None)
for cell in model['content']['cells']:
if cell['cell_type'] != 'code':
continue
cell['outputs'] = []
cell['execution_count'] = None

c.FileContentsManager.pre_save_hook = scrub_output_pre_save
```

A post-save hook to replace `--script` (this could be a simple call to `ipython nbconvert --to notebook`, but spawning the subprocess every time is quite slow):

```python
import io
import os
from IPython.nbconvert.exporters.python import PythonExporter

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`
"""
log = contents_manager.log
global exporter
if model['type'] != 'notebook':
return
if exporter is None:
exporter = PythonExporter(config=contents_manager.config)

base, ext = os.path.splitext(os_path)
py_fname = base + '.py'
log.info("Writing %s", py_fname)
py, resources = exporter.from_filename(os_path)
with io.open(py_fname, 'w', encoding='utf-8') as f:
f.write(py)

c.FileContentsManager.post_save_hook = script_post_save
```