1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
|
#!/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.
LICENSE: Public Domain
From https://gist.github.com/minrk/6176788
ls docs/source/examples/*.ipynb | xargs -I {} ./scripts/strip_examples.py "{}"
After running this on the examples, re-run the outputs on:
Using Interact.ipynb
Output Widget.ipynb
Image Browser.ipynb
Widget Basics.ipynb
Beat Frequencies.ipynb
Lorenz Differential Equations.ipynb
Widget Events.ipynb
Export As (nbconvert).ipynb
Exploring Graphs.ipynb
Image Processing.ipynb
Widget List.ipynb
Widget Styling.ipynb
Widget Low Level.ipynb
Factoring.ipynb
Widget Alignment.ipynb
"""
import io
import sys
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:
yield from ws.cells
else:
yield from nb.cells
def strip_output(nb):
"""strip the outputs from a notebook object"""
nb.metadata.pop('signature', None)
nb.metadata.pop('widgets', None)
for cell in _cells(nb):
if 'outputs' in cell:
cell['outputs'] = []
if 'prompt_number' in cell:
cell['prompt_number'] = None
return nb
if __name__ == '__main__':
filename = sys.argv[1]
with open(filename, 'r', encoding='utf8') as f:
nb = read(f, as_version=NO_CONVERT)
nb = strip_output(nb)
with open(filename, 'w', encoding='utf8') as f:
write(nb, f)
|