-
Notifications
You must be signed in to change notification settings - Fork 7
/
nbstripout
executable file
·69 lines (57 loc) · 1.85 KB
/
nbstripout
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
#!/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)