zmqshell.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794
  1. """A ZMQ-based subclass of InteractiveShell.
  2. This code is meant to ease the refactoring of the base InteractiveShell into
  3. something with a cleaner architecture for 2-process use, without actually
  4. breaking InteractiveShell itself. So we're doing something a bit ugly, where
  5. we subclass and override what we want to fix. Once this is working well, we
  6. can go back to the base class and refactor the code for a cleaner inheritance
  7. implementation that doesn't rely on so much monkeypatching.
  8. But this lets us maintain a fully working IPython as we develop the new
  9. machinery. This should thus be thought of as scaffolding.
  10. """
  11. # Copyright (c) IPython Development Team.
  12. # Distributed under the terms of the Modified BSD License.
  13. import contextvars
  14. import os
  15. import sys
  16. import threading
  17. import typing
  18. import warnings
  19. from pathlib import Path
  20. from IPython.core import page
  21. from IPython.core.autocall import ZMQExitAutocall
  22. from IPython.core.displaypub import DisplayPublisher
  23. from IPython.core.error import UsageError
  24. from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
  25. from IPython.core.magic import Magics, line_magic, magics_class
  26. from IPython.core.magics import CodeMagics, MacroToEdit # type:ignore[attr-defined]
  27. from IPython.core.usage import default_banner
  28. from IPython.display import Javascript, display
  29. from IPython.utils import openpy
  30. from IPython.utils.process import arg_split, system # type:ignore[attr-defined]
  31. from jupyter_client.session import Session, extract_header
  32. from jupyter_core.paths import jupyter_runtime_dir
  33. from traitlets import Any, Bool, CBool, CBytes, Instance, Type, default, observe
  34. from ipykernel import connect_qtconsole, get_connection_file, get_connection_info
  35. from ipykernel.displayhook import ZMQShellDisplayHook
  36. from ipykernel.jsonutil import encode_images, json_clean
  37. try:
  38. from IPython.core.history import HistoryOutput
  39. except ImportError:
  40. HistoryOutput = None # type: ignore[assignment,misc]
  41. # -----------------------------------------------------------------------------
  42. # Functions and classes
  43. # -----------------------------------------------------------------------------
  44. class ZMQDisplayPublisher(DisplayPublisher):
  45. """A display publisher that publishes data using a ZeroMQ PUB socket."""
  46. session = Instance(Session, allow_none=True)
  47. pub_socket = Any(allow_none=True)
  48. _parent_header: contextvars.ContextVar[dict[str, Any]]
  49. topic = CBytes(b"display_data")
  50. store_display_history = Bool(
  51. False,
  52. help="If set to True, store display outputs in the history manager. Default is False.",
  53. ).tag(config=True)
  54. # thread_local:
  55. # An attribute used to ensure the correct output message
  56. # is processed. See ipykernel Issue 113 for a discussion.
  57. _thread_local = Any()
  58. def __init__(self, *args, **kwargs):
  59. super().__init__(*args, **kwargs)
  60. self._parent_header = contextvars.ContextVar("parent_header")
  61. self._parent_header.set({})
  62. self._parent_header_global = {}
  63. @property
  64. def parent_header(self):
  65. try:
  66. return self._parent_header.get()
  67. except LookupError:
  68. return self._parent_header_global
  69. def set_parent(self, parent):
  70. """Set the parent for outbound messages."""
  71. parent_header = extract_header(parent)
  72. self._parent_header.set(parent_header)
  73. self._parent_header_global = parent_header
  74. def _flush_streams(self):
  75. """flush IO Streams prior to display"""
  76. sys.stdout.flush()
  77. sys.stderr.flush()
  78. @default("_thread_local")
  79. def _default_thread_local(self):
  80. """Initialize our thread local storage"""
  81. return threading.local()
  82. @property
  83. def _hooks(self):
  84. if not hasattr(self._thread_local, "hooks"):
  85. # create new list for a new thread
  86. self._thread_local.hooks = []
  87. return self._thread_local.hooks
  88. # Feb: 2025 IPython has a deprecated, `source` parameter, marked for removal that
  89. # triggers typing errors.
  90. def publish( # type:ignore[override]
  91. self,
  92. data,
  93. metadata=None,
  94. *,
  95. transient=None,
  96. update=False,
  97. **kwargs,
  98. ):
  99. """Publish a display-data message
  100. Parameters
  101. ----------
  102. data : dict
  103. A mime-bundle dict, keyed by mime-type.
  104. metadata : dict, optional
  105. Metadata associated with the data.
  106. transient : dict, optional, keyword-only
  107. Transient data that may only be relevant during a live display,
  108. such as display_id.
  109. Transient data should not be persisted to documents.
  110. update : bool, optional, keyword-only
  111. If True, send an update_display_data message instead of display_data.
  112. """
  113. if (
  114. self.store_display_history
  115. and self.shell is not None
  116. and hasattr(self.shell, "history_manager")
  117. and HistoryOutput is not None
  118. ):
  119. # Reference: github.com/ipython/ipython/pull/14998
  120. exec_count = self.shell.execution_count
  121. if getattr(self.shell.display_pub, "_in_post_execute", False):
  122. exec_count -= 1
  123. outputs = getattr(self.shell.history_manager, "outputs", None)
  124. if outputs is not None:
  125. outputs.setdefault(exec_count, []).append(
  126. HistoryOutput(output_type="display_data", bundle=data)
  127. )
  128. self._flush_streams()
  129. if metadata is None:
  130. metadata = {}
  131. if transient is None:
  132. transient = {}
  133. self._validate_data(data, metadata)
  134. content = {}
  135. content["data"] = encode_images(data)
  136. content["metadata"] = metadata
  137. content["transient"] = transient
  138. msg_type = "update_display_data" if update else "display_data"
  139. # Use 2-stage process to send a message,
  140. # in order to put it through the transform
  141. # hooks before potentially sending.
  142. assert self.session is not None
  143. msg = self.session.msg(msg_type, json_clean(content), parent=self.parent_header)
  144. # Each transform either returns a new
  145. # message or None. If None is returned,
  146. # the message has been 'used' and we return.
  147. for hook in self._hooks:
  148. msg = hook(msg)
  149. if msg is None:
  150. return
  151. self.session.send(
  152. self.pub_socket,
  153. msg,
  154. ident=self.topic,
  155. )
  156. def clear_output(self, wait=False):
  157. """Clear output associated with the current execution (cell).
  158. Parameters
  159. ----------
  160. wait : bool (default: False)
  161. If True, the output will not be cleared immediately,
  162. instead waiting for the next display before clearing.
  163. This reduces bounce during repeated clear & display loops.
  164. """
  165. content = dict(wait=wait)
  166. self._flush_streams()
  167. assert self.session is not None
  168. msg = self.session.msg("clear_output", json_clean(content), parent=self.parent_header)
  169. # see publish() for details on how this works
  170. for hook in self._hooks:
  171. msg = hook(msg)
  172. if msg is None:
  173. return
  174. self.session.send(
  175. self.pub_socket,
  176. msg,
  177. ident=self.topic,
  178. )
  179. def register_hook(self, hook):
  180. """
  181. Registers a hook with the thread-local storage.
  182. Parameters
  183. ----------
  184. hook : Any callable object
  185. Returns
  186. -------
  187. Either a publishable message, or `None`.
  188. The DisplayHook objects must return a message from
  189. the __call__ method if they still require the
  190. `session.send` method to be called after transformation.
  191. Returning `None` will halt that execution path, and
  192. session.send will not be called.
  193. """
  194. self._hooks.append(hook)
  195. def unregister_hook(self, hook):
  196. """
  197. Un-registers a hook with the thread-local storage.
  198. Parameters
  199. ----------
  200. hook : Any callable object which has previously been
  201. registered as a hook.
  202. Returns
  203. -------
  204. bool - `True` if the hook was removed, `False` if it wasn't
  205. found.
  206. """
  207. try:
  208. self._hooks.remove(hook)
  209. return True
  210. except ValueError:
  211. return False
  212. @magics_class
  213. class KernelMagics(Magics):
  214. """Kernel magics."""
  215. # ------------------------------------------------------------------------
  216. # Magic overrides
  217. # ------------------------------------------------------------------------
  218. # Once the base class stops inheriting from magic, this code needs to be
  219. # moved into a separate machinery as well. For now, at least isolate here
  220. # the magics which this class needs to implement differently from the base
  221. # class, or that are unique to it.
  222. @line_magic
  223. def edit(self, parameter_s="", last_call=None):
  224. """Bring up an editor and execute the resulting code.
  225. Usage:
  226. %edit [options] [args]
  227. %edit runs an external text editor. You will need to set the command for
  228. this editor via the ``TerminalInteractiveShell.editor`` option in your
  229. configuration file before it will work.
  230. This command allows you to conveniently edit multi-line code right in
  231. your IPython session.
  232. If called without arguments, %edit opens up an empty editor with a
  233. temporary file and will execute the contents of this file when you
  234. close it (don't forget to save it!).
  235. Options:
  236. -n <number>
  237. Open the editor at a specified line number. By default, the IPython
  238. editor hook uses the unix syntax 'editor +N filename', but you can
  239. configure this by providing your own modified hook if your favorite
  240. editor supports line-number specifications with a different syntax.
  241. -p
  242. Call the editor with the same data as the previous time it was used,
  243. regardless of how long ago (in your current session) it was.
  244. -r
  245. Use 'raw' input. This option only applies to input taken from the
  246. user's history. By default, the 'processed' history is used, so that
  247. magics are loaded in their transformed version to valid Python. If
  248. this option is given, the raw input as typed as the command line is
  249. used instead. When you exit the editor, it will be executed by
  250. IPython's own processor.
  251. Arguments:
  252. If arguments are given, the following possibilities exist:
  253. - The arguments are numbers or pairs of colon-separated numbers (like
  254. 1 4:8 9). These are interpreted as lines of previous input to be
  255. loaded into the editor. The syntax is the same of the %macro command.
  256. - If the argument doesn't start with a number, it is evaluated as a
  257. variable and its contents loaded into the editor. You can thus edit
  258. any string which contains python code (including the result of
  259. previous edits).
  260. - If the argument is the name of an object (other than a string),
  261. IPython will try to locate the file where it was defined and open the
  262. editor at the point where it is defined. You can use ``%edit function``
  263. to load an editor exactly at the point where 'function' is defined,
  264. edit it and have the file be executed automatically.
  265. If the object is a macro (see %macro for details), this opens up your
  266. specified editor with a temporary file containing the macro's data.
  267. Upon exit, the macro is reloaded with the contents of the file.
  268. Note: opening at an exact line is only supported under Unix, and some
  269. editors (like kedit and gedit up to Gnome 2.8) do not understand the
  270. '+NUMBER' parameter necessary for this feature. Good editors like
  271. (X)Emacs, vi, jed, pico and joe all do.
  272. - If the argument is not found as a variable, IPython will look for a
  273. file with that name (adding .py if necessary) and load it into the
  274. editor. It will execute its contents with execfile() when you exit,
  275. loading any code in the file into your interactive namespace.
  276. Unlike in the terminal, this is designed to use a GUI editor, and we do
  277. not know when it has closed. So the file you edit will not be
  278. automatically executed or printed.
  279. Note that %edit is also available through the alias %ed.
  280. """
  281. last_call = last_call or ["", ""]
  282. opts, args = self.parse_options(parameter_s, "prn:")
  283. try:
  284. filename, lineno, _ = CodeMagics._find_edit_target(self.shell, args, opts, last_call)
  285. except MacroToEdit:
  286. # TODO: Implement macro editing over 2 processes.
  287. print("Macro editing not yet implemented in 2-process model.")
  288. return
  289. # Make sure we send to the client an absolute path, in case the working
  290. # directory of client and kernel don't match
  291. filename = str(Path(filename).resolve())
  292. payload = {"source": "edit_magic", "filename": filename, "line_number": lineno}
  293. assert self.shell is not None
  294. self.shell.payload_manager.write_payload(payload) # type: ignore[union-attr]
  295. # A few magics that are adapted to the specifics of using pexpect and a
  296. # remote terminal
  297. @line_magic
  298. def clear(self, arg_s):
  299. """Clear the terminal."""
  300. assert self.shell is not None
  301. if os.name == "posix":
  302. self.shell.system("clear")
  303. else:
  304. self.shell.system("cls")
  305. if os.name == "nt":
  306. # This is the usual name in windows
  307. cls = line_magic("cls")(clear)
  308. # Terminal pagers won't work over pexpect, but we do have our own pager
  309. @line_magic
  310. def less(self, arg_s):
  311. """Show a file through the pager.
  312. Files ending in .py are syntax-highlighted."""
  313. if not arg_s:
  314. msg = "Missing filename."
  315. raise UsageError(msg)
  316. if arg_s.endswith(".py"):
  317. assert self.shell is not None
  318. cont = self.shell.pycolorize(openpy.read_py_file(arg_s, skip_encoding_cookie=False))
  319. else:
  320. with open(arg_s) as fid:
  321. cont = fid.read()
  322. page.page(cont)
  323. more = line_magic("more")(less)
  324. # Man calls a pager, so we also need to redefine it
  325. if os.name == "posix":
  326. @line_magic
  327. def man(self, arg_s):
  328. """Find the man page for the given command and display in pager."""
  329. assert self.shell is not None
  330. page.page(self.shell.getoutput("man %s | col -b" % arg_s, split=False))
  331. @line_magic
  332. def connect_info(self, arg_s):
  333. """Print information for connecting other clients to this kernel
  334. It will print the contents of this session's connection file, as well as
  335. shortcuts for local clients.
  336. In the simplest case, when called from the most recently launched kernel,
  337. secondary clients can be connected, simply with:
  338. $> jupyter <app> --existing
  339. """
  340. try:
  341. connection_file = get_connection_file()
  342. info = get_connection_info(unpack=False)
  343. except Exception as e:
  344. warnings.warn("Could not get connection info: %r" % e, stacklevel=2)
  345. return
  346. # if it's in the default dir, truncate to basename
  347. if jupyter_runtime_dir() == str(Path(connection_file).parent):
  348. connection_file = Path(connection_file).name
  349. assert isinstance(info, str)
  350. print(info + "\n")
  351. print(
  352. f"Paste the above JSON into a file, and connect with:\n"
  353. f" $> jupyter <app> --existing <file>\n"
  354. f"or, if you are local, you can connect with just:\n"
  355. f" $> jupyter <app> --existing {connection_file}\n"
  356. f"or even just:\n"
  357. f" $> jupyter <app> --existing\n"
  358. f"if this is the most recent Jupyter kernel you have started."
  359. )
  360. @line_magic
  361. def qtconsole(self, arg_s):
  362. """Open a qtconsole connected to this kernel.
  363. Useful for connecting a qtconsole to running notebooks, for better
  364. debugging.
  365. """
  366. try:
  367. connect_qtconsole(argv=arg_split(arg_s, os.name == "posix"))
  368. except Exception as e:
  369. warnings.warn("Could not start qtconsole: %r" % e, stacklevel=2)
  370. return
  371. @line_magic
  372. def autosave(self, arg_s):
  373. """Set the autosave interval in the notebook (in seconds).
  374. The default value is 120, or two minutes.
  375. ``%autosave 0`` will disable autosave.
  376. This magic only has an effect when called from the notebook interface.
  377. It has no effect when called in a startup file.
  378. """
  379. try:
  380. interval = int(arg_s)
  381. except ValueError as e:
  382. raise UsageError("%%autosave requires an integer, got %r" % arg_s) from e
  383. # javascript wants milliseconds
  384. milliseconds = 1000 * interval
  385. display(
  386. Javascript("IPython.notebook.set_autosave_interval(%i)" % milliseconds),
  387. include=["application/javascript"],
  388. )
  389. if interval:
  390. print("Autosaving every %i seconds" % interval)
  391. else:
  392. print("Autosave disabled")
  393. @line_magic
  394. def subshell(self, arg_s):
  395. """
  396. List all current subshells
  397. """
  398. from ipykernel.kernelapp import IPKernelApp
  399. if not IPKernelApp.initialized():
  400. msg = "Not in a running Kernel"
  401. raise RuntimeError(msg)
  402. app = IPKernelApp.instance()
  403. kernel = app.kernel
  404. if not getattr(kernel, "_supports_kernel_subshells", False):
  405. print("Kernel does not support subshells")
  406. return
  407. thread_id = threading.current_thread().ident
  408. manager = kernel.shell_channel_thread.manager
  409. try:
  410. subshell_id = manager.subshell_id_from_thread_id(thread_id)
  411. except RuntimeError:
  412. subshell_id = "unknown"
  413. subshell_id_list = manager.list_subshell()
  414. print(f"subshell id: {subshell_id}")
  415. print(f"thread id: {thread_id}")
  416. print(f"main thread id: {threading.main_thread().ident}")
  417. print(f"pid: {os.getpid()}")
  418. print(f"thread count: {threading.active_count()}")
  419. print(f"subshell list: {subshell_id_list}")
  420. class ZMQInteractiveShell(InteractiveShell):
  421. """A subclass of InteractiveShell for ZMQ."""
  422. def __init__(self, *args, **kwargs):
  423. super().__init__(*args, **kwargs)
  424. # tqdm has an incorrect detection of ZMQInteractiveShell when launch via
  425. # a scheduler that bypass IPKernelApp Think of JupyterHub cluster
  426. # spawners and co. as of end of Feb 2025, the maintainer has been
  427. # unresponsive for 5 months, to our fix, so we implement a workaround. I
  428. # don't like it but we have few other choices.
  429. # See https://github.com/tqdm/tqdm/pull/1628
  430. if "IPKernelApp" not in self.config:
  431. self.config.IPKernelApp.tqdm = "dummy value for https://github.com/tqdm/tqdm/pull/1628"
  432. self._parent_header = contextvars.ContextVar("parent_header")
  433. self._parent_header.set({})
  434. displayhook_class = Type(ZMQShellDisplayHook)
  435. display_pub_class = Type(ZMQDisplayPublisher)
  436. data_pub_class = Any()
  437. kernel = Any()
  438. _parent_header: contextvars.ContextVar[dict[str, Any]]
  439. @default("banner1")
  440. def _default_banner1(self):
  441. return default_banner
  442. # Override the traitlet in the parent class, because there's no point using
  443. # readline for the kernel. Can be removed when the readline code is moved
  444. # to the terminal frontend.
  445. readline_use = CBool(False)
  446. # autoindent has no meaning in a zmqshell, and attempting to enable it
  447. # will print a warning in the absence of readline.
  448. autoindent = CBool(False)
  449. exiter = Instance(ZMQExitAutocall)
  450. @default("exiter")
  451. def _default_exiter(self):
  452. return ZMQExitAutocall(self)
  453. @observe("exit_now")
  454. def _update_exit_now(self, change):
  455. """stop eventloop when exit_now fires"""
  456. if change["new"]:
  457. if hasattr(self.kernel, "io_loop"):
  458. loop = self.kernel.io_loop
  459. loop.call_later(0.1, loop.stop)
  460. if self.kernel.eventloop:
  461. exit_hook = getattr(self.kernel.eventloop, "exit_hook", None)
  462. if exit_hook:
  463. exit_hook(self.kernel)
  464. keepkernel_on_exit = None
  465. # Over ZeroMQ, GUI control isn't done with PyOS_InputHook as there is no
  466. # interactive input being read; we provide event loop support in ipkernel
  467. def enable_gui(self, gui: typing.Any = None) -> None:
  468. """Enable a given gui."""
  469. from .eventloops import enable_gui as real_enable_gui
  470. try:
  471. real_enable_gui(gui)
  472. self.active_eventloop = gui
  473. except ValueError as e:
  474. raise UsageError("%s" % e) from e
  475. def init_environment(self):
  476. """Configure the user's environment."""
  477. env = os.environ
  478. # These two ensure 'ls' produces nice coloring on BSD-derived systems
  479. env["TERM"] = "xterm-color"
  480. env["CLICOLOR"] = "1"
  481. # These two add terminal color in tools that support it.
  482. env["FORCE_COLOR"] = "1"
  483. env["CLICOLOR_FORCE"] = "1"
  484. # Since normal pagers don't work at all (over pexpect we don't have
  485. # single-key control of the subprocess), try to disable paging in
  486. # subprocesses as much as possible.
  487. env["PAGER"] = "cat"
  488. env["GIT_PAGER"] = "cat"
  489. def payloadpage_page(self, strg, start=0, screen_lines=0, pager_cmd=None):
  490. """Print a string, piping through a pager.
  491. This version ignores the screen_lines and pager_cmd arguments and uses
  492. IPython's payload system instead.
  493. Parameters
  494. ----------
  495. strg : str or mime-dict
  496. Text to page, or a mime-type keyed dict of already formatted data.
  497. start : int
  498. Starting line at which to place the display.
  499. """
  500. # Some routines may auto-compute start offsets incorrectly and pass a
  501. # negative value. Offset to 0 for robustness.
  502. start = max(0, start)
  503. data = strg if isinstance(strg, dict) else {"text/plain": strg}
  504. payload = dict(
  505. source="page",
  506. data=data,
  507. start=start,
  508. )
  509. assert self.payload_manager is not None
  510. self.payload_manager.write_payload(payload)
  511. def init_hooks(self):
  512. """Initialize hooks."""
  513. super().init_hooks()
  514. self.set_hook("show_in_pager", page.as_hook(self.payloadpage_page), 99)
  515. def init_data_pub(self):
  516. """Delay datapub init until request, for deprecation warnings"""
  517. @property
  518. def data_pub(self):
  519. if not hasattr(self, "_data_pub"):
  520. warnings.warn(
  521. "InteractiveShell.data_pub is deprecated outside IPython parallel.",
  522. DeprecationWarning,
  523. stacklevel=2,
  524. )
  525. self._data_pub = self.data_pub_class(parent=self)
  526. self._data_pub.session = self.display_pub.session # type:ignore[attr-defined]
  527. self._data_pub.pub_socket = self.display_pub.pub_socket # type:ignore[attr-defined]
  528. return self._data_pub
  529. @data_pub.setter
  530. def data_pub(self, pub):
  531. self._data_pub = pub
  532. def ask_exit(self):
  533. """Engage the exit actions."""
  534. self.exit_now = not self.keepkernel_on_exit
  535. payload = dict(
  536. source="ask_exit",
  537. keepkernel=self.keepkernel_on_exit,
  538. )
  539. self.payload_manager.write_payload(payload) # type:ignore[union-attr]
  540. def run_cell(self, *args, **kwargs):
  541. """Run a cell."""
  542. self._last_traceback = None
  543. return super().run_cell(*args, **kwargs)
  544. def _showtraceback(self, etype, evalue, stb):
  545. # try to preserve ordering of tracebacks and print statements
  546. sys.stdout.flush()
  547. sys.stderr.flush()
  548. exc_content = {
  549. "traceback": stb,
  550. "ename": str(etype.__name__),
  551. "evalue": str(evalue),
  552. }
  553. dh = self.displayhook
  554. # Send exception info over pub socket for other clients than the caller
  555. # to pick up
  556. topic = None
  557. if dh.topic: # type:ignore[attr-defined]
  558. topic = dh.topic.replace(b"execute_result", b"error") # type:ignore[attr-defined]
  559. dh.session.send( # type:ignore[attr-defined]
  560. dh.pub_socket, # type:ignore[attr-defined]
  561. "error",
  562. json_clean(exc_content),
  563. dh.parent_header, # type:ignore[attr-defined]
  564. ident=topic,
  565. )
  566. # FIXME - Once we rely on Python 3, the traceback is stored on the
  567. # exception object, so we shouldn't need to store it here.
  568. self._last_traceback = stb
  569. def set_next_input(self, text, replace=False):
  570. """Send the specified text to the frontend to be presented at the next
  571. input cell."""
  572. payload = dict(
  573. source="set_next_input",
  574. text=text,
  575. replace=replace,
  576. )
  577. self.payload_manager.write_payload(payload) # type:ignore[union-attr]
  578. @property
  579. def parent_header(self):
  580. try:
  581. return self._parent_header.get()
  582. except LookupError:
  583. return self._parent_header_global
  584. @parent_header.setter
  585. def parent_header(self, value):
  586. self._parent_header_global = value
  587. self._parent_header.set(value)
  588. def set_parent(self, parent):
  589. """Set the parent header for associating output with its triggering input
  590. When called from a thread, sets the thread-local value, which persists
  591. until the next call from this thread.
  592. """
  593. self.parent_header = parent
  594. self.displayhook.set_parent(parent) # type:ignore[attr-defined]
  595. self.display_pub.set_parent(parent) # type:ignore[attr-defined]
  596. if hasattr(self, "_data_pub"):
  597. self.data_pub.set_parent(parent)
  598. if hasattr(sys.stdout, "set_parent"):
  599. sys.stdout.set_parent(parent)
  600. if hasattr(sys.stderr, "set_parent"):
  601. sys.stderr.set_parent(parent)
  602. def get_parent(self):
  603. """Get the parent header.
  604. If set_parent has never been called from the current thread,
  605. the value from the last call to set_parent from _any_ thread will be used
  606. (typically the currently running cell).
  607. """
  608. return self.parent_header
  609. def init_magics(self):
  610. """Initialize magics."""
  611. super().init_magics()
  612. self.register_magics(KernelMagics)
  613. self.magics_manager.register_alias("ed", "edit")
  614. def init_virtualenv(self):
  615. """Initialize virtual environment."""
  616. # Overridden not to do virtualenv detection, because it's probably
  617. # not appropriate in a kernel. To use a kernel in a virtualenv, install
  618. # it inside the virtualenv.
  619. # https://ipython.readthedocs.io/en/latest/install/kernel_install.html
  620. def system_piped(self, cmd):
  621. """Call the given cmd in a subprocess, piping stdout/err
  622. Parameters
  623. ----------
  624. cmd : str
  625. Command to execute (can not end in '&', as background processes are
  626. not supported. Should not be a command that expects input
  627. other than simple text.
  628. """
  629. if cmd.rstrip().endswith("&"):
  630. # this is *far* from a rigorous test
  631. # We do not support backgrounding processes because we either use
  632. # pexpect or pipes to read from. Users can always just call
  633. # os.system() or use ip.system=ip.system_raw
  634. # if they really want a background process.
  635. msg = "Background processes not supported."
  636. raise OSError(msg)
  637. # we explicitly do NOT return the subprocess status code, because
  638. # a non-None value would trigger :func:`sys.displayhook` calls.
  639. # Instead, we store the exit_code in user_ns.
  640. # Also, protect system call from UNC paths on Windows here too
  641. # as is done in InteractiveShell.system_raw
  642. if sys.platform == "win32":
  643. cmd = self.var_expand(cmd, depth=1)
  644. from IPython.utils._process_win32 import AvoidUNCPath
  645. with AvoidUNCPath() as path:
  646. if path is not None:
  647. cmd = f"pushd {path} &&{cmd}"
  648. self.user_ns["_exit_code"] = system(cmd)
  649. else:
  650. self.user_ns["_exit_code"] = system(self.var_expand(cmd, depth=1))
  651. # Ensure new system_piped implementation is used
  652. system = system_piped
  653. InteractiveShellABC.register(ZMQInteractiveShell)