]> us-delaporte.pagekite.me Git - dotfiles.git/blob - util/jupyter_git_clean.py
IRC reminder
[dotfiles.git] / util / jupyter_git_clean.py
1 #!/usr/bin/env python
2
3 """
4 Clear outputs of IPython notebooks.
5
6 By default, it prints the notebooks without outputs into stdout.
7 When the --in-place option is given, all files will be overwritten.
8
9 From
10 https://github.com/ivanov/nbutils/blob/master/nbstrip.py
11
12 """
13
14 import sys
15
16 from IPython.nbformat import current as nbformat
17
18
19
20
21 def clear_outputs(nb):
22 """Clear output of notebook `nb` INPLACE."""
23 for ws in nb.worksheets:
24 for cell in ws.cells:
25 cell.outputs = []
26
27
28 def stripoutput(inputs, inplace=False):
29 """
30 Strip output of notebooks.
31
32 Parameters
33 ----------
34 inputs : list of string
35 Path to the notebooks to be processed.
36 inplace : bool
37 If this is `True`, outputs in the input files will be deleted.
38 Default is `False`.
39
40 """
41 for inpath in inputs:
42 with file(inpath) as fp:
43 nb = nbformat.read(fp, 'ipynb')
44 clear_outputs(nb)
45 if inplace:
46 with file(inpath, 'w') as fp:
47 nbformat.write(nb, fp, 'ipynb')
48 else:
49 nbformat.write(nb, sys.stdout, 'ipynb')
50
51
52 def main():
53 from argparse import ArgumentParser
54 parser = ArgumentParser(description=__doc__)
55 parser.add_argument('inputs', nargs='+', metavar='input',
56 help='Paths to notebook files.')
57 #XXX: TODO: handle alternative outputs here, such as to stdout or to file
58 parser.add_argument('-i', '--inplace', '--in-place', default=True,
59 action='store_true',
60 help='Overwrite existing notebook when given.')
61
62 args = parser.parse_args()
63 stripoutput(**vars(args))
64
65
66 if __name__ == '__main__':
67 main()