Skip to main content

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. loader is inspector_loader: in a kernel of the host’s Python minor version, it loads the host’s Dhrishti, and the kernel’s sys.path does not change. In another version, the kernel imports the Dhrishti of its own environment. Temporary bootstrap names are removed.

args = dict(name='nb-1', port=8123, agent='restricted', token=True, loader='# inspector_loader() goes here',
            sessions='_kunda_sessions', agent_sessions='_kunda_agent_sessions')
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=0, 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, lost:bool=False,
    reason: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. lost marks a run whose reply a dropped gateway connection swallowed after the kernel had finished it, so the outputs may be incomplete and execution_count is unknown.

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

source

runtime_python

def runtime_python(
    python:NoneType=None
):

A selected interpreter, or py2app’s bundled generic Python helper.

runtime_python returns a selected interpreter. A frozen macOS app uses its bundled Python helper. Other calls use sys.executable. A host that spawns its own helper processes, such as a terminal or a language server, asks here so it picks the same interpreter a kernel would.

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. The check reads /dev/null, not the terminal.

missing_kernel_module(), missing_kernel_module(kernel='ipymini')
(None, None)
import os, pty, tempfile
from pathlib import Path
fake = Path(tempfile.mkdtemp())/'python'   # "has the module" only when its stdin is not a terminal
fake.write_text(f'#!{sys.executable}\nimport os, sys; sys.exit(os.isatty(0))\n'); fake.chmod(0o755)
m, s = pty.openpty(); os.write(m, b'x\n')
probe = f"import os, select; from kunda.spec import missing_kernel_module; print(missing_kernel_module({str(fake)!r}), os.read(0, 9) if select.select([0], [], [], 1)[0] else b'')"
got = subprocess.run([sys.executable, '-c', probe], stdin=s, capture_output=True, text=True, timeout=60).stdout.split()
os.close(s); os.close(m)
test_eq(got, ['None', "b'x\\n'"])

source

frozen_pythonpath

def frozen_pythonpath():

Module and extension paths a py2app helper process must inherit.

frozen_pythonpath returns the PYTHONPATH a py2app helper process needs to import the bundle’s modules, or None outside a frozen build. _kernel_env sets it for kernels, and a host passes it to any other child it starts on the bundled interpreter.

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


source

kernel_spec

def kernel_spec(
    python:NoneType=None, name:str='python3', kernel:str='ipykernel', lang:str='python', known:NoneType=None,
    install:str=''
):

Kernelspec pinned to a specific interpreter for Python; other languages return their installed spec unchanged.

kernel_spec builds a Python kernelspec for a selected interpreter. ipykernel enables Curve encryption metadata. Other languages use an installed kernelspec without modification. A host with its own table of languages passes known and install through, the way Kernel does.

s = kernel_spec('/repo/.venv/bin/python', name='myrepo')
s.argv, s.metadata
(['/repo/.venv/bin/python',
  '-m',
  'ipykernel_launcher',
  '-f',
  '{connection_file}'],
 {'supported_encryption': 'curve'})
kernel_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`.