forked from ivanov/nbutils
/
nbrun.py
executable file
·331 lines (288 loc) · 11 KB
/
nbrun.py
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
#!/usr/bin/env python
# from https://gist.github.com/2620735
"""
simple example script for running and testing notebooks.
Usage: `ipnbdoctest.py foo.ipynb [bar.ipynb [...]]`
Each cell is submitted to the kernel, and the outputs are compared with those stored in the notebook.
"""
import os,sys,time
import base64
import re
from collections import defaultdict
from Queue import Empty
from IPython.zmq.blockingkernelmanager import BlockingKernelManager
from IPython.nbformat.current import reads, writes, NotebookNode
import IPython.nbformat.current as cur
import logging
logging.basicConfig(format='%(message)s')
log = logging.getLogger(os.path.basename(__file__))
def compare_png(a64, b64):
"""compare two b64 PNGs (incomplete)"""
try:
import Image
except ImportError:
pass
adata = base64.decodestring(a64)
bdata = base64.decodestring(b64)
return True
def sanitize(s):
"""sanitize a string for comparison.
fix universal newlines, strip trailing newlines, and normalize likely random values (memory addresses and UUIDs)
"""
# normalize newline:
s = s.replace('\r\n', '\n')
# ignore trailing newlines (but not space)
s = s.rstrip('\n')
# normalize hex addresses:
s = re.sub(r'0x[a-f0-9]+', '0xFFFFFFFF', s)
# normalize UUIDs:
s = re.sub(r'[a-f0-9]{8}(\-[a-f0-9]{4}){3}\-[a-f0-9]{12}', 'U-U-I-D', s)
return s
def consolidate_outputs(outputs):
"""consolidate outputs into a summary dict (incomplete)"""
data = defaultdict(list)
data['stdout'] = ''
data['stderr'] = ''
for out in outputs:
if out.type == 'stream':
data[out.stream] += out.text
elif out.type == 'pyerr':
data['pyerr'] = dict(ename=out.ename, evalue=out.evalue)
else:
for key in ('png', 'svg', 'latex', 'html', 'javascript', 'text', 'jpeg',):
if key in out:
data[key].append(out[key])
return data
def compare_outputs(test, ref, skip_compare=('png', 'traceback', 'latex', 'prompt_number')):
for key in ref:
if key not in test:
log.info("missing key: %s != %s" % (test.keys(), ref.keys()))
return False
elif key not in skip_compare and sanitize(test[key]) != sanitize(ref[key]):
log.info("mismatch %s:" % key)
log.info(test[key])
log.info(' != ')
log.info(ref[key])
return False
return True
def get_child_msg(km, msg_id):
while True:
# get_msg will raise with Empty exception if no messages arrive in 1
# second
m= km.shell_channel.get_msg()
if m['parent_header']['msg_id'] == msg_id:
break
else:
#got a message, but not the one we were looking for
print "SKIPPING:" + str(m['content'])
return m
def run_cell(km, cell):
shell = km.shell_channel
iopub = km.sub_channel
# print "\n\ntesting:"
# print cell.input
msg_id = shell.execute(cell.input)
# wait for finish, no maximum
msg = get_child_msg(km, msg_id)
execution_count = msg['content']['execution_count']
outs = []
while True:
try:
msg = iopub.get_msg(timeout=0.2)
except Empty:
break
msg_type = msg['msg_type']
if msg_type in ('status', 'pyin'):
continue
elif msg_type == 'clear_output':
outs = []
continue
content = msg['content']
# print msg_type, content
out = NotebookNode(output_type=msg_type)
if msg_type == 'stream':
out.stream = content['name']
out.text = content['data']
elif msg_type in ('display_data', 'pyout'):
for mime, data in content['data'].iteritems():
attr = mime.split('/')[-1].lower()
# this gets most right, but fix svg+html, plain
attr = attr.replace('+xml', '').replace('plain', 'text')
setattr(out, attr, data)
if msg_type == 'pyout':
out.prompt_number = content['execution_count']
elif msg_type == 'pyerr':
out.ename = content['ename']
out.evalue = content['evalue']
out.traceback = content['traceback']
else:
print "unhandled iopub msg:", msg_type
outs.append(out)
return outs, execution_count
def test_notebook(nb, halt_on_error=True, km=None):
our_kernel = km is None
if our_kernel:
km = BlockingKernelManager()
km.start_kernel(extra_arguments=['--pylab=inline'], stderr=open(os.devnull, 'w'))
km.start_channels()
print km.connection_file
# run %pylab inline, because some notebooks assume this
# even though they shouldn't
km.shell_channel.execute("pass")
km.shell_channel.get_msg()
km.restart_kernel()
km.shell_channel.get_msg()
while True:
try:
km.sub_channel.get_msg(timeout=1)
except Empty:
break
successes = 0
failures = 0
errors = 0
halted = False
for ws in nb.worksheets:
for cell in ws.cells:
if cell.cell_type != 'code':
continue
try:
outs, exec_count = run_cell(km, cell)
except Exception as e:
log.critical( "failed to run cell:"+ repr(e))
log.critical("tested notebook %s" % nb.metadata.name)
print cell.input
errors += 1
continue
c = '.'
for out in outs:
if out['output_type'] == 'pyerr':
c = 'E'
if log.getEffectiveLevel() < logging.FATAL:
sys.stderr.write(c)
failed = False
#for out, ref in zip(outs, cell.outputs):
# if not compare_outputs(out, ref):
# failed = True
if failed:
failures += 1
else:
successes += 1
cell.outputs = outs
cell.prompt_number = exec_count
if c == 'E' and halt_on_error:
log.info("halting on error")
halted = True
# XXX: this next part is specific to nbexplode
save_intermediate(km, ws, cell, nb.metadata.name)
break;
if log.getEffectiveLevel() <= logging.WARNING:
sys.stderr.write('\n')
log.info("tested notebook %s" % nb.metadata.name)
log.info(" %3i cells successfully replicated" % successes)
if failures:
log.info(" %3i cells mismatched output" % failures)
if errors:
log.info(" %3i cells failed to complete" % errors)
if our_kernel:
km.shutdown_kernel()
del km
return nb, halted
def save_intermediate(km, ws, cell, save_name=None):
"""
Conditionally save __save__ variables on error, and perhaps add a cell to
load them up again into the worksheet.
This will be utilized via a command-line flag.
"""
saving_tmpl = """#error happend here, execute this cell to reload state
_load = False
_name = '%s'
if '__save__' in locals():
d = {}
for k in __save__:
try:
d[k] = locals()[k]
# for things that are meant to be saved but that haven't executed yet
except KeyError:
d[k] = None
np.savez(_name, **d)
print "saved " + _name + '.npz'
if _load:
loaded = np.load(_name+'.npz')
print loaded.keys(), "now injected into this namespace"
locals().update(loaded)
"""
if not save_name:
save_name = ''
save_name += '_error'
save_cell = cur.new_code_cell(saving_tmpl%save_name,"-1")
if hasattr(km, 'saveonerror') and km.saveonerror:
idx = ws.cells.index(cell)
outs, exec_count = run_cell(km, save_cell)
save_cell.outputs = outs
# XXX: the problem with this approach is that after the first error,
# the whole notebook must be regenerated in order to not have this
# saving code in it
ws.cells.insert(idx+1, save_cell)
pass
if __name__ == '__main__':
from argparse import ArgumentParser
parser = ArgumentParser(description=__doc__)
parser.add_argument('inputs', nargs='+', metavar='input',
help='Paths to notebook files.')
parser.add_argument('-i', '--inplace', '--in-place', default=False,
action='store_true',
help='Overwrite existing notebook when given.')
parser.add_argument('-p', '--prefix', default='',
help='Path for the destination of converted output')
parser.add_argument('-v', '--verbose', default=False, action='store_true',
help='be verbose about cells comparisons')
parser.add_argument('-q', '--quiet', default=False, action='store_true',
help='be verbose about cells comparisons')
parser.add_argument('-O', '--stdout', default=False, action='store_true',
help='Print converted output instead of sending it to a file')
parser.add_argument('-a', '--all', '--all-cells', default=False,
action='store_true',
help="Try to run all cells (by default will halt on first error)")
parser.add_argument('-s', '--saveonerror', '--save-on-error',
default=False, action='store_true',
help="Try to run all cells (by default will halt on first error)")
parser.add_argument('-A', '--allnotebooks', '--all-notebooks',
default=False, action='store_true',
help="Try to run all notebook (by default will halt on first error)")
args = parser.parse_args()
if args.verbose:
log.setLevel(logging.INFO)
if args.quiet:
log.setLevel(logging.CRITICAL)
km = BlockingKernelManager()
km.start_kernel(extra_arguments=['--pylab=inline'], stderr=open(os.devnull, 'w'))
km.start_channels()
if args.saveonerror:
# XXX: hack - just dange an attribute we can check against
km.saveonerror = True
halt_on_error = not args.all
halt_notebooks = not args.allnotebooks
for ipynb in args.inputs:
log.info('Running '+ ipynb)
with open(ipynb) as f:
nb = reads(f.read(), 'json')
# here, before running the notebook, it'd be nice if we verified it's
# metadata.name, and adjusted it according to the current filename, so
# let's do that
nb.metadata.name = os.path.basename(os.path.splitext(ipynb)[0])
output_nb, halted = test_notebook(nb, halt_on_error, km)
nb_as_json = writes(output_nb, 'json')
if args.stdout:
sys.stdout.write(nb_as_json)
else:
outfile = args.prefix+ipynb
with open(outfile, 'w') as f:
f.write(nb_as_json)
if log.getEffectiveLevel() < logging.CRITICAL:
print outfile
log.info("Wrote file " + outfile)
if halted and halt_notebooks:
break
km.shutdown_kernel()
del km
sys.exit(halted and halt_notebooks)