|
| 1 | +import os |
| 2 | +import signal |
| 3 | +import uuid |
| 4 | + |
| 5 | +from jupyter_core.application import JupyterApp |
| 6 | +from tornado.ioloop import IOLoop |
| 7 | +from traitlets import Unicode |
| 8 | + |
| 9 | +from . import __version__ |
| 10 | +from .kernelspec import KernelSpecManager |
| 11 | +from .manager import KernelManager |
| 12 | + |
| 13 | +class KernelApp(JupyterApp): |
| 14 | + version = __version__ |
| 15 | + description = "Run a kernel locally" |
| 16 | + |
| 17 | + classes = [KernelManager, KernelSpecManager] |
| 18 | + |
| 19 | + aliases = { |
| 20 | + 'kernel': 'KernelApp.kernel_name', |
| 21 | + 'ip': 'KernelManager.ip', |
| 22 | + } |
| 23 | + |
| 24 | + kernel_name = Unicode( |
| 25 | + help = 'The name of a kernel to start' |
| 26 | + ).tag(config=True) |
| 27 | + |
| 28 | + def initialize(self, argv=None): |
| 29 | + super(KernelApp, self).initialize(argv) |
| 30 | + self.km = KernelManager(kernel_name=self.kernel_name, |
| 31 | + config=self.config) |
| 32 | + cf_basename = 'kernel-%s.json' % uuid.uuid4() |
| 33 | + self.km.connection_file = os.path.join(self.runtime_dir, cf_basename) |
| 34 | + self.loop = IOLoop.current() |
| 35 | + |
| 36 | + def setup_signals(self): |
| 37 | + if os.name == 'nt': |
| 38 | + return |
| 39 | + |
| 40 | + def shutdown_handler(signo, frame): |
| 41 | + self.loop.add_callback_from_signal(self.shutdown, signo) |
| 42 | + for sig in [signal.SIGTERM, signal.SIGINT]: |
| 43 | + signal.signal(sig, shutdown_handler) |
| 44 | + |
| 45 | + def shutdown(self, signo): |
| 46 | + self.log.info('Shutting down on signal %d' % signo) |
| 47 | + self.km.shutdown_kernel() |
| 48 | + self.loop.stop() |
| 49 | + |
| 50 | + def log_connection_info(self): |
| 51 | + cf = self.km.connection_file |
| 52 | + self.log.info('Connection file: %s', cf) |
| 53 | + self.log.info("To connect a client: --existing %s", os.path.basename(cf)) |
| 54 | + |
| 55 | + def start(self): |
| 56 | + self.log.info('Starting kernel %r', self.kernel_name) |
| 57 | + try: |
| 58 | + self.km.start_kernel() |
| 59 | + self.log_connection_info() |
| 60 | + self.setup_signals() |
| 61 | + self.loop.start() |
| 62 | + finally: |
| 63 | + self.km.cleanup() |
| 64 | + |
| 65 | + |
| 66 | +main = KernelApp.launch_instance |
0 commit comments