udibr

Command line for cleaning the cells of an ipython notebook

Once in a while I have an ipython notebook that has so much stuff written into its output cells that it takes forever to open it in the browser. In some cases the browser crash, blocking me from reaching the menu option to clear all the cells in the notebook.

I therefore wrote this code to clear the output of all the cells (and the prompt numbers.) With it I can run the code as a command line before attempting to open the notebook from the ipython notebook server.

Code example:

clean_notebook.py download

import sys

if len(sys.argv) != 2:
	print "Usage: %s <file-name>"%sys.argv[0]
	exit(0)
fname = sys.argv[1]

import json

with open(fname,'r') as fp:
    d = json.load(fp)

def filter(d):
    if isinstance(d,dict):
        d = dict((k,[] if k == 'outputs' else filter(v)) for k,v in d.iteritems() if k != 'prompt_number')
    elif isinstance(d,list):
        d = map(filter,d)
    return d

d = filter(d)

with open(fname, 'w') as fp:
    json.dump(d, fp, sort_keys=True, indent=4, separators=(',', ': '))

Comments