##// END OF EJS Templates
Merge pull request #5951 from takluyver/kernelbase...
Merge pull request #5951 from takluyver/kernelbase Refactor kernel base class which can be inherited for wrapper kernels

File last commit:

r17096:d2505409 merge
r17098:2fddb199 merge
Show More
wrapperkernels.rst
148 lines | 5.1 KiB | text/x-rst | RstLexer

Making simple Python wrapper kernels

You can now re-use the kernel machinery in IPython to easily make new kernels. This is useful for languages that have Python bindings, such as Octave (via Oct2Py), or languages where the REPL can be controlled in a tty using pexpect, such as bash.

Required steps

Subclass :class:`IPython.kernel.zmq.kernelbase.Kernel`, and implement the following methods and attributes:

To launch your kernel, add this at the end of your module:

if __name__ == '__main__':
    from IPython.kernel.zmq.kernelapp import IPKernelApp
    IPKernelApp.launch_instance(kernel_class=MyKernel)

Example

echokernel.py will simply echo any input it's given to stdout:

from IPython.kernel.zmq.kernelbase import Kernel

class EchoKernel(Kernel):
    implementation = 'Echo'
    implementation_version = '1.0'
    language = 'no-op'
    language_version = '0.1'
    banner = "Echo kernel - as useful as a parrot"

    def do_execute(self, code, silent, store_history=True, user_experssions=None,
                   allow_stdin=False):
        if not silent:
            stream_content = {'name': 'stdout', 'data':code}
            self.send_response(self.iopub_socket, 'stream', stream_content)

        return {'status': 'ok',
                # The base class increments the execution count
                'execution_count': self.execution_count,
                'payload': [],
                'user_expressions': {},
               }

if __name__ == '__main__':
    from IPython.kernel.zmq.kernelapp import IPKernelApp
    IPKernelApp.launch_instance(kernel_class=EchoKernel)

Here's the Kernel spec kernel.json file for this:

{"argv":["python","-m","echokernel", "-f", "{connection_file}"],
 "display_name":"Echo",
 "language":"no-op"
}

Optional steps

You can override a number of other methods to improve the functionality of your kernel. All of these methods should return a dictionary as described in the relevant section of the :doc:`messaging spec <messaging>`.