Debian Codegraph @

jupyter_client/kernelspecapp.py

raw
1 """Apps for managing kernel specs."""
2
3 # Copyright (c) Jupyter Development Team.
4 # Distributed under the terms of the Modified BSD License.
5 from __future__ import annotations
6
7 import errno
8 import json
9 import os.path
10 import sys
11 import typing as t
12 from pathlib import Path
13
14 from jupyter_core.application import JupyterApp, base_aliases, base_flags
15 from traitlets import Bool, Dict, Instance, List, Unicode
16 from traitlets.config.application import Application
17
18 from . import __version__
19 from .kernelspec import KernelSpecManager
20 from .provisioning.factory import KernelProvisionerFactory
21
22
23 class ListKernelSpecs(JupyterApp):
24 """An app to list kernel specs."""
25
26 version = __version__
27 description = """List installed kernel specifications."""
28 kernel_spec_manager = Instance(KernelSpecManager)
29 json_output = Bool(
30 False,
31 help="output spec name and location as machine-readable json.",
32 config=True,
33 )
34 missing_kernels = Bool(
35 False,
36 help="List only specs with missing interpreters.",
37 config=True,
38 )
39 flags = {
40 "json": (
41 {"ListKernelSpecs": {"json_output": True}},
42 "output spec name and location as machine-readable json.",
43 ),
44 "missing": (
45 {"ListKernelSpecs": {"missing_kernels": True}},
46 "output only missing kernels",
47 ),
48 "debug": base_flags["debug"],
49 }
50
51 def _kernel_spec_manager_default(self) -> KernelSpecManager:
52 return KernelSpecManager(parent=self, data_dir=self.data_dir)
53
54 def start(self) -> dict[str, t.Any] | None: # type:ignore[override]
55 """Start the application."""
56 paths = self.kernel_spec_manager.find_kernel_specs()
57 specs = self.kernel_spec_manager.get_all_specs()
58
59 if self.missing_kernels:
60 paths, specs = _limit_to_missing(paths, specs)
61
62 if not self.json_output:
63 if not specs:
64 print("No kernels available")
65 return None
66 # pad to width of longest kernel name
67 name_len = len(sorted(paths, key=lambda name: len(name))[-1])
68
69 def path_key(item: t.Any) -> t.Any:
70 """sort key function for Jupyter path priority"""
71 path = item[1]
72 for idx, prefix in enumerate(self.jupyter_path):
73 if path.startswith(prefix):
74 return (idx, path)
75 # not in jupyter path, artificially added to the front
76 return (-1, path)
77
78 print("Available kernels:")
79 for kernelname, path in sorted(paths.items(), key=path_key):
80 print(f" {kernelname.ljust(name_len)} {path}")
81 else:
82 print(json.dumps({"kernelspecs": specs}, indent=2))
83 return specs
84
85
86 class InstallKernelSpec(JupyterApp):
87 """An app to install a kernel spec."""
88
89 version = __version__
90 description = """Install a kernel specification directory.
91
92 Given a SOURCE DIRECTORY containing a kernel spec,
93 jupyter will copy that directory into one of the Jupyter kernel directories.
94 The default is to install kernelspecs for all users.
95 `--user` can be specified to install a kernel only for the current user.
96 """
97 examples = """
98 jupyter kernelspec install /path/to/my_kernel --user
99 """
100 usage = "jupyter kernelspec install SOURCE_DIR [--options]"
101 kernel_spec_manager = Instance(KernelSpecManager)
102
103 def _kernel_spec_manager_default(self) -> KernelSpecManager:
104 return KernelSpecManager(data_dir=self.data_dir)
105
106 sourcedir = Unicode()
107 kernel_name = Unicode("", config=True, help="Install the kernel spec with this name")
108
109 def _kernel_name_default(self) -> str:
110 return os.path.basename(self.sourcedir)
111
112 user = Bool(
113 False,
114 config=True,
115 help="""
116 Try to install the kernel spec to the per-user directory instead of
117 the system or environment directory.
118 """,
119 )
120 prefix = Unicode(
121 "",
122 config=True,
123 help="""Specify a prefix to install to, e.g. an env.
124 The kernelspec will be installed in PREFIX/share/jupyter/kernels/
125 """,
126 )
127 replace = Bool(False, config=True, help="Replace any existing kernel spec with this name.")
128
129 aliases = {
130 "name": "InstallKernelSpec.kernel_name",
131 "prefix": "InstallKernelSpec.prefix",
132 }
133 aliases.update(base_aliases)
134
135 flags = {
136 "user": (
137 {"InstallKernelSpec": {"user": True}},
138 "Install to the per-user kernel registry",
139 ),
140 "replace": (
141 {"InstallKernelSpec": {"replace": True}},
142 "Replace any existing kernel spec with this name.",
143 ),
144 "sys-prefix": (
145 {"InstallKernelSpec": {"prefix": sys.prefix}},
146 "Install to Python's sys.prefix. Useful in conda/virtual environments.",
147 ),
148 "debug": base_flags["debug"],
149 }
150
151 def parse_command_line(self, argv: None | list[str]) -> None: # type:ignore[override]
152 """Parse the command line args."""
153 super().parse_command_line(argv)
154 # accept positional arg as profile name
155 if self.extra_args:
156 self.sourcedir = self.extra_args[0]
157 else:
158 print("No source directory specified.", file=sys.stderr)
159 self.exit(1)
160
161 def start(self) -> None:
162 """Start the application."""
163 if self.user and self.prefix:
164 self.exit("Can't specify both user and prefix. Please choose one or the other.")
165 try:
166 self.kernel_spec_manager.install_kernel_spec(
167 self.sourcedir,
168 kernel_name=self.kernel_name,
169 user=self.user,
170 prefix=self.prefix,
171 replace=self.replace,
172 )
173 except OSError as e:
174 if e.errno == errno.EACCES:
175 print(e, file=sys.stderr)
176 if not self.user:
177 print("Perhaps you want to install with `sudo` or `--user`?", file=sys.stderr)
178 self.exit(1)
179 elif e.errno == errno.EEXIST:
180 print(f"A kernel spec is already present at {e.filename}", file=sys.stderr)
181 self.exit(1)
182 raise
183
184
185 class RemoveKernelSpec(JupyterApp):
186 """An app to remove a kernel spec."""
187
188 version = __version__
189 description = """Remove one or more Jupyter kernelspecs by name."""
190 examples = """jupyter kernelspec remove python2 [my_kernel ...]"""
191
192 force = Bool(False, config=True, help="""Force removal, don't prompt for confirmation.""")
193 spec_names = List(Unicode())
194 missing_kernels = Bool(
195 False,
196 help="Remove missing specs.",
197 config=True,
198 )
199
200 kernel_spec_manager = Instance(KernelSpecManager)
201
202 def _kernel_spec_manager_default(self) -> KernelSpecManager:
203 return KernelSpecManager(data_dir=self.data_dir, parent=self)
204
205 flags = {
206 "f": ({"RemoveKernelSpec": {"force": True}}, force.help),
207 "missing": (
208 {"RemoveKernelSpec": {"missing_kernels": True}},
209 "remove missing kernels",
210 ),
211 }
212 flags.update(JupyterApp.flags)
213
214 def parse_command_line(self, argv: list[str] | None) -> None: # type:ignore[override]
215 """Parse the command line args."""
216 super().parse_command_line(argv)
217 # accept positional arg as profile name
218 if self.extra_args:
219 self.spec_names = sorted(set(self.extra_args)) # remove duplicates
220 else:
221 self.spec_names = []
222
223 def start(self) -> None:
224 """Start the application."""
225 self.kernel_spec_manager.ensure_native_kernel = False
226 spec_paths = self.kernel_spec_manager.find_kernel_specs()
227
228 if self.missing_kernels:
229 _, spec = _limit_to_missing(
230 spec_paths,
231 self.kernel_spec_manager.get_all_specs(),
232 )
233
234 # append missing kernels
235 self.spec_names = sorted(set(self.spec_names + list(spec)))
236
237 missing = set(self.spec_names).difference(set(spec_paths))
238 if missing:
239 self.exit("Couldn't find kernel spec(s): %s" % ", ".join(missing))
240
241 if not (self.force or self.answer_yes):
242 print("Kernel specs to remove:")
243 for name in self.spec_names:
244 path = spec_paths.get(name, name)
245 print(f" {name.ljust(20)}\t{path.ljust(20)}")
246 answer = input("Remove %i kernel specs [y/N]: " % len(self.spec_names))
247 if not answer.lower().startswith("y"):
248 return
249
250 for kernel_name in self.spec_names:
251 try:
252 path = self.kernel_spec_manager.remove_kernel_spec(kernel_name)
253 except OSError as e:
254 if e.errno == errno.EACCES:
255 print(e, file=sys.stderr)
256 print("Perhaps you want sudo?", file=sys.stderr)
257 self.exit(1)
258 else:
259 raise
260 print(f"Removed {path}")
261
262
263 class InstallNativeKernelSpec(JupyterApp):
264 """An app to install the native kernel spec."""
265
266 version = __version__
267 description = """[DEPRECATED] Install the IPython kernel spec directory for this Python."""
268 kernel_spec_manager = Instance(KernelSpecManager)
269
270 def _kernel_spec_manager_default(self) -> KernelSpecManager: # pragma: no cover
271 return KernelSpecManager(data_dir=self.data_dir)
272
273 user = Bool(
274 False,
275 config=True,
276 help="""
277 Try to install the kernel spec to the per-user directory instead of
278 the system or environment directory.
279 """,
280 )
281
282 flags = {
283 "user": (
284 {"InstallNativeKernelSpec": {"user": True}},
285 "Install to the per-user kernel registry",
286 ),
287 "debug": base_flags["debug"],
288 }
289
290 def start(self) -> None: # pragma: no cover
291 """Start the application."""
292 self.log.warning(
293 "`jupyter kernelspec install-self` is DEPRECATED as of 4.0."
294 " You probably want `ipython kernel install` to install the IPython kernelspec."
295 )
296 try:
297 from ipykernel import kernelspec
298 except ModuleNotFoundError:
299 print("ipykernel not available, can't install its spec.", file=sys.stderr)
300 self.exit(1)
301 try:
302 kernelspec.install(self.kernel_spec_manager, user=self.user)
303 except OSError as e:
304 if e.errno == errno.EACCES:
305 print(e, file=sys.stderr)
306 if not self.user:
307 print(
308 "Perhaps you want to install with `sudo` or `--user`?",
309 file=sys.stderr,
310 )
311 self.exit(1)
312 self.exit(e) # type:ignore[arg-type]
313
314
315 class ListProvisioners(JupyterApp):
316 """An app to list provisioners."""
317
318 version = __version__
319 description = """List available provisioners for use in kernel specifications."""
320
321 def start(self) -> None:
322 """Start the application."""
323 kfp = KernelProvisionerFactory.instance(parent=self)
324 print("Available kernel provisioners:")
325 provisioners = kfp.get_provisioner_entries()
326
327 # pad to width of longest kernel name
328 name_len = len(sorted(provisioners, key=lambda name: len(name))[-1])
329
330 for name in sorted(provisioners):
331 print(f" {name.ljust(name_len)} {provisioners[name]}")
332
333
334 class KernelSpecApp(Application):
335 """An app to manage kernel specs."""
336
337 version = __version__
338 name = "jupyter kernelspec"
339 description = """Manage Jupyter kernel specifications."""
340
341 subcommands = Dict(
342 {
343 "list": (ListKernelSpecs, ListKernelSpecs.description.splitlines()[0]),
344 "install": (
345 InstallKernelSpec,
346 InstallKernelSpec.description.splitlines()[0],
347 ),
348 "uninstall": (RemoveKernelSpec, "Alias for remove"),
349 "remove": (RemoveKernelSpec, RemoveKernelSpec.description.splitlines()[0]),
350 "install-self": (
351 InstallNativeKernelSpec,
352 InstallNativeKernelSpec.description.splitlines()[0],
353 ),
354 "provisioners": (ListProvisioners, ListProvisioners.description.splitlines()[0]),
355 }
356 )
357
358 aliases = {}
359 flags = {}
360
361 def start(self) -> None:
362 """Start the application."""
363 if self.subapp is None:
364 print("No subcommand specified. Must specify one of: %s" % list(self.subcommands))
365 print()
366 self.print_description()
367 self.print_subcommands()
368 self.exit(1)
369 else:
370 return self.subapp.start()
371
372
373 def _limit_to_missing(
374 paths: dict[str, str], specs: dict[str, t.Any]
375 ) -> tuple[dict[str, str], dict[str, t.Any]]:
376 from shutil import which
377
378 missing: dict[str, t.Any] = {}
379 for name, data in specs.items():
380 exe = data["spec"]["argv"][0]
381 # if exe exists or is on the path, keep it
382 if Path(exe).exists() or which(exe):
383 continue
384 missing[name] = data
385
386 paths_: dict[str, str] = {k: v for k, v in paths.items() if k in missing}
387 return paths_, missing
388
389
390 if __name__ == "__main__":
391 KernelSpecApp.launch_instance()