本文整理汇总了Python中IPython.nbformat.current.NotebookNode类的典型用法代码示例。如果您正苦于以下问题:Python NotebookNode类的具体用法?Python NotebookNode怎么用?Python NotebookNode使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了NotebookNode类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_add_score_output_text
def test_add_score_output_text(self):
"""Is the score properly handled when the cell is a markdown cell?"""
cell = NotebookNode()
cell.cell_type = 'markdown'
cell.outputs = []
self.preprocessor._add_score_output(cell, 10, 15)
assert cell['outputs'] == []
示例2: test_add_score_output
def test_add_score_output(self):
"""Is the score properly formatted and added to the cell outputs?"""
cell = NotebookNode()
cell.cell_type = 'code'
cell.outputs = []
self.preprocessor._add_score_output(cell, 10, 15)
output = cell.outputs[0]
assert output.stream == "stdout"
assert output.output_type == "stream"
assert output.text == "Score: 10 / 15"
示例3: run_cell
def run_cell(self, cell):
'''
Run a notebook cell and update the output of that cell in-place.
'''
logging.info('Running cell:\n%s\n', cell.input)
self.shell.execute(cell.input)
reply = self.shell.get_msg()
status = reply['content']['status']
if status == 'error':
logging.info('Cell raised uncaught exception: %s', reply['content']['ename'])
else:
logging.info('Cell returned')
outs = list()
while True:
try:
msg = self.iopub.get_msg(timeout=1)
if msg['msg_type'] == 'status':
if msg['content']['execution_state'] == 'idle':
break
except Empty:
# execution state should return to idle before the queue becomes empty,
# if it doesn't, something bad has happened
raise
content = msg['content']
msg_type = msg['msg_type']
out = NotebookNode(output_type=msg_type)
if 'execution_count' in content:
cell['prompt_number'] = content['execution_count']
out.prompt_number = content['execution_count']
if msg_type in ['status', 'pyin']:
continue
elif 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():
try:
attr = self.MIME_MAP[mime]
except KeyError:
raise NotImplementedError('unhandled mime type: %s' % mime)
setattr(out, attr, data)
elif msg_type == 'pyerr':
out.ename = content['ename']
out.evalue = content['evalue']
out.traceback = content['traceback']
logging.log('\n'.join(content['traceback']))
else:
raise NotImplementedError('unhandled iopub message: %s' % msg_type)
outs.append(out)
cell['outputs'] = outs
if status == 'error':
raise NotebookError()
示例4: test_preprocess_code_cell_solution
def test_preprocess_code_cell_solution(self):
"""Is the solution version of a code cell correctly preprocessed?"""
self.preprocessor.solution = True
self.preprocessor.toc = ""
cell = self._create_code_cell()
self.preprocessor._create_client()
cell, resources = self.preprocessor.preprocess_cell(cell, {}, 1)
self.preprocessor._shutdown_client()
output = NotebookNode()
output.stream = "stdout"
output.text = "hello\n"
output.output_type = "stream"
assert cell.input == """# YOUR CODE HERE\nprint "hello\""""
assert cell.outputs == [output]
assert cell.prompt_number == 1
示例5: run_cell
def run_cell(shell, iopub, cell, output=False):
shell.execute(cell.input)
#shell.get_msg() # timeout=20
outs = []
while True:
try:
msg = iopub.get_msg(timeout=0.1)
except Empty:
continue
msg_type = msg['msg_type']
if msg_type == 'pyin':
continue
elif msg_type == 'clear_output':
outs = []
continue
elif msg_type == 'status':
if msg['content']['execution_state'] == 'idle':
break
else:
outs = []
continue
content = msg['content']
out = NotebookNode(output_type=msg_type)
if msg_type == 'stream':
out.stream = content['name']
out.text = content['data']
if output:
print(out.texti)#, end="")
elif msg_type in ('display_data', 'pyout'):
out['metadata'] = content['metadata']
for mime, data in content['data'].items():
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:
log.error("Unhandled iopub msg : ", msg_type)
outs.append(out)
return outs
示例6: _process_execute_error
def _process_execute_error(self, msg):
""" Process a reply for an execution request that resulted in an error.
"""
content = msg['content']
# If a SystemExit is passed along, this means exit() was called - also
# all the ipython %exit magic syntax of '-k' to be used to keep
# the kernel running
if content['ename']=='SystemExit':
keepkernel = content['evalue']=='-k' or content['evalue']=='True'
self._keep_kernel_on_exit = keepkernel
self.exit_requested.emit(self)
else:
traceback = ''.join(content['traceback'])
logging.error(traceback)
out = NotebookNode(output_type='pyerr')
out.ename = content['ename']
out.evalue = content['evalue']
out.traceback = content['traceback']
self._current_cell['outputs'].append(out)
self.run_notebook_completed(error=True, traceback=content['traceback'])
示例7: run_cell
def run_cell(kc, cell):
shell = kc.shell_channel
iopub = kc.iopub_channel
outputs = []
shell.execute(cell.input)
# wait for finish, maximum 20s
try:
shell.get_msg(timeout=10)
except Empty:
return outputs
failures = 0
messages = 0
while True:
try:
reply = iopub.get_msg(timeout=0.2)
messages += 1
except Empty:
break
content = reply["content"]
msg_type = reply["msg_type"]
if msg_type in ("status", "pyin"):
continue
elif msg_type == "clear_output":
outputs = []
continue
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
outputs.append(out)
return outputs
示例8: run_cell
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
示例9: run_cell
def run_cell(self, shell, iopub, cell, exec_count):
outs = []
shell.execute(cell.input)
# hard-coded timeout, problem?
shell.get_msg(timeout=90)
cell.prompt_number = exec_count # msg["content"]["execution_count"]
while True:
try:
# whats the assumption on timeout here?
# is it asynchronous?
msg = iopub.get_msg(timeout=.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"]
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 = exec_count #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
示例10: run
def run(self, cell, timeout = None):
use_timeout = self.default_timeout
if timeout is not None:
use_timeout = timeout
self.shell.execute(cell.input)
self.shell.get_msg(timeout=use_timeout)
outs = []
while True:
try:
msg = self.iopub.get_msg(timeout=0.5)
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']
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'):
out['metadata'] = content['metadata']
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
示例11: run_cell
def run_cell(shell, iopub, cell):
# print cell.input
shell.execute(cell.input)
# wait for finish, maximum 20s
shell.get_msg(timeout=30)
outs = []
while True:
try:
msg = iopub.get_msg(timeout=0.2)
except queue.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"):
out["metadata"] = content["metadata"]
for mime, data in content["data"].items():
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
示例12: run_cell
def run_cell(km, cell, timeout=20):
shell = km.shell_channel
iopub = km.iopub_channel
shell.execute(cell.input)
shell.get_msg(timeout=timeout)
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']
out = NotebookNode(output_type=msg_type)
if msg_type == 'stream':
out.stream = content['name']
out.txt = content['data']
elif msg_type in ('display_data', 'pyout'):
for mime, data in content['data'].items():
attr = mime.split('/')[-1].lower()
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)
cell.outputs = outs
return outs
示例13: run_cell
def run_cell(shell, iopub, cell):
stime = time.time()
shell.execute(cell.input)
# wait for finish or timeout (in seconds)
shell.get_msg(timeout=120)
outs = []
elapsedtime = time.time() - stime
print ' %.2f sec | cell done.\n%s' % (elapsedtime, str(cell.input)[:50])
while True:
try:
msg = iopub.get_msg(timeout=1.0)
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']
#TODO: need to find better workaround
pass
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
示例14: run_cell
def run_cell(shell, iopub, cell):
shell.execute(cell.input)
# wait for finish, maximum 20s
shell.get_msg(timeout=20)
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']
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'):
out['metadata'] = content['metadata']
for mime, data in content['data'].items():
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']
elif msg_type not in ('comm_msg', 'comm_open'):
print("unhandled iopub msg:", msg_type)
outs.append(out)
return outs
示例15: poll_for_msgs
def poll_for_msgs(self):
"""Polls for messages from the kernel.
Used after submitting code for execution"""
try:
msg = self.iopub.get_msg(timeout=1)
if msg['msg_type'] == 'status' and msg['content']['execution_state'] == 'idle':
if _debugging: logging.info('Message -- {}:{}'.format(msg['msg_type'], msg['content']))
self._previous_status = 'IDLE'
return NotebookNode(output_type = 'IDLE')
except Empty: # state should return to idle before queue becomes empty, but we ignore it now
prevstat, self._previous_status = self._previous_status, 'EMPTY'
retstat = 'END_CELL' if prevstat == 'IDLE' else 'EMPTY'
# Assuming IDLE followed by EMPTY is the end-of-cell
return NotebookNode(output_type = retstat)
self._previous_status = '' # Not idle, that's all we are concerned about for now
content, msg_type = msg['content'], msg['msg_type']
if msg_type in ['status', 'pyin']: return NotebookNode(output_type = 'NoOp')
out = NotebookNode(output_type = msg_type)
if msg_type in ('display_data', 'pyout'):
for mime, data in content['data'].items():
try:
attr = self.MIME_MAP[mime]
tmpval = RClansiconv(data) if attr == 'text' else data
setattr(out, attr, tmpval)
except KeyError:
raise NotImplementedError('unhandled mime type: %s' % mime)
elif msg_type == 'stream':
setattr(out, 'text', RClansiconv(content['data']))
elif msg_type == 'pyerr':
setattr(out, 'html', RClansiconv('\n'.join(content['traceback']) + '\n'))
else:
if _debugging: logging.info('Unsupported: ' + msg_type)
raise NotImplementedError('unhandled iopub message: %s' % msg_type)
if _debugging: logging.info('Sending: msg_type: [{}]; HTML: [{}]; TEXT: [{}]'.format(msg_type, out.get('html', ''), out.get('text', '') ))
return out # upstream process will handle it [e.g. send as an oob message]