Repository navigation
Description
With ZMQDisplayPublisher.store_display_history = True, a display published while a cell runs is recorded in history_manager.outputs under the next execution count, so %notebook exports it in the following cell.
"""ZMQDisplayPublisher stores a cell's display under the next execution count."""
from _kernel import Kernel
k = Kernel("--ZMQDisplayPublisher.store_display_history=True")
k.run('display("shown by cell 1")')
k.run('"result of cell 2"')
dump = k.run(
"import json\n"
"hm = get_ipython().history_manager\n"
"print(json.dumps({n: [(o.output_type, o.bundle.get('text/plain')) for o in v] for n, v in sorted(hm.outputs.items())}))",
store_history=False,
)
print("history_manager.outputs by execution count:", k.stdout(dump))
k.close()Output:
history_manager.outputs by execution count: {"2": [["display_data", "'shown by cell 1'"], ["execute_result", "'result of cell 2'"]]}
ZMQDisplayPublisher.publish uses self.shell.execution_count and only subtracts 1 during post_execute (the port of ipython/ipython#14998). But run_cell increments execution_count before executing, so during normal execution the current cell is execution_count - 1 as well. IPython's own DisplayPublisher.publish uses execution_count - 1 in both cases.
_kernel.py: a small jupyter_client helper the scripts share
import queue, threading, time
from collections import defaultdict
from jupyter_client import KernelManager
class Kernel:
"""Start an ipykernel; collect iopub messages and shell replies by parent msg_id in background threads."""
def __init__(self, *args):
self.km = KernelManager(kernel_name="python3")
self.km.start_kernel(extra_arguments=list(args))
self.kc = self.km.client()
self.kc.start_channels()
self.kc.wait_for_ready(timeout=30)
self.iopub, self.idle, self.stop = defaultdict(list), defaultdict(threading.Event), False
self.thread = threading.Thread(target=self._pump, daemon=True)
self.thread.start()
def _pump(self):
while not self.stop:
try:
msg = self.kc.get_iopub_msg(timeout=0.2)
except queue.Empty:
continue
parent = msg["parent_header"].get("msg_id")
self.iopub[parent].append(msg)
if msg["msg_type"] == "status" and msg["content"]["execution_state"] == "idle":
self.idle[parent].set()
def subshell(self):
request = self.kc.session.msg("create_subshell_request", {})
self.kc.control_channel.send(request)
return self.kc.get_control_msg(timeout=10)["content"]["subshell_id"]
def send(self, code, subshell=None, store_history=True):
content = dict(code=code, silent=False, store_history=store_history, user_expressions={},
allow_stdin=False, stop_on_error=False)
msg = self.kc.session.msg("execute_request", content)
if subshell:
msg["header"]["subshell_id"] = subshell
self.kc.shell_channel.send(msg)
return msg["header"]["msg_id"]
def wait(self, msg_id):
assert self.idle[msg_id].wait(30)
def run(self, code, **kwargs):
msg_id = self.send(code, **kwargs)
self.wait(msg_id)
return msg_id
def stdout(self, msg_id):
return "".join(m["content"]["text"] for m in self.iopub[msg_id] if m["msg_type"] == "stream")
def close(self):
self.stop = True
self.thread.join()
self.kc.stop_channels()
self.km.shutdown_kernel(now=True)Versions: IPython 9.18.1, ipykernel 7.4.0, jupyter_client 8.10.0, pyzmq 27.3.0, Python 3.13.16, Linux (WSL2). The code involved is unchanged on main as of today.
I found and reduced these while building a tool that drives ipykernel subshells; the investigation and this write-up were done with an AI assistant (🤖🤖). Every output above is pasted from an actual run.
Activity