def execute_request(self, ident, parent): try: code = parent[u'content'][u'code'] except: print("Got bad msg: ", file=sys.__stderr__) print(Message(parent), file=sys.__stderr__) return pyin_msg = self.session.msg(u'pyin',{u'code':code}, parent=parent) self.pub_socket.send_json(pyin_msg) try: # comp_code = self.compiler(code, '<zmq-kernel>') sys.displayhook.set_parent(parent) exec (code, self.user_ns) # FIXME except: result = u'error' etype, evalue, tb = sys.exc_info() tb = traceback.format_exception(etype, evalue, tb) exc_content = { u'status' : u'error', u'traceback' : tb, u'etype' : str(etype), u'evalue' : str(evalue) } exc_msg = self.session.msg(u'pyerr', exc_content, parent) self.pub_socket.send_json(exc_msg) reply_content = exc_content else: reply_content = {'status' : 'ok'} reply_msg = self.session.msg(u'execute_reply', reply_content, parent) print(Message(reply_msg),file=sys.__stdout__) self.reply_socket.send(ident, zmq.SNDMORE) self.reply_socket.send_json(reply_msg) if reply_msg['content']['status'] == u'error': self.abort_queue()
def execute_request(self, ident, parent): try: code = parent[u'content'][u'code'] except: self.log.error("Got bad msg: %s" % Message(parent)) return pyin_msg = self.session.send(self.iopub_socket, u'pyin', {u'code': code}, parent=parent) try: comp_code = self.compiler(code, '<zmq-kernel>') # Replace raw_input. Note that is not sufficient to replace # raw_input in the user namespace. raw_input = lambda prompt='': self._raw_input( prompt, ident, parent) __builtin__.raw_input = raw_input # Set the parent message of the display hook and out streams. sys.displayhook.set_parent(parent) sys.stdout.set_parent(parent) sys.stderr.set_parent(parent) exec comp_code in self.user_ns, self.user_ns except: etype, evalue, tb = sys.exc_info() tb = traceback.format_exception(etype, evalue, tb) exc_content = { u'status': u'error', u'traceback': tb, u'ename': unicode(etype.__name__), u'evalue': unicode(evalue) } exc_msg = self.session.send(self.iopub_socket, u'pyerr', exc_content, parent) reply_content = exc_content else: reply_content = {'status': 'ok', 'payload': {}} # Flush output before sending the reply. sys.stderr.flush() sys.stdout.flush() # FIXME: on rare occasions, the flush doesn't seem to make it to the # clients... This seems to mitigate the problem, but we definitely need # to better understand what's going on. if self._execute_sleep: time.sleep(self._execute_sleep) # Send the reply. reply_msg = self.session.send(self.shell_socket, u'execute_reply', reply_content, parent, ident=ident) self.log.debug(Message(reply_msg)) if reply_msg['content']['status'] == u'error': self._abort_queue()
def execute_request(self, ident, parent): try: code = parent[u'content'][u'code'] except: print >> sys.__stderr__, "Got bad msg: " print >> sys.__stderr__, Message(parent) return pyin_msg = self.session.send(self.pub_socket, u'pyin', {u'code': code}, parent=parent) try: comp_code = self.compiler(code, '<zmq-kernel>') # Replace raw_input. Note that is not sufficient to replace # raw_input in the user namespace. raw_input = lambda prompt='': self._raw_input( prompt, ident, parent) __builtin__.raw_input = raw_input # Set the parent message of the display hook and out streams. sys.displayhook.set_parent(parent) sys.stdout.set_parent(parent) sys.stderr.set_parent(parent) exec comp_code in self.user_ns, self.user_ns except: etype, evalue, tb = sys.exc_info() tb = traceback.format_exception(etype, evalue, tb) exc_content = { u'status': u'error', u'traceback': tb, u'ename': unicode(etype.__name__), u'evalue': unicode(evalue) } exc_msg = self.session.send(self.pub_socket, u'pyerr', exc_content, parent) reply_content = exc_content else: reply_content = {'status': 'ok', 'payload': {}} # Flush output before sending the reply. sys.stderr.flush() sys.stdout.flush() # Send the reply. reply_msg = self.session.send(self.reply_socket, u'execute_reply', reply_content, parent, ident=ident) print >> sys.__stdout__, Message(reply_msg) if reply_msg['content']['status'] == u'error': self._abort_queue()
def _abort_queue(self): while True: ident,msg = self.session.recv(self.shell_socket, zmq.NOBLOCK) if msg is None: # msg=None on EAGAIN break else: assert ident is not None, "Missing message part." self.log.debug("Aborting: %s"%Message(msg)) msg_type = msg['header']['msg_type'] reply_type = msg_type.split('_')[0] + '_reply' reply_msg = self.session.send(self.shell_socket, reply_type, {'status':'aborted'}, msg, ident=ident) self.log.debug(Message(reply_msg)) # We need to wait a bit for requests to come in. This can probably # be set shorter for true asynchronous clients. time.sleep(0.1)
def _raw_input(self, prompt, ident, parent): # Flush output before making the request. sys.stderr.flush() sys.stdout.flush() # Send the input request. content = json_clean(dict(prompt=prompt)) self.session.send(self.stdin_socket, u'input_request', content, parent, ident=ident) # Await a response. while True: try: ident, reply = self.session.recv(self.stdin_socket, 0) except Exception: self.log.warn("Invalid Message:", exc_info=True) else: break try: value = reply['content']['value'] except: self.log.error("Got bad raw_input reply: ") self.log.error(str(Message(parent))) value = '' if value == '\x04': # EOF raise EOFError return value
def _abort_queue(self): while True: try: ident, msg = self.session.recv(self.reply_socket, zmq.NOBLOCK) except zmq.ZMQError, e: if e.errno == zmq.EAGAIN: break else: assert ident is not None, "Missing message part." print >> sys.__stdout__, "Aborting:" print >> sys.__stdout__, Message(msg) msg_type = msg['msg_type'] reply_type = msg_type.split('_')[0] + '_reply' reply_msg = self.session.send(self.reply_socket, reply_type, {'status': 'aborted'}, msg, ident=ident) print >> sys.__stdout__, Message(reply_msg) # We need to wait a bit for requests to come in. This can probably # be set shorter for true asynchronous clients. time.sleep(0.1)
def start(self): while True: ident = self.reply_socket.recv() assert self.reply_socket.rcvmore, "Unexpected missing message part." msg = self.reply_socket.recv_json() omsg = Message(msg) print(omsg, file=sys.__stdout__) handler = self.handlers.get(omsg.msg_type, None) if handler is None: print ("UNKNOWN MESSAGE TYPE:" + omsg, file=sys.__stderr__) else: handler(ident, omsg)
def abort_queue(self): while True: try: ident = self.reply_socket.recv(zmq.NOBLOCK) except zmq.ZMQError as e: if e.errno == zmq.EAGAIN: break else: assert self.reply_socket.rcvmore(), "Unexpected missing message part." msg = self.reply_socket.recv_json() print("Aborting:", file=sys.__stdout__) print(Message(msg), file=sys.__stdout__) msg_type = msg['msg_type'] reply_type = msg_type.split('_')[0] + '_reply' reply_msg = self.session.msg(reply_type, {'status' : 'aborted'}, msg) print(Message(reply_msg),file=sys.__stdout__) self.reply_socket.send(ident,zmq.SNDMORE) self.reply_socket.send_json(reply_msg) # We need to wait a bit for requests to come in. This can probably # be set shorter for true asynchronous clients. time.sleep(0.1)
def flush(self): if self.pub_socket is None: raise ValueError(u'I/O operation on closed file') else: if self._buffer: data = ''.join(self._buffer) content = {u'name':self.name, u'data':data} msg = self.session.msg(u'stream', content=content, parent=self.parent_header) print (Message(msg), file=sys.__stdout__) self.pub_socket.send_json(msg) self._buffer_len = 0 self._buffer = []
def start(self): """ Start the kernel main loop. """ while True: ident, msg = self.session.recv(self.shell_socket, 0) assert ident is not None, "Missing message part." omsg = Message(msg) self.log.debug(str(omsg)) handler = self.handlers.get(omsg.msg_type, None) if handler is None: self.log.error("UNKNOWN MESSAGE TYPE: %s" % omsg) else: handler(ident, omsg)
def start(self): """ Start the kernel main loop. """ while True: ident, msg = self.session.recv(self.reply_socket, 0) assert ident is not None, "Missing message part." omsg = Message(msg) print >> sys.__stdout__ print >> sys.__stdout__, omsg handler = self.handlers.get(omsg.msg_type, None) if handler is None: print >> sys.__stderr__, "UNKNOWN MESSAGE TYPE:", omsg else: handler(ident, omsg)
def start(self): """ Start the kernel main loop. """ while True: ident = self.reply_socket.recv() assert self.reply_socket.rcvmore(), "Missing message part." msg = self.reply_socket.recv_json() omsg = Message(msg) print >> sys.__stdout__ print >> sys.__stdout__, omsg handler = self.handlers.get(omsg.msg_type, None) if handler is None: print >> sys.__stderr__, "UNKNOWN MESSAGE TYPE:", omsg else: handler(ident, omsg)
def _raw_input(self, prompt, ident, parent): # Flush output before making the request. sys.stderr.flush() sys.stdout.flush() # Send the input request. content = dict(prompt=prompt) msg = self.session.send(self.stdin_socket, u'input_request', content, parent, ident=ident) # Await a response. ident,reply = self.session.recv(self.stdin_socket, 0) try: value = reply['content']['value'] except: self.log.error("Got bad raw_input reply: %s"%Message(parent)) value = '' return value
def _abort_queue(self): while True: ident,msg = self.session.recv(self.reply_socket, zmq.NOBLOCK) if msg is None: break else: assert ident is not None, \ "Unexpected missing message part." logger.debug("Aborting:\n"+str(Message(msg))) msg_type = msg['msg_type'] reply_type = msg_type.split('_')[0] + '_reply' reply_msg = self.session.send(self.reply_socket, reply_type, {'status' : 'aborted'}, msg, ident=ident) logger.debug(reply_msg) # We need to wait a bit for requests to come in. This can probably # be set shorter for true asynchronous clients. time.sleep(0.1)
def _raw_input(self, prompt, ident, parent): # Flush output before making the request. sys.stderr.flush() sys.stdout.flush() # Send the input request. content = dict(prompt=prompt) msg = self.session.msg(u'input_request', content, parent) self.req_socket.send_json(msg) # Await a response. reply = self.req_socket.recv_json() try: value = reply['content']['value'] except: print >> sys.__stderr__, "Got bad raw_input reply: " print >> sys.__stderr__, Message(parent) value = '' return value
def _abort_queue(self): while True: try: ident,msg = self.session.recv(self.shell_socket, zmq.NOBLOCK) except Exception: self.log.warn("Invalid Message:", exc_info=True) continue if msg is None: break else: assert ident is not None, \ "Unexpected missing message part." self.log.debug("Aborting:\n"+str(Message(msg))) msg_type = msg['header']['msg_type'] reply_type = msg_type.split('_')[0] + '_reply' reply_msg = self.session.send(self.shell_socket, reply_type, {'status' : 'aborted'}, msg, ident=ident) self.log.debug(reply_msg) # We need to wait a bit for requests to come in. This can probably # be set shorter for true asynchronous clients. time.sleep(0.1)
def execute_request(self, ident, parent): self.session.send(self.iopub_socket, u'status', {u'execution_state': u'busy'}, parent=parent) try: content = parent[u'content'] code = content[u'code'] silent = content[u'silent'] except: self.log.error("Got bad msg: ") self.log.error(str(Message(parent))) return shell = self.shell # we'll need this a lot here # Replace raw_input. Note that is not sufficient to replace # raw_input in the user namespace. if content.get('allow_stdin', False): raw_input = lambda prompt='': self._raw_input( prompt, ident, parent) else: raw_input = lambda prompt='': self._no_raw_input() if py3compat.PY3: __builtin__.input = raw_input else: __builtin__.raw_input = raw_input # Set the parent message of the display hook and out streams. shell.displayhook.set_parent(parent) shell.display_pub.set_parent(parent) sys.stdout.set_parent(parent) sys.stderr.set_parent(parent) # Re-broadcast our input for the benefit of listening clients, and # start computing output if not silent: self._publish_pyin(code, parent) reply_content = {} try: if silent: # run_code uses 'exec' mode, so no displayhook will fire, and it # doesn't call logging or history manipulations. Print # statements in that code will obviously still execute. shell.run_code(code) else: # FIXME: the shell calls the exception handler itself. shell.run_cell(code, store_history=True) except: status = u'error' # FIXME: this code right now isn't being used yet by default, # because the run_cell() call above directly fires off exception # reporting. This code, therefore, is only active in the scenario # where runlines itself has an unhandled exception. We need to # uniformize this, for all exception construction to come from a # single location in the codbase. etype, evalue, tb = sys.exc_info() tb_list = traceback.format_exception(etype, evalue, tb) reply_content.update(shell._showtraceback(etype, evalue, tb_list)) else: status = u'ok' reply_content[u'status'] = status # Return the execution counter so clients can display prompts reply_content['execution_count'] = shell.execution_count - 1 # FIXME - fish exception info out of shell, possibly left there by # runlines. We'll need to clean up this logic later. if shell._reply_content is not None: reply_content.update(shell._reply_content) # reset after use shell._reply_content = None # At this point, we can tell whether the main code execution succeeded # or not. If it did, we proceed to evaluate user_variables/expressions if reply_content['status'] == 'ok': reply_content[u'user_variables'] = \ shell.user_variables(content[u'user_variables']) reply_content[u'user_expressions'] = \ shell.user_expressions(content[u'user_expressions']) else: # If there was an error, don't even try to compute variables or # expressions reply_content[u'user_variables'] = {} reply_content[u'user_expressions'] = {} # Payloads should be retrieved regardless of outcome, so we can both # recover partial output (that could have been generated early in a # block, before an error) and clear the payload system always. reply_content[u'payload'] = shell.payload_manager.read_payload() # Be agressive about clearing the payload because we don't want # it to sit in memory until the next execute_request comes in. shell.payload_manager.clear_payload() # Flush output before sending the reply. sys.stdout.flush() sys.stderr.flush() # FIXME: on rare occasions, the flush doesn't seem to make it to the # clients... This seems to mitigate the problem, but we definitely need # to better understand what's going on. if self._execute_sleep: time.sleep(self._execute_sleep) # Send the reply. reply_content = json_clean(reply_content) reply_msg = self.session.send(self.shell_socket, u'execute_reply', reply_content, parent, ident=ident) self.log.debug(str(reply_msg)) if reply_msg['content']['status'] == u'error': self._abort_queue() self.session.send(self.iopub_socket, u'status', {u'execution_state': u'idle'}, parent=parent)