spec

what a kernel is started from: its spec, its bootstrap, and the shape of what it returns

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


source

run_file_src

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 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.

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.

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

source

bootstrap_src

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 fills the bootstrap template. It finds Dhrishti without importing it. A missing Dhrishti installation raises RuntimeError.


source

output_text

def output_text(
    outs
):

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

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.

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]

source

ExecOutcome

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 stores the shell status and nbformat outputs for one execution request. text renders the outputs when read. Kernel errors are returned in the outcome.

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 returns a selected interpreter. A frozen macOS app uses its bundled Python helper. Other calls use sys.executable.

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

source

KernelStartError

def KernelStartError(
    *args, **kwargs
):

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


source

missing_kernel_module

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

The kernel package python cannot import, or None.

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.

missing_kernel_module(), missing_kernel_module(kernel='ipymini')
(None, None)

_kernel_env removes frozen-host interpreter redirection. A bundled interpreter receives the bundle module paths. A selected project interpreter does not.

_spec builds a Python kernelspec for a selected interpreter. ipykernel enables Curve encryption metadata. Other languages use an installed kernelspec without modification.

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'})
_spec('/repo/.venv/bin/python', kernel='ipymini').argv
['/repo/.venv/bin/python',
 '-Xfrozen_modules=off',
 '-m',
 'ipymini',
 '-f',
 '{connection_file}']

source

installed_kernels

def installed_kernels():

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

installed_kernels returns all readable Jupyter kernelspecs. An unreadable store returns an empty mapping.

sorted(installed_kernels())
['ipymini', 'python3', 'python312']

source

kernelspec_for

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

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

kernelspec_for finds an installed kernelspec by language. A valid entry in known takes priority. Language matching ignores case.

kernelspec_for('rust'), kernelspec_for('rust', known={'rust': 'xrust'}), kernelspec_for('julia')
('evcxr', 'xrust', None)

source

installed_spec

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

The KernelSpec for lang, or a KernelStartError naming what would install one.

installed_spec returns the kernelspec for a language. A missing kernelspec raises KernelStartError with the supplied install command.

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`.