1 """A kernel manager for in-process kernels.""" 2 3 # Copyright (c) IPython Development Team. 4 # Distributed under the terms of the Modified BSD License. 5 6 from jupyter_client.manager import KernelManager 7 from jupyter_client.managerabc import KernelManagerABC 8 from jupyter_client.session import Session 9 from traitlets import DottedObjectName, Instance, default 10 11 from .constants import INPROCESS_KEY 12 13 14 class InProcessKernelManager(KernelManager): 15 """A manager for an in-process kernel. 16 17 This class implements the interface of 18 `jupyter_client.kernelmanagerabc.KernelManagerABC` and allows 19 (asynchronous) frontends to be used seamlessly with an in-process kernel. 20 21 See `jupyter_client.kernelmanager.KernelManager` for docstrings. 22 """ 23 24 # The kernel process with which the KernelManager is communicating. 25 kernel = Instance("ipykernel.inprocess.ipkernel.InProcessKernel", allow_none=True) 26 # the client class for KM.client() shortcut 27 client_class = DottedObjectName("ipykernel.inprocess.BlockingInProcessKernelClient") 28 29 @default("blocking_class") 30 def _default_blocking_class(self): 31 from .blocking import BlockingInProcessKernelClient 32 33 return BlockingInProcessKernelClient 34 35 @default("session") 36 def _default_session(self): 37 # don't sign in-process messages 38 return Session(key=INPROCESS_KEY, parent=self) 39 40 # -------------------------------------------------------------------------- 41 # Kernel management methods 42 # -------------------------------------------------------------------------- 43 44 def start_kernel(self, **kwds): 45 """Start the kernel.""" 46 from ipykernel.inprocess.ipkernel import InProcessKernel 47 48 self.kernel = InProcessKernel(parent=self, session=self.session) 49 50 def shutdown_kernel(self): 51 """Shutdown the kernel.""" 52 if self.kernel: 53 self.kernel.iopub_thread.stop() 54 self._kill_kernel() 55 56 def restart_kernel(self, now=False, **kwds): 57 """Restart the kernel.""" 58 self.shutdown_kernel() 59 self.start_kernel(**kwds) 60 61 @property 62 def has_kernel(self): 63 return self.kernel is not None 64 65 def _kill_kernel(self): 66 self.kernel = None 67 68 def interrupt_kernel(self): 69 """Interrupt the kernel.""" 70 msg = "Cannot interrupt in-process kernel." 71 raise NotImplementedError(msg) 72 73 def signal_kernel(self, signum): 74 """Send a signal to the kernel.""" 75 msg = "Cannot signal in-process kernel." 76 raise NotImplementedError(msg) 77 78 def is_alive(self): 79 """Test if the kernel is alive.""" 80 return self.kernel is not None 81 82 def client(self, **kwargs): 83 """Get a client for the kernel.""" 84 kwargs["kernel"] = self.kernel 85 return super().client(**kwargs) 86 87 88 # ----------------------------------------------------------------------------- 89 # ABC Registration 90 # ----------------------------------------------------------------------------- 91 92 KernelManagerABC.register(InProcessKernelManager) 93