Debian Codegraph @

docs/wrapperkernels.rst

raw
1 Making simple Python wrapper kernels
2 ====================================
3
4 You can reuse IPython's kernel machinery to easily make new kernels.
5 This is useful for languages that have Python bindings, such as `Hy
6 <https://github.com/hylang/hy/>`_ (see
7 `Calysto Hy <https://github.com/Calysto/calysto_hy/#>`_), or languages
8 where the REPL can be controlled in a tty using `pexpect <https://pexpect.readthedocs.io/en/latest/>`_,
9 such as bash.
10
11 .. seealso::
12
13 `bash_kernel <https://github.com/takluyver/bash_kernel>`_
14 A simple kernel for bash, written using this machinery
15
16 The `Metakernel <https://github.com/Calysto/metakernel/#>`_ library makes it easier to
17 write a wrapper kernel that includes a base set of line and cell magics. It
18 also has a ``ProcessKernel`` subclass that makes it easy to write kernels that
19 use ``pexpect``.
20 See `Octave Kernel <https://github.com/Calysto/octave_kernel>`_ as an example.
21
22 If releasing a wrapper kernel as a Python package, see the steps in :ref:`packaging-kernels`.
23
24 Required steps
25 --------------
26
27 Subclass :class:`ipykernel.kernelbase.Kernel`, and implement the
28 following methods and attributes:
29
30 .. class:: MyKernel
31
32 .. attribute:: implementation
33 implementation_version
34 banner
35
36 Information for :ref:`msging_kernel_info` replies. 'Implementation' refers
37 to the kernel (e.g. IPython), rather than the language (e.g. Python).
38 The 'banner' is displayed to the user in console
39 UIs before the first prompt. All of these values are strings.
40
41 .. attribute:: language_info
42
43 Language information for :ref:`msging_kernel_info` replies, in a dictionary.
44 This should contain the key ``mimetype`` with the mimetype of code in the
45 target language (e.g. ``'text/x-python'``), the ``name`` of the language
46 being implemented (e.g. ``'python'``), and ``file_extension`` (e.g.
47 ``'.py'``).
48 It may also contain keys ``codemirror_mode`` and ``pygments_lexer`` if they
49 need to differ from :attr:`language`.
50
51 Other keys may be added to this later.
52
53 .. method:: do_execute(code, silent, store_history=True, user_expressions=None, allow_stdin=False)
54
55 Execute user code.
56
57 :param str code: The code to be executed.
58 :param bool silent: Whether to display output.
59 :param bool store_history: Whether to record this code in history and
60 increase the execution count. If silent is True, this is implicitly
61 False.
62 :param dict user_expressions: Mapping of names to expressions to evaluate
63 after the code has run. You can ignore this if you need to.
64 :param bool allow_stdin: Whether the frontend can provide input on request
65 (e.g. for Python's :func:`raw_input`).
66
67 Your method should return a dict containing the fields described in
68 :ref:`execution_results`. To display output, it can send messages
69 using :meth:`~ipykernel.kernelbase.Kernel.send_response`. If an error
70 occurs during execution, an message of type `error` should be sent
71 through :meth:`~ipykernel.kernelbase.Kernel.send_response`
72 in addition to an :ref:`execution_results` with an `status` of `error`.
73 See :doc:`messaging` for details of the different message types.
74
75 .. automethod:: ipykernel.kernelbase.Kernel.send_response
76
77 To launch your kernel, add this at the end of your module::
78
79 if __name__ == '__main__':
80 from ipykernel.kernelapp import IPKernelApp
81 IPKernelApp.launch_instance(kernel_class=MyKernel)
82
83 Now create a `JSON kernel spec file <https://jupyter-client.readthedocs.io/en/latest/kernels.html#kernel-specs>`_ and install it using ``jupyter kernelspec install </path/to/kernel>``. Place your kernel module anywhere Python can import it (try current directory for testing). Finally, you can run your kernel using ``jupyter console --kernel <mykernelname>``. Note that ``<mykernelname>`` in the below example is ``echo``.
84
85 Example
86 -------
87
88 .. seealso::
89
90 `echo_kernel <https://github.com/jupyter/echo_kernel>`_
91 A packaged, installable version of the condensed example below.
92
93 ``echokernel.py`` will simply echo any input it's given to stdout::
94
95 from ipykernel.kernelbase import Kernel
96
97 class EchoKernel(Kernel):
98 implementation = 'Echo'
99 implementation_version = '1.0'
100 language = 'no-op'
101 language_version = '0.1'
102 language_info = {
103 'name': 'Any text',
104 'mimetype': 'text/plain',
105 'file_extension': '.txt',
106 }
107 banner = "Echo kernel - as useful as a parrot"
108
109 def do_execute(self, code, silent, store_history=True, user_expressions=None,
110 allow_stdin=False):
111 if not silent:
112 stream_content = {'name': 'stdout', 'text': code}
113 self.send_response(self.iopub_socket, 'stream', stream_content)
114
115 return {'status': 'ok',
116 # The base class increments the execution count
117 'execution_count': self.execution_count,
118 'payload': [],
119 'user_expressions': {},
120 }
121
122 if __name__ == '__main__':
123 from ipykernel.kernelapp import IPKernelApp
124 IPKernelApp.launch_instance(kernel_class=EchoKernel)
125
126 Here's the Kernel spec ``kernel.json`` file for this::
127
128 {"argv":["python","-m","echokernel", "-f", "{connection_file}"],
129 "display_name":"Echo"
130 }
131
132
133 Optional steps
134 --------------
135
136 You can override a number of other methods to improve the functionality of your
137 kernel. All of these methods should return a dictionary as described in the
138 relevant section of the :doc:`messaging spec <messaging>`.
139
140 .. class:: MyCustomKernel
141
142 .. method:: do_complete(code, cursor_pos)
143
144 Code completion
145
146 :param str code: The code already present
147 :param int cursor_pos: The position in the code where completion is requested
148
149 .. seealso::
150
151 :ref:`msging_completion` messages
152
153 .. method:: do_inspect(code, cursor_pos, detail_level=0)
154
155 Object introspection
156
157 :param str code: The code
158 :param int cursor_pos: The position in the code where introspection is requested
159 :param int detail_level: 0 or 1 for more or less detail. In IPython, 1 gets
160 the source code.
161
162 .. seealso::
163
164 :ref:`msging_inspection` messages
165
166 .. method:: do_history(hist_access_type, output, raw, session=None, start=None, stop=None, n=None, pattern=None, unique=False)
167
168 History access. Only the relevant parameters for the type of history
169 request concerned will be passed, so your method definition must have defaults
170 for all the arguments shown with defaults here.
171
172 .. seealso::
173
174 :ref:`msging_history` messages
175
176 .. method:: do_is_complete(code)
177
178 Is code entered in a console-like interface complete and ready to execute,
179 or should a continuation prompt be shown?
180
181 :param str code: The code entered so far - possibly multiple lines
182
183 .. seealso::
184
185 :ref:`msging_is_complete` messages
186
187 .. method:: do_shutdown(restart)
188
189 Shutdown the kernel. You only need to handle your own clean up - the kernel
190 machinery will take care of cleaning up its own things before stopping.
191
192 :param bool restart: Whether the kernel will be started again afterwards
193
194 .. seealso::
195
196 :ref:`msging_shutdown` messages