public
Last active

run and validate a notebook

  • Download Gist
checkipnb.py
Python
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
#!/usr/bin/env python
"""
simple example script for running notebooks and reporting exceptions.
 
Usage: `checkipnb.py foo.ipynb [bar.ipynb [...]]`
 
Each cell is submitted to the kernel, and checked for errors.
"""
 
import os,sys,time
 
from Queue import Empty
 
try:
from IPython.kernel import KernelManager
except ImportError:
from IPython.zmq.blockingkernelmanager import BlockingKernelManager as KernelManager
 
from IPython.nbformat.current import reads, NotebookNode
 
def run_notebook(nb):
km = KernelManager()
km.start_kernel(stderr=open(os.devnull, 'w'))
try:
kc = km.client()
except AttributeError:
# 0.13
kc = km
kc.start_channels()
shell = kc.shell_channel
# simple ping:
shell.execute("pass")
shell.get_msg()
cells = 0
failures = 0
for ws in nb.worksheets:
for cell in ws.cells:
if cell.cell_type != 'code':
continue
shell.execute(cell.input)
# wait for finish, maximum 20s
reply = shell.get_msg(timeout=20)['content']
if reply['status'] == 'error':
failures += 1
print "\nFAILURE:"
print cell.input
print '-----'
print "raised:"
print '\n'.join(reply['traceback'])
cells += 1
sys.stdout.write('.')
 
print
print "ran notebook %s" % nb.metadata.name
print " ran %3i cells" % cells
if failures:
print " %3i cells raised exceptions" % failures
kc.stop_channels()
km.shutdown_kernel()
del km
 
if __name__ == '__main__':
for ipynb in sys.argv[1:]:
print "running %s" % ipynb
with open(ipynb) as f:
nb = reads(f.read(), 'json')
run_notebook(nb)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.