kernel
run_code) and streamed from a background thread (_run_code_bg + _RunState/_TeeStream). Deliberately stateless about the notebook: no nb, no _run_state global, no rendering. cells.py owns those and drives these primitives.
Thread-safe stdout routing
_StdoutRouter is installed once as the process’s real sys.stdout/sys.stderr and dispatches each write to a per-thread target – so cells running on different threads never cross-contaminate each other’s output, and ordinary prints still reach the console.
Building output blocks
Helpers that turn raw execution output into the ordered list of display blocks a cell stores: _collapse_cr flattens \r-overwritten progress bars, _best_block picks the richest MIME rendering of a result, and _flush_figures captures any still-open matplotlib figures as PNGs.
Running code synchronously
run_code executes a cell’s source in the shared IPython shell and returns its output blocks – the simple, blocking path.
run_code
def run_code(
src:str
)->list:*Execute src in the shared shell; return an ordered list of output blocks (each a dict with ‘type’ – stream/error/display – and, for display blocks, a ‘mime’ type). See Cell.output. Routes stdout/stderr through _StdoutRouter (same pattern as _run_code_bg) rather than IPython’s own capture_output(stdout=True), whose internal swap is a raw global reassignment – letting this call and a concurrent _run_code_bg (different threads) safely capture their own output at the same time instead of one clobbering the other’s capture window.*
Streaming from a background thread
For live output, _run_code_bg runs the same execution on a background thread with stdout/stderr tee’d (_TeeStream) into a shared buffer, while _RunState tracks the single in-flight run (only one cell executes at a time, like a real kernel). cells.py polls this state to stream output to the browser.