client.py 30 KB

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