def km_from_string(s = PMX_IPYTHON_CONNECTION): """create kernel manager from IPKernelApp string such as '--shell=47378 --iopub=39859 --stdin=36778 --hb=52668' for IPython 0.11 or just 'kernel-12345.json' for IPython 0.12 """ from os.path import join as pjoin from IPython.zmq.blockingkernelmanager import BlockingKernelManager from IPython.config.loader import KeyValueConfigLoader from IPython.zmq.kernelapp import kernel_aliases s = s.replace('--existing', '') if 'connection_file' in BlockingKernelManager.class_trait_names(): from IPython.lib.kernel import find_connection_file # 0.12 uses files instead of a collection of ports # include default IPython search path # filefind also allows for absolute paths, in which case the search # is ignored try: # XXX: the following approach will be brittle, depending on what # connection strings will end up looking like in the future, and # whether or not they are allowed to have spaces. I'll have to sync # up with the IPython team to address these issues -pi if '--profile' in s: k,p = s.split('--profile') k = k.lstrip().rstrip() # kernel part of the string p = p.lstrip().rstrip() # profile part of the string fullpath = find_connection_file(k,p) else: fullpath = find_connection_file(s.lstrip().rstrip()) except IOError,e: print ":IPython " + s + " failed", "Info" print "^-- failed '" + s + "' not found", "Error" return km = BlockingKernelManager(connection_file = fullpath) km.load_connection_file()
def init_connection_file(self): """find the connection file, and load the info if found. The current working directory and the current profile's security directory will be searched for the file if it is not given by absolute path. When attempting to connect to an existing kernel and the `--existing` argument does not match an existing file, it will be interpreted as a fileglob, and the matching file in the current profile's security dir with the latest access time will be used. After this method is called, self.connection_file contains the *full path* to the connection file, never just its name. """ if self.existing: try: cf = find_connection_file(self.existing) except Exception: self.log.critical( "Could not find existing kernel connection file %s", self.existing) self.exit(1) self.log.info("Connecting to existing kernel: %s" % cf) self.connection_file = cf else: # not existing, check if we are going to write the file # and ensure that self.connection_file is a full path, not just the shortname try: cf = find_connection_file(self.connection_file) except Exception: # file might not exist if self.connection_file == os.path.basename( self.connection_file): # just shortname, put it in security dir cf = os.path.join(self.profile_dir.security_dir, self.connection_file) else: cf = self.connection_file self.connection_file = cf # should load_connection_file only be used for existing? # as it is now, this allows reusing ports if an existing # file is requested try: self.load_connection_file() except Exception: self.log.error("Failed to load connection file: %r", self.connection_file, exc_info=True) self.exit(1)
def create_client(name): if name.endswith('.json'): # Received an existing kernel we should connect to. cf = find_connection_file(name) else: cf = find_connection_file('emacs-' + name) c = client.BlockingKernelClient(connection_file=cf) c.load_connection_file() c.start_channels() chans = [('io', c.get_iopub_msg), ('shell', c.get_shell_msg), ('stdin', c.get_stdin_msg)] for name, ch in chans: t = threading.Thread(target=msg_router, args=(name, ch)) t.start() return c
def init_connection_file(self): """find the connection file, and load the info if found. The current working directory and the current profile's security directory will be searched for the file if it is not given by absolute path. When attempting to connect to an existing kernel and the `--existing` argument does not match an existing file, it will be interpreted as a fileglob, and the matching file in the current profile's security dir with the latest access time will be used. """ if self.existing: try: cf = find_connection_file(self.existing) except Exception: self.log.critical( "Could not find existing kernel connection file %s", self.existing) self.exit(1) self.log.info("Connecting to existing kernel: %s" % cf) self.connection_file = cf # should load_connection_file only be used for existing? # as it is now, this allows reusing ports if an existing # file is requested try: self.load_connection_file() except Exception: self.log.error("Failed to load connection file: %r", self.connection_file, exc_info=True) self.exit(1)
def get_client(cf): connection_file = find_connection_file(cf) km = KernelManager(connection_file=connection_file) km.load_connection_file() client = km.client() return KernelClient(client)
def init_connection_file(self): """find the connection file, and load the info if found. The current working directory and the current profile's security directory will be searched for the file if it is not given by absolute path. When attempting to connect to an existing kernel and the `--existing` argument does not match an existing file, it will be interpreted as a fileglob, and the matching file in the current profile's security dir with the latest access time will be used. """ if self.existing: try: cf = find_connection_file(self.existing) except Exception: self.log.critical("Could not find existing kernel connection file %s", self.existing) self.exit(1) self.log.info("Connecting to existing kernel: %s" % cf) self.connection_file = cf # should load_connection_file only be used for existing? # as it is now, this allows reusing ports if an existing # file is requested try: self.load_connection_file() except Exception: self.log.error("Failed to load connection file: %r", self.connection_file, exc_info=True) self.exit(1)
def default_manager(kernel): connection_file = find_connection_file(kernel.connection_file) manager = QtKernelManager(connection_file=connection_file) manager.load_connection_file() manager.start_channels() atexit.register(manager.cleanup_connection_file) return manager
def main(pat): fname = find_connection_file(pat) with open(fname) as f: cfg = json.load(f) url = "%s://%s:%s" % (cfg.get('transport', 'tcp'), cfg['ip'], cfg['iopub_port']) session = Session(key=cfg['key']) ctx = zmq.Context.instance() sub = ctx.socket(zmq.SUB) sub.subscribe = b'' sub.connect(url) # import IPython # IPython.embed() # return stream = ZMQStream(sub) stream.on_recv(lambda msg_list: log_msg(session, msg_list)) pc = PeriodicCallback(print_time, 5 * 60 * 1000) pc.start() IOLoop.instance().start()
def _init_kernel_manager(self): connection_file = find_connection_file(self.app.connection_file) manager = QtKernelManager(connection_file=connection_file) manager.load_connection_file() manager.start_channels() atexit.register(manager.cleanup_connection_file) self.kernel_manager = manager
def create_kernel_manager_and_client(self, connection_file=None, hostname=None, sshkey=None, password=None): """Create kernel manager and client""" cf = find_connection_file(connection_file, profile='default') kernel_manager = QtKernelManager(connection_file=cf, config=None) kernel_client = kernel_manager.client() kernel_client.load_connection_file() if hostname is not None: try: newports = self.tunnel_to_kernel(dict(ip=kernel_client.ip, shell_port=kernel_client.shell_port, iopub_port=kernel_client.iopub_port, stdin_port=kernel_client.stdin_port, hb_port=kernel_client.hb_port), hostname, sshkey, password) (kernel_client.shell_port, kernel_client.iopub_port, kernel_client.stdin_port, kernel_client.hb_port) = newports except Exception as e: print(("Could not open ssh tunnel. The error was:\n\n" + e.message)) return None, None kernel_client.start_channels() # To rely on kernel's heartbeat to know when a kernel has died kernel_client.hb_channel.unpause() return kernel_manager, kernel_client
def init_ipython(): """ Encapsulate Kernel creation logic: Only the kernel client, manager and shell are exposed This is in order to ensure interoperability between major IPython changes """ if ipython_1: manager = QtInProcessKernelManager() manager.start_kernel() manager.kernel.gui = 'qt4' shell = manager.kernel.shell shell.run_cell('%pylab inline') client = manager.client() client.start_channels() else: def event_loop(kernel): kernel.timer = QTimer() kernel.timer.timeout.connect(kernel.do_one_iteration) kernel.timer.start(1000 * kernel._poll_interval) kernel_app = IPKernelApp.instance() kernel_app.initialize(['python', '--pylab=qt']) # at this point, print() won’t work anymore kernel_app.kernel.eventloop = event_loop connection_file = find_connection_file(kernel_app.connection_file) manager = QtKernelManager(connection_file=connection_file) manager.load_connection_file() manager.start_channels() kernel_app.start() client = None shell = kernel_app.shell return client, manager, shell
def connect_kernel(self, connection_file, heartbeat=False): self._heartbeat = heartbeat if os.path.exists(connection_file): self._connection_file = connection_file else: self._connection_file = find_connection_file(connection_file) self._init_kernel_manager()
def init_connection_file(self): """find the connection file, and load the info if found. The current working directory and the current profile's security directory will be searched for the file if it is not given by absolute path. When attempting to connect to an existing kernel and the `--existing` argument does not match an existing file, it will be interpreted as a fileglob, and the matching file in the current profile's security dir with the latest access time will be used. After this method is called, self.connection_file contains the *full path* to the connection file, never just its name. """ if self.existing: try: cf = find_connection_file(self.existing) except Exception: self.log.critical("Could not find existing kernel connection file %s", self.existing) self.exit(1) self.log.info("Connecting to existing kernel: %s" % cf) self.connection_file = cf else: # not existing, check if we are going to write the file # and ensure that self.connection_file is a full path, not just the shortname try: cf = find_connection_file(self.connection_file) except Exception: # file might not exist if self.connection_file == os.path.basename(self.connection_file): # just shortname, put it in security dir cf = os.path.join(self.profile_dir.security_dir, self.connection_file) else: cf = self.connection_file self.connection_file = cf # should load_connection_file only be used for existing? # as it is now, this allows reusing ports if an existing # file is requested try: self.load_connection_file() except Exception: self.log.error("Failed to load connection file: %r", self.connection_file, exc_info=True) self.exit(1)
def _create_client_for_kernel(self, cf, hostname, kf, pw): # Verifying if the connection file exists - in the case of an empty # file name, the last used connection file is returned. try: cf = find_connection_file(cf, profile='default') except (IOError, UnboundLocalError): QMessageBox.critical(self, _('IPython'), _("Unable to connect to IPython <b>%s") % cf) return # Base client name: # remove path and extension, and use the last part when split by '-' base_client_name = osp.splitext(cf.split('/')[-1])[0].split('-')[-1] # Generating the client name by appending /A, /B... until it is unique count = 0 while True: client_name = base_client_name + '/' + chr(65 + count) for cl in self.get_clients(): if cl.name == client_name: break else: break count += 1 # Getting kernel_widget_id from the currently open kernels. kernel_widget_id = None for sw in self.extconsole.shellwidgets: if sw.connection_file == cf.split('/')[-1]: kernel_widget_id = id(sw) # Verifying if frontend and kernel have compatible versions if not self.kernel_and_frontend_match(cf): QMessageBox.critical( self, _("Mismatch between kernel and frontend"), _("Your IPython frontend and kernel versions " "are <b>incompatible!!</b>" "<br><br>" "We're sorry but we can't create an IPython " "console for you."), QMessageBox.Ok) return # Creating the client client = IPythonClient(self, history_filename='history.py', connection_file=cf, kernel_widget_id=kernel_widget_id, menu_actions=self.menu_actions, hostname=hostname, sshkey=kf, password=pw) # Adding the tab self.add_tab(client, name=client.get_name()) # Connecting kernel and client self.register_client(client, client_name)
def create_client(name): cf = find_connection_file('emacs-' + name) c = client.BlockingKernelClient(connection_file=cf) c.load_connection_file() c.start_channels() chans = [('io', c.get_iopub_msg), ('shell', c.get_shell_msg), ('stdin', c.get_stdin_msg)] for name, ch in chans: t = threading.Thread(target=msg_router, args=(name, ch)) t.start() return c
def default_kernel_manager(kernel_app): from IPython.lib.kernel import find_connection_file from IPython.qt.manager import QtKernelManager connection = find_connection_file(kernel_app.connection_file) kernelManager = QtKernelManager(connection_file=connection) kernelClient = kernelManager.client() kernelClient.load_connection_file() kernelClient.start_channels() #atexit.register(kernelManager.cleanup_connection_file) return kernelManager, kernelClient, connection
def _create_client_for_kernel(self, cf, hostname, kf, pw): # Verifying if the connection file exists - in the case of an empty # file name, the last used connection file is returned. try: cf = find_connection_file(cf, profile='default') except (IOError, UnboundLocalError): QMessageBox.critical(self, _('IPython'), _("Unable to connect to IPython <b>%s") % cf) return # Base client name: # remove path and extension, and use the last part when split by '-' base_client_name = osp.splitext(cf.split('/')[-1])[0].split('-')[-1] # Generating the client name by appending /A, /B... until it is unique count = 0 while True: client_name = base_client_name + '/' + chr(65 + count) for cl in self.get_clients(): if cl.name == client_name: break else: break count += 1 # Getting kernel_widget_id from the currently open kernels. kernel_widget_id = None for sw in self.extconsole.shellwidgets: if sw.connection_file == cf.split('/')[-1]: kernel_widget_id = id(sw) # Verifying if frontend and kernel have compatible versions if not self.kernel_and_frontend_match(cf): QMessageBox.critical(self, _("Mismatch between kernel and frontend"), _("Your IPython frontend and kernel versions " "are <b>incompatible!!</b>" "<br><br>" "We're sorry but we can't create an IPython " "console for you." ), QMessageBox.Ok) return # Creating the client client = IPythonClient(self, history_filename='history.py', connection_file=cf, kernel_widget_id=kernel_widget_id, menu_actions=self.menu_actions, hostname=hostname, sshkey=kf, password=pw) # Adding the tab self.add_tab(client, name=client.get_name()) # Connecting kernel and client self.register_client(client, client_name)
def __init__(self, *args, **kwargs): connection_file = find_connection_file(kwargs.pop("connection_file")) km = BlockingKernelManager(connection_file=connection_file) km.load_connection_file() heartbeat = True km.start_channels(hb=heartbeat) atexit.register(km.cleanup_connection_file) super(IPythonConsoleShell, self).__init__(kernel_manager=km) self.km = km
def __init__(self, *args, **kwargs): connection_file = find_connection_file(kwargs.pop("connection_file")) km = BlockingKernelManager(connection_file=connection_file) km.load_connection_file() heartbeat = True km.start_channels(hb=heartbeat) atexit.register(km.cleanup_connection_file) super(IPythonConsoleShell, self).__init__(kernel_manager = km) self.km = km
def default_manager(kernel): """ Return a configured QtKernelManager :param kernel: An IPKernelApp instance """ connection_file = find_connection_file(kernel.connection_file) manager = QtKernelManager(connection_file=connection_file) manager.load_connection_file() manager.start_channels() atexit.register(manager.cleanup_connection_file) return manager
def create_kernel_manager_and_client(self, connection_file=None, hostname=None, sshkey=None, password=None): """Create kernel manager and client""" cf = find_connection_file(connection_file, profile='default') kernel_manager = QtKernelManager(connection_file=cf, config=None) if programs.is_module_installed('IPython', '>=1.0'): kernel_client = kernel_manager.client() kernel_client.load_connection_file() if hostname is not None: try: newports = tunnel_to_kernel( dict(ip=kernel_client.ip, shell_port=kernel_client.shell_port, iopub_port=kernel_client.iopub_port, stdin_port=kernel_client.stdin_port, hb_port=kernel_client.hb_port), hostname, sshkey, password) (kernel_client.shell_port, kernel_client.iopub_port, kernel_client.stdin_port, kernel_client.hb_port) = newports except Exception as e: QMessageBox.critical( self, _('Connection error'), _('Could not open ssh tunnel\n') + str(e)) return None, None kernel_client.start_channels() # To rely on kernel's heartbeat to know when a kernel has died kernel_client.hb_channel.unpause() return kernel_manager, kernel_client else: kernel_manager.load_connection_file() if hostname is not None: try: newports = tunnel_to_kernel( dict(ip=kernel_manager.ip, shell_port=kernel_manager.shell_port, iopub_port=kernel_manager.iopub_port, stdin_port=kernel_manager.stdin_port, hb_port=kernel_manager.hb_port), hostname, sshkey, password) (kernel_manager.shell_port, kernel_manager.iopub_port, kernel_manager.stdin_port, kernel_manager.hb_port) = newports except Exception as e: QMessageBox.critical( self, _('Connection error'), _('Could not open ssh tunnel\n') + str(e)) return None, None kernel_manager.start_channels() return kernel_manager, None
def connect_kernel(self, connection_file, heartbeat=False): """Connect's to ipython kernel. connection_file - connection file to use heartbeat - should start heartbeat server? Workaround for problems with inproc embedded kernels (right click save image as/save as html kills kernel heartbeat/pool(??) serwer """ self._heartbeat = heartbeat if os.path.exists(connection_file): self._connection_file = connection_file else: self._connection_file = find_connection_file(connection_file) self._init_kernel_manager()
def get_client(cf, profile=None): """ Usage: >>> kc = get_client('kernel-143a2687-f294-42b1-bdcb-6f1cc2f4cc87.json', 'dale') >>> data = kc.execute("'123'") >>> data {u'text/plain': u'123'} """ connection_file = find_connection_file(cf, profile=profile) km = KernelManager(connection_file=connection_file) km.load_connection_file() client = km.client() return KernelClient(client)
def create_kernel_manager_and_client(self, connection_file=None): """Create kernel manager and client""" cf = find_connection_file(connection_file, profile='default') kernel_manager = QtKernelManager(connection_file=cf, config=None) if programs.is_module_installed('IPython', '>=1.0'): kernel_client = kernel_manager.client() kernel_client.load_connection_file() kernel_client.start_channels() # To rely on kernel's heartbeat to know when a kernel has died kernel_client.hb_channel.unpause() else: kernel_client = None kernel_manager.load_connection_file() kernel_manager.start_channels() return kernel_manager, kernel_client
def connect_kernel(self, connection_file, heartbeat=False): """Connect to ipython kernel. connection_file - connection file to use heartbeat - should start heartbeat server? Workaround for problems with inproc embedded kernels (right click save image as/save as html kills kernel heartbeat/pool(??) serwer """ self._heartbeat = heartbeat if os.path.exists(connection_file): self._connection_file = connection_file else: self._connection_file = find_connection_file(connection_file) self._init_kernel_manager()
def create_kernel_manager_and_client(self, connection_file=None, hostname=None, sshkey=None, password=None): """Create kernel manager and client""" cf = find_connection_file(connection_file, profile='default') kernel_manager = QtKernelManager(connection_file=cf, config=None) if programs.is_module_installed('IPython', '>=1.0'): kernel_client = kernel_manager.client() kernel_client.load_connection_file() if hostname is not None: try: newports = tunnel_to_kernel(dict(ip=kernel_client.ip, shell_port=kernel_client.shell_port, iopub_port=kernel_client.iopub_port, stdin_port=kernel_client.stdin_port, hb_port=kernel_client.hb_port), hostname, sshkey, password) (kernel_client.shell_port, kernel_client.iopub_port, kernel_client.stdin_port, kernel_client.hb_port) = newports except Exception as e: QMessageBox.critical(self, _('Connection error'), _('Could not open ssh tunnel\n') + str(e)) return None, None kernel_client.start_channels() # To rely on kernel's heartbeat to know when a kernel has died kernel_client.hb_channel.unpause() return kernel_manager, kernel_client else: kernel_manager.load_connection_file() if hostname is not None: try: newports = tunnel_to_kernel(dict(ip=kernel_manager.ip, shell_port=kernel_manager.shell_port, iopub_port=kernel_manager.iopub_port, stdin_port=kernel_manager.stdin_port, hb_port=kernel_manager.hb_port), hostname, sshkey, password) (kernel_manager.shell_port, kernel_manager.iopub_port, kernel_manager.stdin_port, kernel_manager.hb_port) = newports except Exception as e: QMessageBox.critical(self, _('Connection error'), _('Could not open ssh tunnel\n') + str(e)) return None, None kernel_manager.start_channels() return kernel_manager, None
def connect_kernel(self, connection_file, heartbeat=False): """ connection_file: str - is the connection file name, for example 'kernel-16098.json'. heartbeat: bool - workaround, needed for right click/save as ... errors ... i don't know how to fix this issue. Anyone knows? Anyway it needs more testing example1 (standalone): app = QtGui.QApplication([]) widget = IPythonConsoleQtWidget() widget.set_default_style(colors='linux') widget.connect_kernel( connection_file='some connection file name') app.exec_() example2 (IPythonLocalKernelApp): app = QtGui.QApplication([]) kernelapp = IPythonLocalKernelApp.instance() kernelapp.initialize() widget = IPythonConsoleQtWidget() # Green text, black background ;) widget.set_default_style(colors='linux') widget.connect_kernel( connection_file='kernelapp.get_connection_file()) app.exec_() """ km = QtKernelManager( connection_file=find_connection_file(connection_file), config=self.config) km.load_connection_file() km.start_channels(hb=heartbeat) self.kernel_manager = km atexit.register(self.kernel_manager.cleanup_connection_file)
def _createConsoleWidget(self): if is_using_pyqt5(): layout = QtWidgets.QVBoxLayout() else: layout = QtGui.QVBoxLayout() connection_file = find_connection_file(self.connection_file) self.kernel_manager = QtKernelManager(connection_file=connection_file) self.kernel_manager.load_connection_file() self.kernel_manager.client_factory = QtKernelClient self.kernel_client = self.kernel_manager.client() self.kernel_client.start_channels() self.ipython_widget = RichIPythonWidget(self.parent) self.ipython_widget.kernel_manager = self.kernel_manager self.ipython_widget.kernel_client = self.kernel_client layout.addWidget(self.ipython_widget) return layout
def get_widget(self, droplist_completion=True): if IPython.__version__ < '0.13': completion = droplist_completion else: completion = 'droplist' if droplist_completion else 'plain' widget = RichIPythonWidget(gui_completion=completion) cf = find_connection_file(self.kernel_app.connection_file) km = QtKernelManager(connection_file=cf, config=widget.config) km.load_connection_file() km.start_channels() widget.kernel_manager = km atexit.register(km.cleanup_connection_file) sys.stdout = self._stdout sys.stderr = self._stderr sys.displayhook = self._dishook return widget
def connect_kernel(self, connection_file, heartbeat=False): """ connection_file: str - is the connection file name, for example 'kernel-16098.json' heartbeat: bool - workaround, needed for right click/save as ... errors ... i don't know how to fix this issue. Anyone knows? Anyway it needs more testing example1 (standalone): app = QtGui.QApplication([]) widget = IPythonConsoleQtWidget() widget.set_default_style(colors='linux') widget.connect_kernel(connection_file='some connection file name') app.exec_() example2 (IPythonLocalKernelApp): app = QtGui.QApplication([]) kernelapp = IPythonLocalKernelApp.instance() kernelapp.initialize() widget = IPythonConsoleQtWidget() # Green text, black background ;) widget.set_default_style(colors='linux') widget.connect_kernel(connection_file='kernelapp.get_connection_file()) app.exec_() """ km = QtKernelManager( connection_file=find_connection_file(connection_file), config=self.config) km.load_connection_file() km.start_channels(hb=heartbeat) self.kernel_manager = km atexit.register(self.kernel_manager.cleanup_connection_file)
def create_client_for_kernel(self): """Create a client connected to an existing kernel""" example = _("(for example: kernel-3764.json, or simply 3764)") while True: cf, valid = QInputDialog.getText(self, _('IPython'), _('Provide an IPython kernel connection file:')+\ '\n'+example, QLineEdit.Normal) if valid: cf = str(cf) match = re.match('(kernel-|^)([a-fA-F0-9-]+)(.json|$)', cf) if match is not None: kernel_num = match.groups()[1] if kernel_num: cf = 'kernel-%s.json' % kernel_num break else: return # Generating the client name and setting kernel_widget_id match = re.match('^kernel-([a-fA-F0-9-]+).json', cf) count = 0 kernel_widget_id = None while True: client_name = match.groups()[0] if '-' in client_name: # Avoid long names client_name = client_name.split('-')[0] client_name = client_name + '/' + chr(65+count) for cl in self.get_clients(): if cl.name == client_name: kernel_widget_id = cl.kernel_widget_id break else: break count += 1 # Trying to get kernel_widget_id from the currently opened kernels if # the previous procedure fails. This could happen when the first # client connected to a kernel is closed but the kernel is left open # and you try to connect new clients to it if kernel_widget_id is None: for sw in self.extconsole.shellwidgets: if sw.connection_file == cf: kernel_widget_id = id(sw) # Verifying if the kernel exists try: find_connection_file(cf, profile='default') except (IOError, UnboundLocalError): QMessageBox.critical(self, _('IPython'), _("Unable to connect to IPython <b>%s") % cf) return # Verifying if frontend and kernel have compatible versions if not self.kernel_and_frontend_match(cf): QMessageBox.critical(self, _("Mismatch between kernel and frontend"), _("Your IPython frontend and kernel versions " "are <b>incompatible!!</b>" "<br><br>" "We're sorry but we can't create an IPython " "console for you." ), QMessageBox.Ok) return # Creating the client client = IPythonClient(self, history_filename='history.py', connection_file=cf, kernel_widget_id=kernel_widget_id, menu_actions=self.menu_actions) self.add_tab(client, name=client.get_name()) self.register_client(client, client_name)
def connect_kernel(self, conn, heartbeat=False): km = QtKernelManager(connection_file=find_connection_file(conn)) km.load_connection_file() km.start_channels(hb=heartbeat) self.kernel_manager = km atexit.register(self.kernel_manager.cleanup_connection_file)
import zmq from IPython.lib.kernel import find_connection_file from IPython.zmq.blockingkernelmanager import BlockingKernelManager # startup channel pidfile = '/tmp/ipython.pid' with open(pidfile, 'r') as f: cf = f.readline() # remove trailing carriage-return cf = cf[:-1] try: # get real pid of ipython kernel cf = str(int(cf) + 1) cf = find_connection_file(cf) except IOError: cf = str(int(cf) + 1) cf = find_connection_file(cf) km = BlockingKernelManager() km.connection_file = cf km.load_connection_file() km.start_channels() def run_code(code): # execution is immediate and async, returning a UUID msg_id = km.shell_channel.execute(code) # get_meg can block for a reply reply = km.shell_channel.get_msg() if reply['content']['status'] == 'error':
def __init__(self,connection): self.cf = find_connection_file(connection) self.km = BlockingKernelManager(connection_file=self.cf) self.km.load_connection_file() self.km.start_channels()