# kernel


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

Run one local or gateway kernel. Execution returns nbformat outputs.
Inspection uses the Dhrishti HTTP API.

`KERNELS` lists supported Python launchers. Unknown launcher names use
`ipykernel`.

[`_give_up_after`](https://vedicreader.github.io/kunda/kernel.html#_give_up_after)
stops waiting for shutdown after the timeout.

``` python
t = time.time()
await _give_up_after(asyncio.sleep(30), timeout=.05)      # the deadline ends this, not the sleep
async def never_answers(): raise RuntimeError('the kernel never answered')
await _give_up_after(never_answers()), time.time() - t < 1
```

    (None, True)

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

### never_answers

``` python
async def never_answers():
```

*Call self as a function.*

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

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

### ipymini_available

``` python
def ipymini_available():
```

*True when the ipymini package can be imported in this interpreter.*

[`ipymini_available`](https://vedicreader.github.io/kunda/kernel.html#ipymini_available)
checks whether the package can be imported without importing it.

``` python
ipymini_available()
```

    True

[`_Inspector`](https://vedicreader.github.io/kunda/kernel.html#_inspector)
holds state and Dhrishti client methods shared by local and gateway
kernels.

``` python
p = Probe('http://127.0.0.1:8123')
p.token, p._headers(), Probe().token
```

    ('S3CRET', {'X-Dhrishti-Token': 'S3CRET'}, None)

``` python
p.touch()
p.busy, p.idle_for < 1, p.kernel_kind
```

    (False, True, 'ipykernel')

`names` returns top-level names from Dhrishti’s grouped response.

``` python
class Rows(Probe):
    "The inspector's answer, without the inspector."
    async def api(self, path, params=None, timeout=15):
        self.asked = path
        return {'groups': [{'name': 'data', 'nodes': [{'name': 'df'}, {'name': 'raw'}]}, {'name': 'other', 'nodes': [{'name': 'x'}]}]}
r = Rows('http://127.0.0.1:8123')
await r.names(), r.asked
```

    (['df', 'raw', 'x'], '/api/rows')

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

### Rows

``` python
def Rows(
    base:NoneType=None, name:str='nb'
):
```

*The inspector’s answer, without the inspector.*

`stop` interrupts the active execution. It restarts the kernel when the
execution does not stop before the timeout.

``` python
async def one_cell(obeys):
    k = Running(obeys)
    return (await k.stop(timeout=.05))['note'], k.restarted
print(await Probe().stop())
for obeys in (True, False): print(await one_cell(obeys))
```

    {'ok': False, 'forced': False, 'note': 'nothing is running'}
    ('cell interrupted', False)
    ('kernel restarted after interrupt was ignored', True)

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

### one_cell

``` python
async def one_cell(
    obeys
):
```

*Call self as a function.*

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

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

### Kernel

``` python
def Kernel(
    cwd:NoneType=None, name:NoneType=None, python:NoneType=None, inspect:bool=True, agent:str='restricted',
    port:int=8000, kernel:str='ipykernel', lang:str='python',
    known:NoneType=None, # the host's `{language: kernelspec}`, handed down by the pool
    install:str='', # what would install a kernel for `lang`, for the error when none is
):
```

*One ipykernel process: execute/complete over jupyter_client, live
variables over its in-kernel.*

[`Kernel`](https://vedicreader.github.io/kunda/kernel.html#kernel) owns
one local kernel process and its Jupyter client. `start` waits for the
kernel and then starts Dhrishti when inspection is enabled.

``` python
k = Kernel(kernel='not-a-kernel', inspect=False)
j = Kernel(cwd='/proj', lang='julia', inspect=True)
k.kernel, (j.kernel, j.inspect, await j.chdir('/proj'))
```

    ('ipykernel', ('ipykernel', False, False))

Execution on a stopped kernel returns a failed
[`ExecOutcome`](https://vedicreader.github.io/kunda/spec.html#execoutcome).
Each request collects only messages with its own parent ID.

``` python
k.alive, k.pid, (await k.execute('1+1')).error, await k.complete('1+', 2), await k.inspect_obj('1+', 2)
```

    (False, None, 'kernel is not running', {'from': 2, 'matches': []}, '')

Registered language kernels use their installed kernelspec. A missing
kernelspec raises
[`KernelStartError`](https://vedicreader.github.io/kunda/spec.html#kernelstarterror).

`_as_output` converts one IOPub message to an nbformat output. Messages
without output return `None`.

``` python
[Kernel._as_output('stream', {'name': 'stdout', 'text': 'hello\n'}),
 Kernel._as_output('execute_result', {'data': {'text/plain': '42'}, 'execution_count': 1}),
 Kernel._as_output('update_display_data', {'data': {'text/plain': 'second'}}),
 Kernel._as_output('status', {'execution_state': 'idle'})]
```

    [{'output_type': 'stream', 'name': 'stdout', 'text': 'hello\n'},
     {'output_type': 'execute_result',
      'data': {'text/plain': '42'},
      'metadata': {},
      'execution_count': 1},
     {'output_type': 'display_data',
      'data': {'text/plain': 'second'},
      'metadata': {}},
     None]

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

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

### check_gateway_deps

``` python
def check_gateway_deps():
```

*Check the gateway dependencies and versions.*

[`check_gateway_deps`](https://vedicreader.github.io/kunda/kernel.html#check_gateway_deps)
reports a missing or incompatible gateway package. `jupyasyncclient`
0.2.8 is excluded because it does not execute requests.

``` python
try: check_gateway_deps()
except RuntimeError as e: print(e)
```

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

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

### GatewayService

``` python
def GatewayService(
    port:int=8787, token:NoneType=None
):
```

*One supervised jupygate for all workspace kernels in this host
process.*

[`GatewayService`](https://vedicreader.github.io/kunda/kernel.html#gatewayservice)
starts one Jupyter gateway for this process and returns its connection
details.

``` python
g = GatewayService(port='8899', token='shared-secret')
g.url, g.server
```

    ('http://127.0.0.1:8899', None)

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

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

### GatewayKernel

``` python
def GatewayKernel(
    gateway, cwd:NoneType=None, name:NoneType=None, python:NoneType=None, inspect:bool=True, agent:str='restricted',
    port:int=8000, kernel:str='ipykernel'
):
```

*The [`Kernel`](https://vedicreader.github.io/kunda/kernel.html#kernel)
interface over jupygate + jupyasyncclient, so a kernel outlives a client
reconnect.*

[`GatewayKernel`](https://vedicreader.github.io/kunda/kernel.html#gatewaykernel)
implements the
[`Kernel`](https://vedicreader.github.io/kunda/kernel.html#kernel)
interface over a gateway WebSocket. The gateway owns the kernel process.

``` python
gk = GatewayKernel(None, name='nb', inspect=False)
gk.alive, gk.pid, gk.lang, gk._boot_name.startswith('nb:'), (await gk.execute('1+1')).error
```

    (False, None, 'python', True, 'kernel is not running')
