Skip to content
Browse files

Added a --clean notebook option to save .clean files w/o output.

- This exactly mimics the behaviour of the --script option and
  should probably be removed once a method for hooking into the
  save command is established.
  • Loading branch information...
1 parent b1976c9 commit f70e40461e5c991e4bf7305317393abc0b1a78da Michael McNeil Forbes committed Nov 6, 2013
View
7 IPython/html/notebookapp.py
@@ -236,10 +236,15 @@ def init_handlers(self, settings):
'Auto-save a .py script everytime the .ipynb notebook is saved',
'Do not auto-save .py scripts for every notebook'))
+flags.update(boolean_flag('clean', 'FileNotebookManager.save_clean',
+ 'Save a ".clean" (no output) version when the notebook is saved.',
+ 'Do auto-save a ".clean" (no output) version'))
+
# the flags that are specific to the frontend
# these must be scrubbed before being passed to the kernel,
# or it will raise an error on unrecognized flags
-notebook_flags = ['no-browser', 'no-mathjax', 'script', 'no-script']
+notebook_flags = ['no-browser', 'no-mathjax', 'script', 'no-script',
+ 'clean', 'no-clean']
aliases = dict(kernel_aliases)
View
40 IPython/html/services/notebooks/filenbmanager.py
@@ -30,6 +30,19 @@
from IPython.utils.traitlets import Unicode, Dict, Bool, TraitError
from IPython.utils import tz
+def clean_nb(nb):
+ """Return a clean copy of the notebook nb with all output removed."""
+ clean_nb = nb.copy()
+
+ # Strip out all of the output and prompt_number sections
+ for worksheet in clean_nb["worksheets"]:
+ for cell in worksheet["cells"]:
+ if "outputs" in cell:
+ del cell.outputs[:]
+ if "prompt_number" in cell:
+ del cell["prompt_number"]
+ return clean_nb
+
#-----------------------------------------------------------------------------
# Classes
#-----------------------------------------------------------------------------
@@ -46,6 +59,13 @@ class FileNotebookManager(NotebookManager):
"""
)
+ save_clean = Bool(False, config=True,
+ help="""Save a clean (output removed) version when saving the notebook.
+
+ This can also be set with the short `--clean` flag.
+ """
+ )
+
checkpoint_dir = Unicode(config=True,
help="""The location in which to keep notebook checkpoints
@@ -255,6 +275,16 @@ def save_notebook_model(self, model, name='', path=''):
except Exception as e:
raise web.HTTPError(400, u'Unexpected error while saving notebook as script: %s %s' % (py_path, e))
+ # Save .ipynb.clean as well.
+ if self.save_clean:
+ py_path = os_path + '.clean'
+ self.log.debug("Writing clean file %s", py_path)
+ try:
+ with io.open(py_path, 'w', encoding='utf-8') as f:
+ current.write(clean_nb(nb), f, u'ipynb')
+ except Exception as e:
+ raise web.HTTPError(400, u'Unexpected error while saving clean notebook: %s %s' % (py_path, e))
+
model = self.get_notebook_model(new_name, new_path, content=False)
return model
@@ -305,6 +335,12 @@ def rename_notebook(self, old_name, old_path, new_name, new_path):
if os.path.isfile(new_py_path):
raise web.HTTPError(409, u'Python script with name already exists: %s' % new_py_path)
+ if self.save_clean:
+ old_clean_path = old_os_path + '.clean'
+ new_clean_path = new_os_path + '.clean'
+ if os.path.isfile(new_py_path):
+ raise web.HTTPError(409, u'Clean notebook with name already exists: %s' % new_py_path)
+
# Move the notebook file
try:
os.rename(old_os_path, new_os_path)
@@ -324,6 +360,10 @@ def rename_notebook(self, old_name, old_path, new_name, new_path):
# Move the .py script
if self.save_script:
os.rename(old_py_path, new_py_path)
+
+ # Move the .clean file
+ if self.save_clean:
+ os.rename(old_clean_path, new_clean_path)
# Checkpoint-related utilities
View
19 IPython/html/services/notebooks/tests/test_nbmanager.py
@@ -215,6 +215,25 @@ def test_save_notebook_with_script(self):
py_path = os.path.join(td, os.path.splitext(name)[0]+'.py')
assert os.path.exists(py_path), py_path
+ def test_save_notebook_with_clean(self):
+ with TemporaryDirectory() as td:
+ # Create a notebook
+ nm = FileNotebookManager(notebook_dir=td)
+ nm.save_clean = True
+ model = nm.create_notebook_model()
+ name = model['name']
+ path = model['path']
+
+ # Get the model with 'content'
+ full_model = nm.get_notebook_model(name, path)
+
+ # Save the notebook
+ model = nm.save_notebook_model(full_model, name, path)
+
+ # Check that the script was created
+ py_path = os.path.join(td, name+'.clean')
+ assert os.path.exists(py_path), py_path
+
def test_delete_notebook_model(self):
with TemporaryDirectory() as td:
# Test in the root directory

0 comments on commit f70e404

Please sign in to comment.
Something went wrong with that request. Please try again.