# spec


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

Build kernel specifications, bootstrap source, and execution results.
Kernel startup lives in `kunda.kernel`.

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

<a
href="https://github.com/vedicreader/kunda/blob/main/kunda/spec.py#L18"
target="_blank" style="float:right; font-size:smaller">source</a>

### run_file_src

``` python
def run_file_src(
    path, src:NoneType=None, argv:tuple=(), cwd:NoneType=None
):
```

*Code that runs a file in the kernel’s* own\* namespace, with script
semantics.\*

[`run_file_src`](https://vedicreader.github.io/kunda/spec.html#run_file_src)
runs a file in the kernel namespace. It sets `sys.argv` and an optional
working directory for the run, then restores both. `src` can supply
unsaved editor text. Tracebacks still use `path`.

``` python
print(run_file_src('/proj/train.py', src='import sys\nprint(sys.argv)\n', argv=['--epochs', '3']))
```

    import os as _kd_os, sys as _kd_sys
    _kd_code = compile('import sys\nprint(sys.argv)\n', '/proj/train.py', "exec")
    _kd_argv, _kd_cwd = _kd_sys.argv, _kd_os.getcwd()
    _kd_sys.argv = ['/proj/train.py', *['--epochs', '3']]
    try: exec(_kd_code)
    finally:
        _kd_sys.argv = _kd_argv
        _kd_os.chdir(_kd_cwd)
        del _kd_os, _kd_sys, _kd_code, _kd_argv, _kd_cwd

`BOOTSTRAP` starts Dhrishti inside the kernel. Host import paths are
used only when the kernel has the same Python minor version. The host
Dhrishti package is preferred, with the project package as fallback.
Temporary bootstrap names are removed.

``` python
args = dict(name='nb-1', port=8123, agent='restricted', token=True, support=['/host/site-packages'],
            sessions='_kunda_sessions', agent_sessions='_kunda_agent_sessions', version=(3, 12),
            dhrishti_init='/host/dhrishti/__init__.py', dhrishti_dir='/host/dhrishti')
src = BOOTSTRAP.format(**args)
print(src)
```

    def _kd_bootstrap():
        import sys, importlib.util
        if tuple(sys.version_info[:2]) == tuple((3, 12)):
            for _p in ['/host/site-packages']:
                if _p and _p not in sys.path: sys.path.append(_p)
        try:
            if tuple(sys.version_info[:2]) != tuple((3, 12)): raise ImportError('another Python')
            for _n in [n for n in sys.modules if n == 'dhrishti' or n.startswith('dhrishti.')]: del sys.modules[_n]
            _spec = importlib.util.spec_from_file_location('dhrishti', '/host/dhrishti/__init__.py', submodule_search_locations=['/host/dhrishti'])
            _pkg = importlib.util.module_from_spec(_spec)
            sys.modules['dhrishti'] = _pkg
            _spec.loader.exec_module(_pkg)
        except Exception:
            for _n in [n for n in sys.modules if n == 'dhrishti' or n.startswith('dhrishti.')]: del sys.modules[_n]
        import dhrishti.serving as ls
        r = ls.serve_in_kernel(name='nb-1', port=8123, agent='restricted', token=True, session_dir='_kunda_sessions', agent_session_dir='_kunda_agent_sessions')
        return r
    try: _kd_bootstrap()
    finally: del _kd_bootstrap

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

<a
href="https://github.com/vedicreader/kunda/blob/main/kunda/spec.py#L56"
target="_blank" style="float:right; font-size:smaller">source</a>

### bootstrap_src

``` python
def bootstrap_src(
    name:NoneType=None, port:int=8000, agent:str='restricted', token:bool=True, sessions:NoneType=None,
    agent_sessions:NoneType=None
):
```

*The bootstrap cell source for a kernel that should host an inspector.*

[`bootstrap_src`](https://vedicreader.github.io/kunda/spec.html#bootstrap_src)
fills the bootstrap template. It finds Dhrishti without importing it. A
missing Dhrishti installation raises `RuntimeError`.

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

<a
href="https://github.com/vedicreader/kunda/blob/main/kunda/spec.py#L67"
target="_blank" style="float:right; font-size:smaller">source</a>

### output_text

``` python
def output_text(
    outs
):
```

*Flatten nbformat outputs to plain text: the terminal rendering, and the
agent’s view of a run.*

[`output_text`](https://vedicreader.github.io/kunda/spec.html#output_text)
converts nbformat outputs to terminal text. It includes streams,
tracebacks, Markdown, and plain text. Other display data is represented
by its MIME type.

``` python
outs = [{'output_type': 'stream', 'name': 'stdout', 'text': 'fitting\n'},
        {'output_type': 'execute_result', 'data': {'text/plain': '0.94'}},
        {'output_type': 'display_data', 'data': {'image/png': 'iVBORw0KGgo'}}]
print(output_text(outs))
```

    fitting
    0.94[image/png]

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

<a
href="https://github.com/vedicreader/kunda/blob/main/kunda/spec.py#L81"
target="_blank" style="float:right; font-size:smaller">source</a>

### ExecOutcome

``` python
def ExecOutcome(
    ok:bool=True, execution_count:int | None=None, outputs:list=<factory>, error:str | None=None
)->None:
```

*Result of one execute_request: nbformat-shaped outputs plus the shell
reply status.*

[`ExecOutcome`](https://vedicreader.github.io/kunda/spec.html#execoutcome)
stores the shell status and nbformat outputs for one execution request.
`text` renders the outputs when read. Kernel errors are returned in the
outcome.

``` python
out = ExecOutcome(execution_count=3, outputs=[{'output_type': 'stream', 'text': 'fitting\n'}])
out.ok, out.execution_count, out.text
```

    (True, 3, 'fitting\n')

[`_runtime_python`](https://vedicreader.github.io/kunda/spec.html#_runtime_python)
returns a selected interpreter. A frozen macOS app uses its bundled
Python helper. Other calls use `sys.executable`.

``` python
_runtime_python('/repo/.venv/bin/python'), _runtime_python() == sys.executable
```

    ('/repo/.venv/bin/python', True)

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

<a
href="https://github.com/vedicreader/kunda/blob/main/kunda/spec.py#L100"
target="_blank" style="float:right; font-size:smaller">source</a>

### KernelStartError

``` python
def KernelStartError(
    *args, **kwargs
):
```

*A kernel that could not start, said in terms of the environment rather
than the protocol.*

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

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

### missing_kernel_module

``` python
def missing_kernel_module(
    python:NoneType=None, kernel:str='ipykernel'
):
```

*The kernel package `python` cannot import, or None.*

[`missing_kernel_module`](https://vedicreader.github.io/kunda/spec.html#missing_kernel_module)
checks whether an interpreter can import its kernel launcher. It returns
`None` when the module exists or the interpreter cannot be checked.

``` python
missing_kernel_module(), missing_kernel_module(kernel='ipymini')
```

    (None, None)

[`_kernel_env`](https://vedicreader.github.io/kunda/spec.html#_kernel_env)
removes frozen-host interpreter redirection. A bundled interpreter
receives the bundle module paths. A selected project interpreter does
not.

[`_spec`](https://vedicreader.github.io/kunda/spec.html#_spec) builds a
Python kernelspec for a selected interpreter. `ipykernel` enables Curve
encryption metadata. Other languages use an installed kernelspec without
modification.

``` python
s = _spec('/repo/.venv/bin/python', name='myrepo')
s.argv, s.metadata
```

    (['/repo/.venv/bin/python',
      '-m',
      'ipykernel_launcher',
      '-f',
      '{connection_file}'],
     {'supported_encryption': 'curve'})

``` python
_spec('/repo/.venv/bin/python', kernel='ipymini').argv
```

    ['/repo/.venv/bin/python',
     '-Xfrozen_modules=off',
     '-m',
     'ipymini',
     '-f',
     '{connection_file}']

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

<a
href="https://github.com/vedicreader/kunda/blob/main/kunda/spec.py#L141"
target="_blank" style="float:right; font-size:smaller">source</a>

### installed_kernels

``` python
def installed_kernels():
```

*Every Jupyter kernelspec on this machine, as `{name: spec}`. An
unreadable store is none.*

[`installed_kernels`](https://vedicreader.github.io/kunda/spec.html#installed_kernels)
returns all readable Jupyter kernelspecs. An unreadable store returns an
empty mapping.

``` python
sorted(installed_kernels())
```

    ['ipymini', 'python3', 'python312']

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

<a
href="https://github.com/vedicreader/kunda/blob/main/kunda/spec.py#L148"
target="_blank" style="float:right; font-size:smaller">source</a>

### kernelspec_for

``` python
def kernelspec_for(
    lang, known:NoneType=None
):
```

*Return the installed kernelspec name for `lang`, checking `known`
first; None if not found.*

[`kernelspec_for`](https://vedicreader.github.io/kunda/spec.html#kernelspec_for)
finds an installed kernelspec by language. A valid entry in `known`
takes priority. Language matching ignores case.

``` python
kernelspec_for('rust'), kernelspec_for('rust', known={'rust': 'xrust'}), kernelspec_for('julia')
```

    ('evcxr', 'xrust', None)

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

<a
href="https://github.com/vedicreader/kunda/blob/main/kunda/spec.py#L156"
target="_blank" style="float:right; font-size:smaller">source</a>

### installed_spec

``` python
def installed_spec(
    lang, known:NoneType=None, install:str=''
):
```

*The `KernelSpec` for `lang`, or a
[`KernelStartError`](https://vedicreader.github.io/kunda/spec.html#kernelstarterror)
naming what would install one.*

[`installed_spec`](https://vedicreader.github.io/kunda/spec.html#installed_spec)
returns the kernelspec for a language. A missing kernelspec raises
[`KernelStartError`](https://vedicreader.github.io/kunda/spec.html#kernelstarterror)
with the supplied install command.

``` python
try: installed_spec('rust', install='cargo install evcxr_jupyter')
except KernelStartError as e: print(e)
```

    no Jupyter kernel is installed for rust. Install one with `cargo install evcxr_jupyter`.
