| 1 |
"""Base class to manage the interaction with a running kernel""" |
| 2 |
|
| 3 |
# Copyright (c) Jupyter Development Team. |
| 4 |
# Distributed under the terms of the Modified BSD License. |
| 5 |
import asyncio |
| 6 |
import inspect |
| •7 |
import re |
| 8 |
import sys |
| •9 |
import textwrap |
| 10 |
import time |
| 11 |
import typing as t |
| 12 |
from functools import partial |
| 13 |
from getpass import getpass |
| 14 |
from queue import Empty |
| 15 |
|
| 16 |
import zmq.asyncio |
| 17 |
from jupyter_core.utils import ensure_async |
| 18 |
from traitlets import Any, Bool, Instance, Type |
| 19 |
|
| 20 |
from .channels import major_protocol_version |
| 21 |
from .channelsabc import ChannelABC, HBChannelABC |
| 22 |
from .clientabc import KernelClientABC |
| 23 |
from .connect import ConnectionFileMixin |
| 24 |
from .session import Session |
| 25 |
|
| 26 |
# some utilities to validate message structure, these might get moved elsewhere |
| 27 |
# if they prove to have more generic utility |
| 28 |
|
| 29 |
|
| 30 |
def validate_string_dict(dct: t.Dict[str, str]) -> None: |
| 31 |
"""Validate that the input is a dict with string keys and values. |
| 32 |
|
| 33 |
Raises ValueError if not.""" |
| 34 |
for k, v in dct.items(): |
| 35 |
if not isinstance(k, str): |
| 36 |
raise ValueError("key %r in dict must be a string" % k) |
| 37 |
if not isinstance(v, str): |
| 38 |
raise ValueError("value %r in dict must be a string" % v) |
| 39 |
|
| 40 |
|
| •41 |
def get_docstring_indent(doc: str) -> str: |
| 42 |
# Python 3.13 dedents docstrings automatically. |
| 43 |
# In this module, the docstring indent is the indent of the |
| 44 |
# first non-blank line after the initial line, which is returned |
| 45 |
# as a whitespace string. |
| 46 |
# This is not a general method for determining the indent of a docstring! |
| 47 |
# See the source code of textwrap.dedent() for that. |
| 48 |
doclines = doc.split("\n") |
| 49 |
for line in doclines[1:]: |
| 50 |
if re.match(r"\s*$", line): |
| 51 |
continue |
| 52 |
linematch = re.match(r"(\s*)\S", line) |
| 53 |
assert linematch is not None |
| 54 |
return linematch.group(1) |
| 55 |
# If there was no content in the docstring beyond the initial line |
| 56 |
return "" |
| 57 |
|
| 58 |
|
| 59 |
def reqrep(wrapped: t.Callable, meth: t.Callable, channel: str = "shell") -> t.Callable: |
| 60 |
wrapped = wrapped(meth, channel) |
| 61 |
if not meth.__doc__: |
| 62 |
# python -OO removes docstrings, |
| 63 |
# so don't bother building the wrapped docstring |
| 64 |
return wrapped |
| 65 |
|
| •66 |
params_header = """\ |
| 67 |
Parameters |
| 68 |
---------- |
| 69 |
""" |
| •70 |
returns_doc = """\ |
| 71 |
reply : bool (default: False) |
| 72 |
Whether to wait for and return reply |
| •73 |
|
| 74 |
timeout : float or None (default: None) |
| 75 |
Timeout to use when waiting for a reply |
| 76 |
|
| 77 |
Returns |
| 78 |
------- |
| •79 |
msg_id : str |
| 80 |
The msg_id of the request sent, if reply=False (default) |
| •81 |
|
| 82 |
reply : dict |
| 83 |
The reply message for this request, if reply=True |
| •84 |
""" |
| 85 |
|
| 86 |
basedoc, _ = meth.__doc__.split("Returns\n", 1) |
| 87 |
parts = [basedoc.strip()] |
| 88 |
indent = get_docstring_indent(basedoc) |
| 89 |
if "Parameters" not in basedoc: |
| 90 |
parts.append(textwrap.indent(textwrap.dedent(params_header), indent)) |
| 91 |
parts.append(textwrap.indent(textwrap.dedent(returns_doc), indent)) |
| 92 |
|
| 93 |
wrapped.__doc__ = "\n\n".join(parts) |
| 94 |
return wrapped |
| 95 |
|
| 96 |
|
| 97 |
class KernelClient(ConnectionFileMixin): |
| 98 |
"""Communicates with a single kernel on any host via zmq channels. |
| 99 |
|
| 100 |
There are five channels associated with each kernel: |
| 101 |
|
| 102 |
* shell: for request/reply calls to the kernel. |
| 103 |
* iopub: for the kernel to publish results to frontends. |
| 104 |
* hb: for monitoring the kernel's heartbeat. |
| 105 |
* stdin: for frontends to reply to raw_input calls in the kernel. |
| 106 |
* control: for kernel management calls to the kernel. |
| 107 |
|
| 108 |
The messages that can be sent on these channels are exposed as methods of the |
| 109 |
client (KernelClient.execute, complete, history, etc.). These methods only |
| 110 |
send the message, they don't wait for a reply. To get results, use e.g. |
| 111 |
:meth:`get_shell_msg` to fetch messages from the shell channel. |
| 112 |
""" |
| 113 |
|
| 114 |
# The PyZMQ Context to use for communication with the kernel. |
| 115 |
context = Instance(zmq.Context) |
| 116 |
|
| 117 |
_created_context = Bool(False) |
| 118 |
|
| 119 |
def _context_default(self) -> zmq.Context: |
| 120 |
self._created_context = True |
| 121 |
return zmq.Context() |
| 122 |
|
| 123 |
# The classes to use for the various channels |
| 124 |
shell_channel_class = Type(ChannelABC) |
| 125 |
iopub_channel_class = Type(ChannelABC) |
| 126 |
stdin_channel_class = Type(ChannelABC) |
| 127 |
hb_channel_class = Type(HBChannelABC) |
| 128 |
control_channel_class = Type(ChannelABC) |
| 129 |
|
| 130 |
# Protected traits |
| 131 |
_shell_channel = Any() |
| 132 |
_iopub_channel = Any() |
| 133 |
_stdin_channel = Any() |
| 134 |
_hb_channel = Any() |
| 135 |
_control_channel = Any() |
| 136 |
|
| 137 |
# flag for whether execute requests should be allowed to call raw_input: |
| 138 |
allow_stdin: bool = True |
| 139 |
|
| 140 |
def __del__(self) -> None: |
| 141 |
"""Handle garbage collection. Destroy context if applicable.""" |
| 142 |
if ( |
| 143 |
self._created_context |
| 144 |
and self.context is not None # type:ignore[redundant-expr] |
| 145 |
and not self.context.closed |
| 146 |
): |
| 147 |
if self.channels_running: |
| 148 |
if self.log: |
| 149 |
self.log.warning("Could not destroy zmq context for %s", self) |
| 150 |
else: |
| 151 |
if self.log: |
| 152 |
self.log.debug("Destroying zmq context for %s", self) |
| 153 |
self.context.destroy(linger=100) |
| 154 |
try: |
| 155 |
super_del = super().__del__ # type:ignore[misc] |
| 156 |
except AttributeError: |
| 157 |
pass |
| 158 |
else: |
| 159 |
super_del() |
| 160 |
|
| 161 |
# -------------------------------------------------------------------------- |
| 162 |
# Channel proxy methods |
| 163 |
# -------------------------------------------------------------------------- |
| 164 |
|
| 165 |
async def _async_get_shell_msg(self, *args: t.Any, **kwargs: t.Any) -> t.Dict[str, t.Any]: |
| 166 |
"""Get a message from the shell channel""" |
| 167 |
return await ensure_async(self.shell_channel.get_msg(*args, **kwargs)) |
| 168 |
|
| 169 |
async def _async_get_iopub_msg(self, *args: t.Any, **kwargs: t.Any) -> t.Dict[str, t.Any]: |
| 170 |
"""Get a message from the iopub channel""" |
| 171 |
return await ensure_async(self.iopub_channel.get_msg(*args, **kwargs)) |
| 172 |
|
| 173 |
async def _async_get_stdin_msg(self, *args: t.Any, **kwargs: t.Any) -> t.Dict[str, t.Any]: |
| 174 |
"""Get a message from the stdin channel""" |
| 175 |
return await ensure_async(self.stdin_channel.get_msg(*args, **kwargs)) |
| 176 |
|
| 177 |
async def _async_get_control_msg(self, *args: t.Any, **kwargs: t.Any) -> t.Dict[str, t.Any]: |
| 178 |
"""Get a message from the control channel""" |
| 179 |
return await ensure_async(self.control_channel.get_msg(*args, **kwargs)) |
| 180 |
|
| 181 |
async def _async_wait_for_ready(self, timeout: float | None = None) -> None: |
| 182 |
"""Waits for a response when a client is blocked |
| 183 |
|
| 184 |
- Sets future time for timeout |
| 185 |
- Blocks on shell channel until a message is received |
| 186 |
- Exit if the kernel has died |
| 187 |
- If client times out before receiving a message from the kernel, send RuntimeError |
| 188 |
- Flush the IOPub channel |
| 189 |
""" |
| 190 |
if timeout is None: |
| 191 |
timeout = float("inf") |
| 192 |
abs_timeout = time.time() + timeout |
| 193 |
|
| 194 |
from .manager import KernelManager |
| 195 |
|
| 196 |
if not isinstance(self.parent, KernelManager): |
| 197 |
# This Client was not created by a KernelManager, |
| 198 |
# so wait for kernel to become responsive to heartbeats |
| 199 |
# before checking for kernel_info reply |
| 200 |
while not await self._async_is_alive(): |
| 201 |
if time.time() > abs_timeout: |
| 202 |
raise RuntimeError( |
| 203 |
"Kernel didn't respond to heartbeats in %d seconds and timed out" % timeout |
| 204 |
) |
| 205 |
await asyncio.sleep(0.2) |
| 206 |
|
| 207 |
# Wait for kernel info reply on shell channel |
| 208 |
while True: |
| 209 |
self.kernel_info() |
| 210 |
try: |
| 211 |
msg = await ensure_async(self.shell_channel.get_msg(timeout=1)) |
| 212 |
except Empty: |
| 213 |
pass |
| 214 |
else: |
| 215 |
if msg["msg_type"] == "kernel_info_reply": |
| 216 |
# Checking that IOPub is connected. If it is not connected, start over. |
| 217 |
try: |
| 218 |
await ensure_async(self.iopub_channel.get_msg(timeout=0.2)) |
| 219 |
except Empty: |
| 220 |
pass |
| 221 |
else: |
| 222 |
self._handle_kernel_info_reply(msg) |
| 223 |
break |
| 224 |
|
| 225 |
if not await self._async_is_alive(): |
| 226 |
msg = "Kernel died before replying to kernel_info" |
| 227 |
raise RuntimeError(msg) |
| 228 |
|
| 229 |
# Check if current time is ready check time plus timeout |
| 230 |
if time.time() > abs_timeout: |
| 231 |
raise RuntimeError("Kernel didn't respond in %d seconds" % timeout) |
| 232 |
|
| 233 |
# Flush IOPub channel |
| 234 |
while True: |
| 235 |
try: |
| 236 |
msg = await ensure_async(self.iopub_channel.get_msg(timeout=0.2)) |
| 237 |
except Empty: |
| 238 |
break |
| 239 |
|
| 240 |
async def _async_recv_reply( |
| 241 |
self, msg_id: str, timeout: float | None = None, channel: str = "shell" |
| 242 |
) -> t.Dict[str, t.Any]: |
| 243 |
"""Receive and return the reply for a given request""" |
| 244 |
if timeout is not None: |
| 245 |
deadline = time.monotonic() + timeout |
| 246 |
while True: |
| 247 |
if timeout is not None: |
| 248 |
timeout = max(0, deadline - time.monotonic()) |
| 249 |
try: |
| 250 |
if channel == "control": |
| 251 |
reply = await self._async_get_control_msg(timeout=timeout) |
| 252 |
else: |
| 253 |
reply = await self._async_get_shell_msg(timeout=timeout) |
| 254 |
except Empty as e: |
| 255 |
msg = "Timeout waiting for reply" |
| 256 |
raise TimeoutError(msg) from e |
| 257 |
if reply["parent_header"].get("msg_id") != msg_id: |
| 258 |
# not my reply, someone may have forgotten to retrieve theirs |
| 259 |
continue |
| 260 |
return reply |
| 261 |
|
| 262 |
async def _stdin_hook_default(self, msg: t.Dict[str, t.Any]) -> None: |
| 263 |
"""Handle an input request""" |
| 264 |
content = msg["content"] |
| 265 |
prompt = getpass if content.get("password", False) else input |
| 266 |
|
| 267 |
try: |
| 268 |
raw_data = prompt(content["prompt"]) |
| 269 |
except EOFError: |
| 270 |
# turn EOFError into EOF character |
| 271 |
raw_data = "\x04" |
| 272 |
except KeyboardInterrupt: |
| 273 |
sys.stdout.write("\n") |
| 274 |
return |
| 275 |
|
| 276 |
# only send stdin reply if there *was not* another request |
| 277 |
# or execution finished while we were reading. |
| 278 |
if not (await self.stdin_channel.msg_ready() or await self.shell_channel.msg_ready()): |
| 279 |
self.input(raw_data) |
| 280 |
|
| 281 |
def _output_hook_default(self, msg: t.Dict[str, t.Any]) -> None: |
| 282 |
"""Default hook for redisplaying plain-text output""" |
| 283 |
msg_type = msg["header"]["msg_type"] |
| 284 |
content = msg["content"] |
| 285 |
if msg_type == "stream": |
| 286 |
stream = getattr(sys, content["name"]) |
| 287 |
stream.write(content["text"]) |
| 288 |
elif msg_type in ("display_data", "execute_result"): |
| 289 |
sys.stdout.write(content["data"].get("text/plain", "")) |
| 290 |
elif msg_type == "error": |
| 291 |
sys.stderr.write("\n".join(content["traceback"])) |
| 292 |
|
| 293 |
def _output_hook_kernel( |
| 294 |
self, |
| 295 |
session: Session, |
| 296 |
socket: zmq.sugar.socket.Socket, |
| 297 |
parent_header: t.Any, |
| 298 |
msg: t.Dict[str, t.Any], |
| 299 |
) -> None: |
| 300 |
"""Output hook when running inside an IPython kernel |
| 301 |
|
| 302 |
adds rich output support. |
| 303 |
""" |
| 304 |
msg_type = msg["header"]["msg_type"] |
| 305 |
if msg_type in ("display_data", "execute_result", "error"): |
| 306 |
session.send(socket, msg_type, msg["content"], parent=parent_header) |
| 307 |
else: |
| 308 |
self._output_hook_default(msg) |
| 309 |
|
| 310 |
# -------------------------------------------------------------------------- |
| 311 |
# Channel management methods |
| 312 |
# -------------------------------------------------------------------------- |
| 313 |
|
| 314 |
def start_channels( |
| 315 |
self, |
| 316 |
shell: bool = True, |
| 317 |
iopub: bool = True, |
| 318 |
stdin: bool = True, |
| 319 |
hb: bool = True, |
| 320 |
control: bool = True, |
| 321 |
) -> None: |
| 322 |
"""Starts the channels for this kernel. |
| 323 |
|
| 324 |
This will create the channels if they do not exist and then start |
| 325 |
them (their activity runs in a thread). If port numbers of 0 are |
| 326 |
being used (random ports) then you must first call |
| 327 |
:meth:`start_kernel`. If the channels have been stopped and you |
| 328 |
call this, :class:`RuntimeError` will be raised. |
| 329 |
""" |
| 330 |
if iopub: |
| 331 |
self.iopub_channel.start() |
| 332 |
if shell: |
| 333 |
self.shell_channel.start() |
| 334 |
if stdin: |
| 335 |
self.stdin_channel.start() |
| 336 |
self.allow_stdin = True |
| 337 |
else: |
| 338 |
self.allow_stdin = False |
| 339 |
if hb: |
| 340 |
self.hb_channel.start() |
| 341 |
if control: |
| 342 |
self.control_channel.start() |
| 343 |
|
| 344 |
def stop_channels(self) -> None: |
| 345 |
"""Stops all the running channels for this kernel. |
| 346 |
|
| 347 |
This stops their event loops and joins their threads. |
| 348 |
""" |
| 349 |
if self.shell_channel.is_alive(): |
| 350 |
self.shell_channel.stop() |
| 351 |
if self.iopub_channel.is_alive(): |
| 352 |
self.iopub_channel.stop() |
| 353 |
if self.stdin_channel.is_alive(): |
| 354 |
self.stdin_channel.stop() |
| 355 |
if self.hb_channel.is_alive(): |
| 356 |
self.hb_channel.stop() |
| 357 |
if self.control_channel.is_alive(): |
| 358 |
self.control_channel.stop() |
| 359 |
|
| 360 |
if self._created_context and not self.context.closed: |
| 361 |
self.context.destroy(linger=100) |
| 362 |
|
| 363 |
@property |
| 364 |
def channels_running(self) -> bool: |
| 365 |
"""Are any of the channels created and running?""" |
| 366 |
return ( |
| 367 |
(self._shell_channel and self.shell_channel.is_alive()) |
| 368 |
or (self._iopub_channel and self.iopub_channel.is_alive()) |
| 369 |
or (self._stdin_channel and self.stdin_channel.is_alive()) |
| 370 |
or (self._hb_channel and self.hb_channel.is_alive()) |
| 371 |
or (self._control_channel and self.control_channel.is_alive()) |
| 372 |
) |
| 373 |
|
| 374 |
ioloop = None # Overridden in subclasses that use pyzmq event loop |
| 375 |
|
| 376 |
@property |
| 377 |
def shell_channel(self) -> t.Any: |
| 378 |
"""Get the shell channel object for this kernel.""" |
| 379 |
if self._shell_channel is None: |
| 380 |
url = self._make_url("shell") |
| 381 |
self.log.debug("connecting shell channel to %s", url) |
| 382 |
socket = self.connect_shell(identity=self.session.bsession) |
| 383 |
self._shell_channel = self.shell_channel_class( # type:ignore[call-arg,abstract] |
| 384 |
socket, self.session, self.ioloop |
| 385 |
) |
| 386 |
return self._shell_channel |
| 387 |
|
| 388 |
@property |
| 389 |
def iopub_channel(self) -> t.Any: |
| 390 |
"""Get the iopub channel object for this kernel.""" |
| 391 |
if self._iopub_channel is None: |
| 392 |
url = self._make_url("iopub") |
| 393 |
self.log.debug("connecting iopub channel to %s", url) |
| 394 |
socket = self.connect_iopub() |
| 395 |
self._iopub_channel = self.iopub_channel_class( # type:ignore[call-arg,abstract] |
| 396 |
socket, self.session, self.ioloop |
| 397 |
) |
| 398 |
return self._iopub_channel |
| 399 |
|
| 400 |
@property |
| 401 |
def stdin_channel(self) -> t.Any: |
| 402 |
"""Get the stdin channel object for this kernel.""" |
| 403 |
if self._stdin_channel is None: |
| 404 |
url = self._make_url("stdin") |
| 405 |
self.log.debug("connecting stdin channel to %s", url) |
| 406 |
socket = self.connect_stdin(identity=self.session.bsession) |
| 407 |
self._stdin_channel = self.stdin_channel_class( # type:ignore[call-arg,abstract] |
| 408 |
socket, self.session, self.ioloop |
| 409 |
) |
| 410 |
return self._stdin_channel |
| 411 |
|
| 412 |
@property |
| 413 |
def hb_channel(self) -> t.Any: |
| 414 |
"""Get the hb channel object for this kernel.""" |
| 415 |
if self._hb_channel is None: |
| 416 |
url = self._make_url("hb") |
| 417 |
self.log.debug("connecting heartbeat channel to %s", url) |
| 418 |
self._hb_channel = self.hb_channel_class( # type:ignore[call-arg,abstract] |
| 419 |
self.context, self.session, url |
| 420 |
) |
| 421 |
return self._hb_channel |
| 422 |
|
| 423 |
@property |
| 424 |
def control_channel(self) -> t.Any: |
| 425 |
"""Get the control channel object for this kernel.""" |
| 426 |
if self._control_channel is None: |
| 427 |
url = self._make_url("control") |
| 428 |
self.log.debug("connecting control channel to %s", url) |
| 429 |
socket = self.connect_control(identity=self.session.bsession) |
| 430 |
self._control_channel = self.control_channel_class( # type:ignore[call-arg,abstract] |
| 431 |
socket, self.session, self.ioloop |
| 432 |
) |
| 433 |
return self._control_channel |
| 434 |
|
| 435 |
async def _async_is_alive(self) -> bool: |
| 436 |
"""Is the kernel process still running?""" |
| 437 |
from .manager import KernelManager |
| 438 |
|
| 439 |
if isinstance(self.parent, KernelManager): |
| 440 |
# This KernelClient was created by a KernelManager, |
| 441 |
# we can ask the parent KernelManager: |
| 442 |
return await self.parent._async_is_alive() |
| 443 |
if self._hb_channel is not None: |
| 444 |
# We don't have access to the KernelManager, |
| 445 |
# so we use the heartbeat. |
| 446 |
return self._hb_channel.is_beating() |
| 447 |
# no heartbeat and not local, we can't tell if it's running, |
| 448 |
# so naively return True |
| 449 |
return True |
| 450 |
|
| 451 |
async def _async_execute_interactive( |
| 452 |
self, |
| 453 |
code: str, |
| 454 |
silent: bool = False, |
| 455 |
store_history: bool = True, |
| 456 |
user_expressions: t.Dict[str, t.Any] | None = None, |
| 457 |
allow_stdin: bool | None = None, |
| 458 |
stop_on_error: bool = True, |
| 459 |
timeout: float | None = None, |
| 460 |
output_hook: t.Callable | None = None, |
| 461 |
stdin_hook: t.Callable | None = None, |
| 462 |
) -> t.Dict[str, t.Any]: |
| 463 |
"""Execute code in the kernel interactively |
| 464 |
|
| 465 |
Output will be redisplayed, and stdin prompts will be relayed as well. |
| 466 |
If an IPython kernel is detected, rich output will be displayed. |
| 467 |
|
| 468 |
You can pass a custom output_hook callable that will be called |
| 469 |
with every IOPub message that is produced instead of the default redisplay. |
| 470 |
|
| 471 |
.. versionadded:: 5.0 |
| 472 |
|
| 473 |
Parameters |
| 474 |
---------- |
| 475 |
code : str |
| 476 |
A string of code in the kernel's language. |
| 477 |
|
| 478 |
silent : bool, optional (default False) |
| 479 |
If set, the kernel will execute the code as quietly possible, and |
| 480 |
will force store_history to be False. |
| 481 |
|
| 482 |
store_history : bool, optional (default True) |
| 483 |
If set, the kernel will store command history. This is forced |
| 484 |
to be False if silent is True. |
| 485 |
|
| 486 |
user_expressions : dict, optional |
| 487 |
A dict mapping names to expressions to be evaluated in the user's |
| 488 |
dict. The expression values are returned as strings formatted using |
| 489 |
:func:`repr`. |
| 490 |
|
| 491 |
allow_stdin : bool, optional (default self.allow_stdin) |
| 492 |
Flag for whether the kernel can send stdin requests to frontends. |
| 493 |
|
| 494 |
Some frontends (e.g. the Notebook) do not support stdin requests. |
| 495 |
If raw_input is called from code executed from such a frontend, a |
| 496 |
StdinNotImplementedError will be raised. |
| 497 |
|
| 498 |
stop_on_error: bool, optional (default True) |
| 499 |
Flag whether to abort the execution queue, if an exception is encountered. |
| 500 |
|
| 501 |
timeout: float or None (default: None) |
| 502 |
Timeout to use when waiting for a reply |
| 503 |
|
| 504 |
output_hook: callable(msg) |
| 505 |
Function to be called with output messages. |
| 506 |
If not specified, output will be redisplayed. |
| 507 |
|
| 508 |
stdin_hook: callable(msg) |
| 509 |
Function or awaitable to be called with stdin_request messages. |
| 510 |
If not specified, input/getpass will be called. |
| 511 |
|
| 512 |
Returns |
| 513 |
------- |
| 514 |
reply: dict |
| 515 |
The reply message for this request |
| 516 |
""" |
| 517 |
if not self.iopub_channel.is_alive(): |
| 518 |
emsg = "IOPub channel must be running to receive output" |
| 519 |
raise RuntimeError(emsg) |
| 520 |
if allow_stdin is None: |
| 521 |
allow_stdin = self.allow_stdin |
| 522 |
if allow_stdin and not self.stdin_channel.is_alive(): |
| 523 |
emsg = "stdin channel must be running to allow input" |
| 524 |
raise RuntimeError(emsg) |
| 525 |
msg_id = await ensure_async( |
| 526 |
self.execute( |
| 527 |
code, |
| 528 |
silent=silent, |
| 529 |
store_history=store_history, |
| 530 |
user_expressions=user_expressions, |
| 531 |
allow_stdin=allow_stdin, |
| 532 |
stop_on_error=stop_on_error, |
| 533 |
) |
| 534 |
) |
| 535 |
if stdin_hook is None: |
| 536 |
stdin_hook = self._stdin_hook_default |
| 537 |
# detect IPython kernel |
| 538 |
if output_hook is None and "IPython" in sys.modules: |
| 539 |
from IPython import get_ipython |
| 540 |
|
| 541 |
ip = get_ipython() # type:ignore[no-untyped-call] |
| 542 |
in_kernel = getattr(ip, "kernel", False) |
| 543 |
if in_kernel: |
| 544 |
output_hook = partial( |
| 545 |
self._output_hook_kernel, |
| 546 |
ip.display_pub.session, |
| 547 |
ip.display_pub.pub_socket, |
| 548 |
ip.display_pub.parent_header, |
| 549 |
) |
| 550 |
if output_hook is None: |
| 551 |
# default: redisplay plain-text outputs |
| 552 |
output_hook = self._output_hook_default |
| 553 |
|
| 554 |
# set deadline based on timeout |
| 555 |
if timeout is not None: |
| 556 |
deadline = time.monotonic() + timeout |
| 557 |
else: |
| 558 |
timeout_ms = None |
| 559 |
|
| 560 |
poller = zmq.asyncio.Poller() |
| 561 |
iopub_socket = self.iopub_channel.socket |
| 562 |
poller.register(iopub_socket, zmq.POLLIN) |
| 563 |
if allow_stdin: |
| 564 |
stdin_socket = self.stdin_channel.socket |
| 565 |
poller.register(stdin_socket, zmq.POLLIN) |
| 566 |
else: |
| 567 |
stdin_socket = None |
| 568 |
|
| 569 |
# wait for output and redisplay it |
| 570 |
while True: |
| 571 |
if timeout is not None: |
| 572 |
timeout = max(0, deadline - time.monotonic()) |
| 573 |
timeout_ms = int(1000 * timeout) |
| 574 |
events = dict(await poller.poll(timeout_ms)) |
| 575 |
if not events: |
| 576 |
emsg = "Timeout waiting for output" |
| 577 |
raise TimeoutError(emsg) |
| 578 |
if stdin_socket in events: |
| 579 |
req = await ensure_async(self.stdin_channel.get_msg(timeout=0)) |
| 580 |
res = stdin_hook(req) |
| 581 |
if inspect.isawaitable(res): |
| 582 |
await res |
| 583 |
continue |
| 584 |
if iopub_socket not in events: |
| 585 |
continue |
| 586 |
|
| 587 |
msg = await ensure_async(self.iopub_channel.get_msg(timeout=0)) |
| 588 |
|
| 589 |
if msg["parent_header"].get("msg_id") != msg_id: |
| 590 |
# not from my request |
| 591 |
continue |
| 592 |
output_hook(msg) |
| 593 |
|
| 594 |
# stop on idle |
| 595 |
if ( |
| 596 |
msg["header"]["msg_type"] == "status" |
| 597 |
and msg["content"]["execution_state"] == "idle" |
| 598 |
): |
| 599 |
break |
| 600 |
|
| 601 |
# output is done, get the reply |
| 602 |
if timeout is not None: |
| 603 |
timeout = max(0, deadline - time.monotonic()) |
| 604 |
return await self._async_recv_reply(msg_id, timeout=timeout) |
| 605 |
|
| 606 |
# Methods to send specific messages on channels |
| 607 |
def execute( |
| 608 |
self, |
| 609 |
code: str, |
| 610 |
silent: bool = False, |
| 611 |
store_history: bool = True, |
| 612 |
user_expressions: t.Dict[str, t.Any] | None = None, |
| 613 |
allow_stdin: bool | None = None, |
| 614 |
stop_on_error: bool = True, |
| 615 |
) -> str: |
| 616 |
"""Execute code in the kernel. |
| 617 |
|
| 618 |
Parameters |
| 619 |
---------- |
| 620 |
code : str |
| 621 |
A string of code in the kernel's language. |
| 622 |
|
| 623 |
silent : bool, optional (default False) |
| 624 |
If set, the kernel will execute the code as quietly possible, and |
| 625 |
will force store_history to be False. |
| 626 |
|
| 627 |
store_history : bool, optional (default True) |
| 628 |
If set, the kernel will store command history. This is forced |
| 629 |
to be False if silent is True. |
| 630 |
|
| 631 |
user_expressions : dict, optional |
| 632 |
A dict mapping names to expressions to be evaluated in the user's |
| 633 |
dict. The expression values are returned as strings formatted using |
| 634 |
:func:`repr`. |
| 635 |
|
| 636 |
allow_stdin : bool, optional (default self.allow_stdin) |
| 637 |
Flag for whether the kernel can send stdin requests to frontends. |
| 638 |
|
| 639 |
Some frontends (e.g. the Notebook) do not support stdin requests. |
| 640 |
If raw_input is called from code executed from such a frontend, a |
| 641 |
StdinNotImplementedError will be raised. |
| 642 |
|
| 643 |
stop_on_error: bool, optional (default True) |
| 644 |
Flag whether to abort the execution queue, if an exception is encountered. |
| 645 |
|
| 646 |
Returns |
| 647 |
------- |
| 648 |
The msg_id of the message sent. |
| 649 |
""" |
| 650 |
if user_expressions is None: |
| 651 |
user_expressions = {} |
| 652 |
if allow_stdin is None: |
| 653 |
allow_stdin = self.allow_stdin |
| 654 |
|
| 655 |
# Don't waste network traffic if inputs are invalid |
| 656 |
if not isinstance(code, str): |
| 657 |
raise ValueError("code %r must be a string" % code) |
| 658 |
validate_string_dict(user_expressions) |
| 659 |
|
| 660 |
# Create class for content/msg creation. Related to, but possibly |
| 661 |
# not in Session. |
| 662 |
content = { |
| 663 |
"code": code, |
| 664 |
"silent": silent, |
| 665 |
"store_history": store_history, |
| 666 |
"user_expressions": user_expressions, |
| 667 |
"allow_stdin": allow_stdin, |
| 668 |
"stop_on_error": stop_on_error, |
| 669 |
} |
| 670 |
msg = self.session.msg("execute_request", content) |
| 671 |
self.shell_channel.send(msg) |
| 672 |
return msg["header"]["msg_id"] |
| 673 |
|
| 674 |
def complete(self, code: str, cursor_pos: int | None = None) -> str: |
| 675 |
"""Tab complete text in the kernel's namespace. |
| 676 |
|
| 677 |
Parameters |
| 678 |
---------- |
| 679 |
code : str |
| 680 |
The context in which completion is requested. |
| 681 |
Can be anything between a variable name and an entire cell. |
| 682 |
cursor_pos : int, optional |
| 683 |
The position of the cursor in the block of code where the completion was requested. |
| 684 |
Default: ``len(code)`` |
| 685 |
|
| 686 |
Returns |
| 687 |
------- |
| 688 |
The msg_id of the message sent. |
| 689 |
""" |
| 690 |
if cursor_pos is None: |
| 691 |
cursor_pos = len(code) |
| 692 |
content = {"code": code, "cursor_pos": cursor_pos} |
| 693 |
msg = self.session.msg("complete_request", content) |
| 694 |
self.shell_channel.send(msg) |
| 695 |
return msg["header"]["msg_id"] |
| 696 |
|
| 697 |
def inspect(self, code: str, cursor_pos: int | None = None, detail_level: int = 0) -> str: |
| 698 |
"""Get metadata information about an object in the kernel's namespace. |
| 699 |
|
| 700 |
It is up to the kernel to determine the appropriate object to inspect. |
| 701 |
|
| 702 |
Parameters |
| 703 |
---------- |
| 704 |
code : str |
| 705 |
The context in which info is requested. |
| 706 |
Can be anything between a variable name and an entire cell. |
| 707 |
cursor_pos : int, optional |
| 708 |
The position of the cursor in the block of code where the info was requested. |
| 709 |
Default: ``len(code)`` |
| 710 |
detail_level : int, optional |
| 711 |
The level of detail for the introspection (0-2) |
| 712 |
|
| 713 |
Returns |
| 714 |
------- |
| 715 |
The msg_id of the message sent. |
| 716 |
""" |
| 717 |
if cursor_pos is None: |
| 718 |
cursor_pos = len(code) |
| 719 |
content = { |
| 720 |
"code": code, |
| 721 |
"cursor_pos": cursor_pos, |
| 722 |
"detail_level": detail_level, |
| 723 |
} |
| 724 |
msg = self.session.msg("inspect_request", content) |
| 725 |
self.shell_channel.send(msg) |
| 726 |
return msg["header"]["msg_id"] |
| 727 |
|
| 728 |
def history( |
| 729 |
self, |
| 730 |
raw: bool = True, |
| 731 |
output: bool = False, |
| 732 |
hist_access_type: str = "range", |
| 733 |
**kwargs: t.Any, |
| 734 |
) -> str: |
| 735 |
"""Get entries from the kernel's history list. |
| 736 |
|
| 737 |
Parameters |
| 738 |
---------- |
| 739 |
raw : bool |
| 740 |
If True, return the raw input. |
| 741 |
output : bool |
| 742 |
If True, then return the output as well. |
| 743 |
hist_access_type : str |
| 744 |
'range' (fill in session, start and stop params), 'tail' (fill in n) |
| 745 |
or 'search' (fill in pattern param). |
| 746 |
|
| 747 |
session : int |
| 748 |
For a range request, the session from which to get lines. Session |
| 749 |
numbers are positive integers; negative ones count back from the |
| 750 |
current session. |
| 751 |
start : int |
| 752 |
The first line number of a history range. |
| 753 |
stop : int |
| 754 |
The final (excluded) line number of a history range. |
| 755 |
|
| 756 |
n : int |
| 757 |
The number of lines of history to get for a tail request. |
| 758 |
|
| 759 |
pattern : str |
| 760 |
The glob-syntax pattern for a search request. |
| 761 |
|
| 762 |
Returns |
| 763 |
------- |
| 764 |
The ID of the message sent. |
| 765 |
""" |
| 766 |
if hist_access_type == "range": |
| 767 |
kwargs.setdefault("session", 0) |
| 768 |
kwargs.setdefault("start", 0) |
| 769 |
content = dict(raw=raw, output=output, hist_access_type=hist_access_type, **kwargs) |
| 770 |
msg = self.session.msg("history_request", content) |
| 771 |
self.shell_channel.send(msg) |
| 772 |
return msg["header"]["msg_id"] |
| 773 |
|
| 774 |
def kernel_info(self) -> str: |
| 775 |
"""Request kernel info |
| 776 |
|
| 777 |
Returns |
| 778 |
------- |
| 779 |
The msg_id of the message sent |
| 780 |
""" |
| 781 |
msg = self.session.msg("kernel_info_request") |
| 782 |
self.shell_channel.send(msg) |
| 783 |
return msg["header"]["msg_id"] |
| 784 |
|
| 785 |
def comm_info(self, target_name: str | None = None) -> str: |
| 786 |
"""Request comm info |
| 787 |
|
| 788 |
Returns |
| 789 |
------- |
| 790 |
The msg_id of the message sent |
| 791 |
""" |
| 792 |
content = {} if target_name is None else {"target_name": target_name} |
| 793 |
msg = self.session.msg("comm_info_request", content) |
| 794 |
self.shell_channel.send(msg) |
| 795 |
return msg["header"]["msg_id"] |
| 796 |
|
| 797 |
def _handle_kernel_info_reply(self, msg: t.Dict[str, t.Any]) -> None: |
| 798 |
"""handle kernel info reply |
| 799 |
|
| 800 |
sets protocol adaptation version. This might |
| 801 |
be run from a separate thread. |
| 802 |
""" |
| 803 |
adapt_version = int(msg["content"]["protocol_version"].split(".")[0]) |
| 804 |
if adapt_version != major_protocol_version: |
| 805 |
self.session.adapt_version = adapt_version |
| 806 |
|
| 807 |
def is_complete(self, code: str) -> str: |
| 808 |
"""Ask the kernel whether some code is complete and ready to execute. |
| 809 |
|
| 810 |
Returns |
| 811 |
------- |
| 812 |
The ID of the message sent. |
| 813 |
""" |
| 814 |
msg = self.session.msg("is_complete_request", {"code": code}) |
| 815 |
self.shell_channel.send(msg) |
| 816 |
return msg["header"]["msg_id"] |
| 817 |
|
| 818 |
def input(self, string: str) -> None: |
| 819 |
"""Send a string of raw input to the kernel. |
| 820 |
|
| 821 |
This should only be called in response to the kernel sending an |
| 822 |
``input_request`` message on the stdin channel. |
| 823 |
|
| 824 |
Returns |
| 825 |
------- |
| 826 |
The ID of the message sent. |
| 827 |
""" |
| 828 |
content = {"value": string} |
| 829 |
msg = self.session.msg("input_reply", content) |
| 830 |
self.stdin_channel.send(msg) |
| 831 |
|
| 832 |
def shutdown(self, restart: bool = False) -> str: |
| 833 |
"""Request an immediate kernel shutdown on the control channel. |
| 834 |
|
| 835 |
Upon receipt of the (empty) reply, client code can safely assume that |
| 836 |
the kernel has shut down and it's safe to forcefully terminate it if |
| 837 |
it's still alive. |
| 838 |
|
| 839 |
The kernel will send the reply via a function registered with Python's |
| 840 |
atexit module, ensuring it's truly done as the kernel is done with all |
| 841 |
normal operation. |
| 842 |
|
| 843 |
Returns |
| 844 |
------- |
| 845 |
The msg_id of the message sent |
| 846 |
""" |
| 847 |
# Send quit message to kernel. Once we implement kernel-side setattr, |
| 848 |
# this should probably be done that way, but for now this will do. |
| 849 |
msg = self.session.msg("shutdown_request", {"restart": restart}) |
| 850 |
self.control_channel.send(msg) |
| 851 |
return msg["header"]["msg_id"] |
| 852 |
|
| 853 |
|
| 854 |
KernelClientABC.register(KernelClient) |