Skip to content

Instantly share code, notes, and snippets.

@hensing
Last active November 13, 2015 12:29
Show Gist options
  • Save hensing/d225617754bef4082012 to your computer and use it in GitHub Desktop.
Save hensing/d225617754bef4082012 to your computer and use it in GitHub Desktop.
[git/ipynb/nbformat] filter / clear output of ipython notebooks on git commit
*.ipynb filter=filter_notebook
# add this to .git/config
[filter "filter_notebook"]
clean = "./filter_notebook"
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
clears all cells of an ipython notebook
given via stdin
by H.Dickten 2014
"""
import sys
try:
import nbformat
except ImportError:
sys.exit(1)
NBVERSION = 4
def clear_outputs(notebook, clear_prompt_numbers=True):
"""
clears the output of all cells in an ipython notebook
Parameters:
===========
clear_promt_numbers: bool, optional
clears the prompt numbers of all cells
(default: True)
"""
for cell in notebook.cells:
if cell.get('cell_type', None) == 'code':
cell.outputs = []
if clear_prompt_numbers is True:
cell.execution_count = None
cell.pop('prompt_number', None)
return notebook
if __name__ == '__main__':
if len(sys.argv) > 1:
INFILE = sys.argv[1]
else:
INFILE = sys.stdin
if len(sys.argv) > 2:
OUTFILE = open(sys.argv[2], 'w')
else:
OUTFILE = sys.stdout
NB = nbformat.read(fp=INFILE, as_version=NBVERSION)
NB = clear_outputs(NB)
NBS = nbformat.writes(NB, version=NBVERSION).encode('utf-8')
OUTFILE.write(NBS)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment