Debian Codegraph @

jupyter_client/kernelapp.py

raw
1 """An application to launch a kernel by name in a local subprocess."""
2
3 import os
4 import signal
5 import typing as t
6 import uuid
7
8 from jupyter_core.application import JupyterApp, base_flags
9 from tornado.ioloop import IOLoop
10 from traitlets import Unicode
11
12 from . import __version__
13 from .kernelspec import NATIVE_KERNEL_NAME, KernelSpecManager
14 from .manager import KernelManager
15
16
17 class KernelApp(JupyterApp):
18 """Launch a kernel by name in a local subprocess."""
19
20 version = __version__
21 description = "Run a kernel locally in a subprocess"
22
23 classes = [KernelManager, KernelSpecManager]
24
25 aliases = {
26 "kernel": "KernelApp.kernel_name",
27 "ip": "KernelManager.ip",
28 }
29 flags = {"debug": base_flags["debug"]}
30
31 kernel_name = Unicode(NATIVE_KERNEL_NAME, help="The name of a kernel type to start").tag(
32 config=True
33 )
34
35 def initialize(self, argv: t.Union[str, t.Sequence[str], None] = None) -> None:
36 """Initialize the application."""
37 super().initialize(argv)
38
39 cf_basename = "kernel-%s.json" % uuid.uuid4()
40 self.config.setdefault("KernelManager", {}).setdefault(
41 "connection_file", os.path.join(self.runtime_dir, cf_basename)
42 )
43 self.km = KernelManager(kernel_name=self.kernel_name, config=self.config)
44
45 self.loop = IOLoop.current()
46 self.loop.add_callback(self._record_started)
47
48 def setup_signals(self) -> None:
49 """Shutdown on SIGTERM or SIGINT (Ctrl-C)"""
50 if os.name == "nt":
51 return
52
53 def shutdown_handler(signo: int, frame: t.Any) -> None:
54 self.loop.add_callback_from_signal(self.shutdown, signo)
55
56 for sig in [signal.SIGTERM, signal.SIGINT]:
57 signal.signal(sig, shutdown_handler)
58
59 def shutdown(self, signo: int) -> None:
60 """Shut down the application."""
61 self.log.info("Shutting down on signal %d", signo)
62 self.km.shutdown_kernel()
63 self.loop.stop()
64
65 def log_connection_info(self) -> None:
66 """Log the connection info for the kernel."""
67 cf = self.km.connection_file
68 self.log.info("Connection file: %s", cf)
69 self.log.info("To connect a client: --existing %s", os.path.basename(cf))
70
71 def _record_started(self) -> None:
72 """For tests, create a file to indicate that we've started
73
74 Do not rely on this except in our own tests!
75 """
76 fn = os.environ.get("JUPYTER_CLIENT_TEST_RECORD_STARTUP_PRIVATE")
77 if fn is not None:
78 with open(fn, "wb"):
79 pass
80
81 def start(self) -> None:
82 """Start the application."""
83 self.log.info("Starting kernel %r", self.kernel_name)
84 try:
85 self.km.start_kernel()
86 self.log_connection_info()
87 self.setup_signals()
88 self.loop.start()
89 finally:
90 self.km.cleanup_resources()
91
92
93 main = KernelApp.launch_instance