# kernel


<div class="boopcell boop-raw">

</div>

<div class="boopcell boop-note">

<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->

</div>

<div class="boopcell boop-note">

## Thread-safe stdout routing

[`_StdoutRouter`](https://drscotthawley.github.io/boopiter/kernel.html#_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.

</div>

<div class="boopcell boop-note">

## Building output blocks

Helpers that turn raw execution output into the ordered list of display
blocks a cell stores:
[`_collapse_cr`](https://drscotthawley.github.io/boopiter/kernel.html#_collapse_cr)
flattens `\r`-overwritten progress bars,
[`_best_block`](https://drscotthawley.github.io/boopiter/kernel.html#_best_block)
picks the richest MIME rendering of a result, and
[`_flush_figures`](https://drscotthawley.github.io/boopiter/kernel.html#_flush_figures)
captures any still-open matplotlib figures as PNGs.

</div>

<div class="boopcell boop-note">

## Running code synchronously

[`run_code`](https://drscotthawley.github.io/boopiter/kernel.html#run_code)
executes a cell’s source in the shared IPython shell and returns its
output blocks – the simple, blocking path.

</div>

<div class="prose" data-markdown="1">

------------------------------------------------------------------------

<a
href="https://github.com/drscotthawley/boopiter/blob/main/boopiter/kernel.py#L104"
target="_blank" style="float:right; font-size:smaller">source</a>

### run_code

``` python
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.\*

</div>

<div class="boopcell boop-note">

## Streaming from a background thread

For live output,
[`_run_code_bg`](https://drscotthawley.github.io/boopiter/kernel.html#_run_code_bg)
runs the same execution on a background thread with stdout/stderr tee’d
([`_TeeStream`](https://drscotthawley.github.io/boopiter/kernel.html#_teestream))
into a shared buffer, while
[`_RunState`](https://drscotthawley.github.io/boopiter/kernel.html#_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.

</div>
