Debian Codegraph @

jupyter_client/runapp.py

raw
1 """A Jupyter console app to run files."""
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 atexit
8 import signal
9 import sys
10 import typing as t
11
12 from jupyter_core.application import JupyterApp, base_aliases, base_flags
13 from traitlets import Any, Dict, Float
14 from traitlets.config import catch_config_error
15
16 from . import __version__
17 from .consoleapp import JupyterConsoleApp, app_aliases, app_flags
18
19 OUTPUT_TIMEOUT = 10
20
21 # copy flags from mixin:
22 flags = dict(base_flags)
23 # start with mixin frontend flags:
24 frontend_flags_dict = dict(app_flags)
25 # update full dict with frontend flags:
26 flags.update(frontend_flags_dict)
27
28 # copy flags from mixin
29 aliases = dict(base_aliases)
30 # start with mixin frontend flags
31 frontend_aliases_dict = dict(app_aliases)
32 # load updated frontend flags into full dict
33 aliases.update(frontend_aliases_dict)
34
35 # get flags&aliases into sets, and remove a couple that
36 # shouldn't be scrubbed from backend flags:
37 frontend_aliases = set(frontend_aliases_dict.keys())
38 frontend_flags = set(frontend_flags_dict.keys())
39
40
41 class RunApp(JupyterApp, JupyterConsoleApp):
42 """An Jupyter Console app to run files."""
43
44 version = __version__
45 name = "jupyter run"
46 description = """Run Jupyter kernel code."""
47 flags = Dict(flags)
48 aliases = Dict(aliases)
49 frontend_aliases = Any(frontend_aliases)
50 frontend_flags = Any(frontend_flags)
51 kernel_timeout = Float(
52 60,
53 config=True,
54 help="""Timeout for giving up on a kernel (in seconds).
55
56 On first connect and restart, the console tests whether the
57 kernel is running and responsive by sending kernel_info_requests.
58 This sets the timeout in seconds for how long the kernel can take
59 before being presumed dead.
60 """,
61 )
62
63 def parse_command_line(self, argv: list[str] | None = None) -> None:
64 """Parse the command line arguments."""
65 super().parse_command_line(argv)
66 self.build_kernel_argv(self.extra_args)
67 self.filenames_to_run = self.extra_args[:]
68
69 @catch_config_error
70 def initialize(self, argv: list[str] | None = None) -> None: # type:ignore[override]
71 """Initialize the app."""
72 self.log.debug("jupyter run: initialize...")
73 super().initialize(argv)
74 JupyterConsoleApp.initialize(self)
75 signal.signal(signal.SIGINT, self.handle_sigint)
76 if self.kernel_manager:
77 atexit.register(self.kernel_manager.shutdown_kernel)
78
79 def handle_sigint(self, *args: t.Any) -> None:
80 """Handle SIGINT."""
81 if self.kernel_manager:
82 self.kernel_manager.interrupt_kernel()
83 else:
84 self.log.error("Cannot interrupt kernels we didn't start.\n")
85
86 def start(self) -> None:
87 """Start the application."""
88 self.log.debug("jupyter run: starting...")
89 super().start()
90 self.kernel_client.wait_for_ready(timeout=self.kernel_timeout)
91 if self.filenames_to_run:
92 for filename in self.filenames_to_run:
93 self.log.debug("jupyter run: executing `%s`", filename)
94 with open(filename) as fp:
95 code = fp.read()
96 reply = self.kernel_client.execute_interactive(code, timeout=OUTPUT_TIMEOUT)
97 return_code = 0 if reply["content"]["status"] == "ok" else 1
98 if return_code:
99 msg = f"jupyter-run error running '{filename}'"
100 raise Exception(msg)
101 else:
102 self.log.debug("jupyter run: executing from stdin")
103 code = sys.stdin.read()
104 reply = self.kernel_client.execute_interactive(code, timeout=OUTPUT_TIMEOUT)
105 return_code = 0 if reply["content"]["status"] == "ok" else 1
106 if return_code:
107 msg = "jupyter-run error running 'stdin'"
108 raise Exception(msg)
109
110
111 main = launch_new_instance = RunApp.launch_instance
112
113 if __name__ == "__main__":
114 main()