Permalink
Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
executable file 70 lines (57 sloc) 1.85 KB
#!/usr/bin/env python
"""strip outputs from an IPython Notebook
Opens a notebook, strips its output, and writes the outputless version to the
original file. Useful mainly as a git filter or pre-commit hook for users who
don't want to track output in VCS. This does mostly the same thing as the
`Clear All Output` command in the notebook UI.
"""
import sys
from io import StringIO
import codecs
py2 = True
if (sys.version_info > (3, 0)):
py2 = False
try:
# Jupyter >= 4
from nbformat import read, write, NO_CONVERT
except ImportError:
# IPython 3
try:
from IPython.nbformat import read, write, NO_CONVERT
except ImportError:
# IPython < 3
from IPython.nbformat import current
def read(f, as_version):
return current.read(f, 'json')
def write(nb, f):
return current.write(nb, f, 'json')
def _cells(nb):
"""Yield all cells in an nbformat-insensitive manner"""
if nb.nbformat < 4:
for ws in nb.worksheets:
for cell in ws.cells:
yield cell
else:
for cell in nb.cells:
yield cell
def strip_output(nb):
"""strip the outputs from a notebook object"""
nb.metadata.pop('signature', None)
for cell in _cells(nb):
if 'outputs' in cell:
cell['outputs'] = []
if 'prompt_number' in cell:
cell['prompt_number'] = 0
if 'execution_count' in cell:
cell['execution_count'] = 0
if 'metadata' in cell and 'ExecuteTime' in cell['metadata']:
cell['metadata']['ExecuteTime'] = {}
return nb
if __name__ == '__main__':
nb = None
if py2:
UTF8Reader = codecs.getreader('utf8')
sys.stdin = UTF8Reader(sys.stdin)
nb = read(StringIO(sys.stdin.read()), as_version=NO_CONVERT)
nb = strip_output(nb)
write(nb, sys.stdout)