##// END OF EJS Templates
Merge pull request #6179 from takluyver/master...
Thomas Kluyver -
r17296:abffd96e merge
parent child Browse files
Show More
@@ -0,0 +1,152 b''
1 ==========================
2 Making kernels for IPython
3 ==========================
4
5 A 'kernel' is a program that runs and introspects the user's code. IPython
6 includes a kernel for Python code, and people have written kernels for
7 `several other languages <https://github.com/ipython/ipython/wiki/Projects-using-IPython#list-of-some-ipython-compatible-kernels>`_.
8
9 When IPython starts a kernel, it passes it a connection file. This specifies
10 how to set up communications with the frontend.
11
12 There are two options for writing a kernel:
13
14 1. You can reuse the IPython kernel machinery to handle the communications, and
15 just describe how to execute your code. This is much simpler if the target
16 language can be driven from Python. See :doc:`wrapperkernels` for details.
17 2. You can implement the kernel machinery in your target language. This is more
18 work initially, but the people using your kernel might be more likely to
19 contribute to it if it's in the language they know.
20
21 Connection files
22 ================
23
24 Your kernel will be given the path to a connection file when it starts (see
25 :ref:`kernelspecs` for how to specify the command line arguments for your kernel).
26 This file, which is accessible only to the current user, will contain a JSON
27 dictionary looking something like this::
28
29 {
30 "control_port": 50160,
31 "shell_port": 57503,
32 "transport": "tcp",
33 "signature_scheme": "hmac-sha256",
34 "stdin_port": 52597,
35 "hb_port": 42540,
36 "ip": "127.0.0.1",
37 "iopub_port": 40885,
38 "key": "a0436f6c-1916-498b-8eb9-e81ab9368e84"
39 }
40
41 The ``transport``, ``ip`` and five ``_port`` fields specify five ports which the
42 kernel should bind to using `ZeroMQ <http://zeromq.org/>`_. For instance, the
43 address of the shell socket in the example above would be::
44
45 tcp://127.0.0.1:57503
46
47 New ports are chosen at random for each kernel started.
48
49 ``signature_scheme`` and ``key`` are used to cryptographically sign messages, so
50 that other users on the system can't send code to run in this kernel. See
51 :ref:`wire_protocol` for the details of how this signature is calculated.
52
53 Handling messages
54 =================
55
56 After reading the connection file and binding to the necessary sockets, the
57 kernel should go into an event loop, listening on the hb (heartbeat), control
58 and shell sockets.
59
60 :ref:`Heartbeat <kernel_heartbeat>` messages should be echoed back immediately
61 on the same socket - the frontend uses this to check that the kernel is still
62 alive.
63
64 Messages on the control and shell sockets should be parsed, and their signature
65 validated. See :ref:`wire_protocol` for how to do this.
66
67 The kernel will send messages on the iopub socket to display output, and on the
68 stdin socket to prompt the user for textual input.
69
70 .. seealso::
71
72 :doc:`messaging`
73 Details of the different sockets and the messages that come over them
74
75 `Creating Language Kernels for IPython <http://andrew.gibiansky.com/blog/ipython/ipython-kernels/>`_
76 A blog post by the author of `IHaskell <https://github.com/gibiansky/IHaskell>`_,
77 a Haskell kernel
78
79 `simple_kernel <https://github.com/dsblank/simple_kernel>`_
80 A simple example implementation of the kernel machinery in Python
81
82
83 .. _kernelspecs:
84
85 Kernel specs
86 ============
87
88 A kernel identifies itself to IPython by creating a directory, the name of which
89 is used as an identifier for the kernel. These may be created in a number of
90 locations:
91
92 +--------+--------------------------------------+-----------------------------------+
93 | | Unix | Windows |
94 +========+======================================+===================================+
95 | System | ``/usr/share/ipython/kernels`` | ``%PROGRAMDATA%\ipython\kernels`` |
96 | | | |
97 | | ``/usr/local/share/ipython/kernels`` | |
98 +--------+--------------------------------------+-----------------------------------+
99 | User | ``~/.ipython/kernels`` |
100 +--------+--------------------------------------+-----------------------------------+
101
102 The user location takes priority over the system locations, and the case of the
103 names is ignored, so selecting kernels works the same way whether or not the
104 filesystem is case sensitive.
105
106 Inside the directory, the most important file is *kernel.json*. This should be a
107 JSON serialised dictionary containing the following keys and values:
108
109 - **argv**: A list of command line arguments used to start the kernel. The text
110 ``{connection_file}`` in any argument will be replaced with the path to the
111 connection file.
112 - **display_name**: The kernel's name as it should be displayed in the UI.
113 Unlike the kernel name used in the API, this can contain arbitrary unicode
114 characters.
115 - **language**: The programming language which this kernel runs. This will be
116 stored in notebook metadata. This may be used by syntax highlighters to guess
117 how to parse code in a notebook, and frontends may eventually use it to
118 identify alternative kernels that can run some code.
119 - **codemirror_mode** (optional): The `codemirror mode <http://codemirror.net/mode/index.html>`_
120 to use for code in this language. This can be a string or a dictionary, as
121 passed to codemirror config. The string from *language* will be used if this is
122 not provided.
123 - **env** (optional): A dictionary of environment variables to set for the kernel.
124 These will be added to the current environment variables before the kernel is
125 started.
126 - **help_links** (optional): A list of dictionaries, each with keys 'text' and
127 'url'. These will be displayed in the help menu in the notebook UI.
128
129 For example, the kernel.json file for IPython looks like this::
130
131 {
132 "argv": ["python3", "-c", "from IPython.kernel.zmq.kernelapp import main; main()",
133 "-f", "{connection_file}"],
134 "codemirror_mode": {
135 "version": 3,
136 "name": "ipython"
137 },
138 "display_name": "IPython (Python 3)",
139 "language": "python"
140 }
141
142 To see the available kernel specs, run::
143
144 ipython kernelspec list
145
146 To start the terminal console or the Qt console with a specific kernel::
147
148 ipython console --kernel bash
149 ipython qtconsole --kernel bash
150
151 To use different kernels in the notebook, select a different kernel from the
152 dropdown menu in the top-right of the UI.
@@ -1,1063 +1,1066 b''
1 .. _messaging:
1 .. _messaging:
2
2
3 ======================
3 ======================
4 Messaging in IPython
4 Messaging in IPython
5 ======================
5 ======================
6
6
7
7
8 Versioning
8 Versioning
9 ==========
9 ==========
10
10
11 The IPython message specification is versioned independently of IPython.
11 The IPython message specification is versioned independently of IPython.
12 The current version of the specification is 5.0.
12 The current version of the specification is 5.0.
13
13
14
14
15 Introduction
15 Introduction
16 ============
16 ============
17
17
18 This document explains the basic communications design and messaging
18 This document explains the basic communications design and messaging
19 specification for how the various IPython objects interact over a network
19 specification for how the various IPython objects interact over a network
20 transport. The current implementation uses the ZeroMQ_ library for messaging
20 transport. The current implementation uses the ZeroMQ_ library for messaging
21 within and between hosts.
21 within and between hosts.
22
22
23 .. Note::
23 .. Note::
24
24
25 This document should be considered the authoritative description of the
25 This document should be considered the authoritative description of the
26 IPython messaging protocol, and all developers are strongly encouraged to
26 IPython messaging protocol, and all developers are strongly encouraged to
27 keep it updated as the implementation evolves, so that we have a single
27 keep it updated as the implementation evolves, so that we have a single
28 common reference for all protocol details.
28 common reference for all protocol details.
29
29
30 The basic design is explained in the following diagram:
30 The basic design is explained in the following diagram:
31
31
32 .. image:: figs/frontend-kernel.png
32 .. image:: figs/frontend-kernel.png
33 :width: 450px
33 :width: 450px
34 :alt: IPython kernel/frontend messaging architecture.
34 :alt: IPython kernel/frontend messaging architecture.
35 :align: center
35 :align: center
36 :target: ../_images/frontend-kernel.png
36 :target: ../_images/frontend-kernel.png
37
37
38 A single kernel can be simultaneously connected to one or more frontends. The
38 A single kernel can be simultaneously connected to one or more frontends. The
39 kernel has three sockets that serve the following functions:
39 kernel has three sockets that serve the following functions:
40
40
41 1. Shell: this single ROUTER socket allows multiple incoming connections from
41 1. Shell: this single ROUTER socket allows multiple incoming connections from
42 frontends, and this is the socket where requests for code execution, object
42 frontends, and this is the socket where requests for code execution, object
43 information, prompts, etc. are made to the kernel by any frontend. The
43 information, prompts, etc. are made to the kernel by any frontend. The
44 communication on this socket is a sequence of request/reply actions from
44 communication on this socket is a sequence of request/reply actions from
45 each frontend and the kernel.
45 each frontend and the kernel.
46
46
47 2. IOPub: this socket is the 'broadcast channel' where the kernel publishes all
47 2. IOPub: this socket is the 'broadcast channel' where the kernel publishes all
48 side effects (stdout, stderr, etc.) as well as the requests coming from any
48 side effects (stdout, stderr, etc.) as well as the requests coming from any
49 client over the shell socket and its own requests on the stdin socket. There
49 client over the shell socket and its own requests on the stdin socket. There
50 are a number of actions in Python which generate side effects: :func:`print`
50 are a number of actions in Python which generate side effects: :func:`print`
51 writes to ``sys.stdout``, errors generate tracebacks, etc. Additionally, in
51 writes to ``sys.stdout``, errors generate tracebacks, etc. Additionally, in
52 a multi-client scenario, we want all frontends to be able to know what each
52 a multi-client scenario, we want all frontends to be able to know what each
53 other has sent to the kernel (this can be useful in collaborative scenarios,
53 other has sent to the kernel (this can be useful in collaborative scenarios,
54 for example). This socket allows both side effects and the information
54 for example). This socket allows both side effects and the information
55 about communications taking place with one client over the shell channel
55 about communications taking place with one client over the shell channel
56 to be made available to all clients in a uniform manner.
56 to be made available to all clients in a uniform manner.
57
57
58 3. stdin: this ROUTER socket is connected to all frontends, and it allows
58 3. stdin: this ROUTER socket is connected to all frontends, and it allows
59 the kernel to request input from the active frontend when :func:`raw_input` is called.
59 the kernel to request input from the active frontend when :func:`raw_input` is called.
60 The frontend that executed the code has a DEALER socket that acts as a 'virtual keyboard'
60 The frontend that executed the code has a DEALER socket that acts as a 'virtual keyboard'
61 for the kernel while this communication is happening (illustrated in the
61 for the kernel while this communication is happening (illustrated in the
62 figure by the black outline around the central keyboard). In practice,
62 figure by the black outline around the central keyboard). In practice,
63 frontends may display such kernel requests using a special input widget or
63 frontends may display such kernel requests using a special input widget or
64 otherwise indicating that the user is to type input for the kernel instead
64 otherwise indicating that the user is to type input for the kernel instead
65 of normal commands in the frontend.
65 of normal commands in the frontend.
66
66
67 All messages are tagged with enough information (details below) for clients
67 All messages are tagged with enough information (details below) for clients
68 to know which messages come from their own interaction with the kernel and
68 to know which messages come from their own interaction with the kernel and
69 which ones are from other clients, so they can display each type
69 which ones are from other clients, so they can display each type
70 appropriately.
70 appropriately.
71
71
72 4. Control: This channel is identical to Shell, but operates on a separate socket,
72 4. Control: This channel is identical to Shell, but operates on a separate socket,
73 to allow important messages to avoid queueing behind execution requests (e.g. shutdown or abort).
73 to allow important messages to avoid queueing behind execution requests (e.g. shutdown or abort).
74
74
75 The actual format of the messages allowed on each of these channels is
75 The actual format of the messages allowed on each of these channels is
76 specified below. Messages are dicts of dicts with string keys and values that
76 specified below. Messages are dicts of dicts with string keys and values that
77 are reasonably representable in JSON. Our current implementation uses JSON
77 are reasonably representable in JSON. Our current implementation uses JSON
78 explicitly as its message format, but this shouldn't be considered a permanent
78 explicitly as its message format, but this shouldn't be considered a permanent
79 feature. As we've discovered that JSON has non-trivial performance issues due
79 feature. As we've discovered that JSON has non-trivial performance issues due
80 to excessive copying, we may in the future move to a pure pickle-based raw
80 to excessive copying, we may in the future move to a pure pickle-based raw
81 message format. However, it should be possible to easily convert from the raw
81 message format. However, it should be possible to easily convert from the raw
82 objects to JSON, since we may have non-python clients (e.g. a web frontend).
82 objects to JSON, since we may have non-python clients (e.g. a web frontend).
83 As long as it's easy to make a JSON version of the objects that is a faithful
83 As long as it's easy to make a JSON version of the objects that is a faithful
84 representation of all the data, we can communicate with such clients.
84 representation of all the data, we can communicate with such clients.
85
85
86 .. Note::
86 .. Note::
87
87
88 Not all of these have yet been fully fleshed out, but the key ones are, see
88 Not all of these have yet been fully fleshed out, but the key ones are, see
89 kernel and frontend files for actual implementation details.
89 kernel and frontend files for actual implementation details.
90
90
91 General Message Format
91 General Message Format
92 ======================
92 ======================
93
93
94 A message is defined by the following four-dictionary structure::
94 A message is defined by the following four-dictionary structure::
95
95
96 {
96 {
97 # The message header contains a pair of unique identifiers for the
97 # The message header contains a pair of unique identifiers for the
98 # originating session and the actual message id, in addition to the
98 # originating session and the actual message id, in addition to the
99 # username for the process that generated the message. This is useful in
99 # username for the process that generated the message. This is useful in
100 # collaborative settings where multiple users may be interacting with the
100 # collaborative settings where multiple users may be interacting with the
101 # same kernel simultaneously, so that frontends can label the various
101 # same kernel simultaneously, so that frontends can label the various
102 # messages in a meaningful way.
102 # messages in a meaningful way.
103 'header' : {
103 'header' : {
104 'msg_id' : uuid,
104 'msg_id' : uuid,
105 'username' : str,
105 'username' : str,
106 'session' : uuid,
106 'session' : uuid,
107 # All recognized message type strings are listed below.
107 # All recognized message type strings are listed below.
108 'msg_type' : str,
108 'msg_type' : str,
109 # the message protocol version
109 # the message protocol version
110 'version' : '5.0',
110 'version' : '5.0',
111 },
111 },
112
112
113 # In a chain of messages, the header from the parent is copied so that
113 # In a chain of messages, the header from the parent is copied so that
114 # clients can track where messages come from.
114 # clients can track where messages come from.
115 'parent_header' : dict,
115 'parent_header' : dict,
116
116
117 # Any metadata associated with the message.
117 # Any metadata associated with the message.
118 'metadata' : dict,
118 'metadata' : dict,
119
119
120 # The actual content of the message must be a dict, whose structure
120 # The actual content of the message must be a dict, whose structure
121 # depends on the message type.
121 # depends on the message type.
122 'content' : dict,
122 'content' : dict,
123 }
123 }
124
124
125 .. versionchanged:: 5.0
125 .. versionchanged:: 5.0
126
126
127 ``version`` key added to the header.
127 ``version`` key added to the header.
128
128
129 .. _wire_protocol:
130
129 The Wire Protocol
131 The Wire Protocol
130 =================
132 =================
131
133
132
134
133 This message format exists at a high level,
135 This message format exists at a high level,
134 but does not describe the actual *implementation* at the wire level in zeromq.
136 but does not describe the actual *implementation* at the wire level in zeromq.
135 The canonical implementation of the message spec is our :class:`~IPython.kernel.zmq.session.Session` class.
137 The canonical implementation of the message spec is our :class:`~IPython.kernel.zmq.session.Session` class.
136
138
137 .. note::
139 .. note::
138
140
139 This section should only be relevant to non-Python consumers of the protocol.
141 This section should only be relevant to non-Python consumers of the protocol.
140 Python consumers should simply import and use IPython's own implementation of the wire protocol
142 Python consumers should simply import and use IPython's own implementation of the wire protocol
141 in the :class:`IPython.kernel.zmq.session.Session` object.
143 in the :class:`IPython.kernel.zmq.session.Session` object.
142
144
143 Every message is serialized to a sequence of at least six blobs of bytes:
145 Every message is serialized to a sequence of at least six blobs of bytes:
144
146
145 .. sourcecode:: python
147 .. sourcecode:: python
146
148
147 [
149 [
148 b'u-u-i-d', # zmq identity(ies)
150 b'u-u-i-d', # zmq identity(ies)
149 b'<IDS|MSG>', # delimiter
151 b'<IDS|MSG>', # delimiter
150 b'baddad42', # HMAC signature
152 b'baddad42', # HMAC signature
151 b'{header}', # serialized header dict
153 b'{header}', # serialized header dict
152 b'{parent_header}', # serialized parent header dict
154 b'{parent_header}', # serialized parent header dict
153 b'{metadata}', # serialized metadata dict
155 b'{metadata}', # serialized metadata dict
154 b'{content}, # serialized content dict
156 b'{content}, # serialized content dict
155 b'blob', # extra raw data buffer(s)
157 b'blob', # extra raw data buffer(s)
156 ...
158 ...
157 ]
159 ]
158
160
159 The front of the message is the ZeroMQ routing prefix,
161 The front of the message is the ZeroMQ routing prefix,
160 which can be zero or more socket identities.
162 which can be zero or more socket identities.
161 This is every piece of the message prior to the delimiter key ``<IDS|MSG>``.
163 This is every piece of the message prior to the delimiter key ``<IDS|MSG>``.
162 In the case of IOPub, there should be just one prefix component,
164 In the case of IOPub, there should be just one prefix component,
163 which is the topic for IOPub subscribers, e.g. ``execute_result``, ``display_data``.
165 which is the topic for IOPub subscribers, e.g. ``execute_result``, ``display_data``.
164
166
165 .. note::
167 .. note::
166
168
167 In most cases, the IOPub topics are irrelevant and completely ignored,
169 In most cases, the IOPub topics are irrelevant and completely ignored,
168 because frontends just subscribe to all topics.
170 because frontends just subscribe to all topics.
169 The convention used in the IPython kernel is to use the msg_type as the topic,
171 The convention used in the IPython kernel is to use the msg_type as the topic,
170 and possibly extra information about the message, e.g. ``execute_result`` or ``stream.stdout``
172 and possibly extra information about the message, e.g. ``execute_result`` or ``stream.stdout``
171
173
172 After the delimiter is the `HMAC`_ signature of the message, used for authentication.
174 After the delimiter is the `HMAC`_ signature of the message, used for authentication.
173 If authentication is disabled, this should be an empty string.
175 If authentication is disabled, this should be an empty string.
174 By default, the hashing function used for computing these signatures is sha256.
176 By default, the hashing function used for computing these signatures is sha256.
175
177
176 .. _HMAC: http://en.wikipedia.org/wiki/HMAC
178 .. _HMAC: http://en.wikipedia.org/wiki/HMAC
177
179
178 .. note::
180 .. note::
179
181
180 To disable authentication and signature checking,
182 To disable authentication and signature checking,
181 set the `key` field of a connection file to an empty string.
183 set the `key` field of a connection file to an empty string.
182
184
183 The signature is the HMAC hex digest of the concatenation of:
185 The signature is the HMAC hex digest of the concatenation of:
184
186
185 - A shared key (typically the ``key`` field of a connection file)
187 - A shared key (typically the ``key`` field of a connection file)
186 - The serialized header dict
188 - The serialized header dict
187 - The serialized parent header dict
189 - The serialized parent header dict
188 - The serialized metadata dict
190 - The serialized metadata dict
189 - The serialized content dict
191 - The serialized content dict
190
192
191 In Python, this is implemented via:
193 In Python, this is implemented via:
192
194
193 .. sourcecode:: python
195 .. sourcecode:: python
194
196
195 # once:
197 # once:
196 digester = HMAC(key, digestmod=hashlib.sha256)
198 digester = HMAC(key, digestmod=hashlib.sha256)
197
199
198 # for each message
200 # for each message
199 d = digester.copy()
201 d = digester.copy()
200 for serialized_dict in (header, parent, metadata, content):
202 for serialized_dict in (header, parent, metadata, content):
201 d.update(serialized_dict)
203 d.update(serialized_dict)
202 signature = d.hexdigest()
204 signature = d.hexdigest()
203
205
204 After the signature is the actual message, always in four frames of bytes.
206 After the signature is the actual message, always in four frames of bytes.
205 The four dictionaries that compose a message are serialized separately,
207 The four dictionaries that compose a message are serialized separately,
206 in the order of header, parent header, metadata, and content.
208 in the order of header, parent header, metadata, and content.
207 These can be serialized by any function that turns a dict into bytes.
209 These can be serialized by any function that turns a dict into bytes.
208 The default and most common serialization is JSON, but msgpack and pickle
210 The default and most common serialization is JSON, but msgpack and pickle
209 are common alternatives.
211 are common alternatives.
210
212
211 After the serialized dicts are zero to many raw data buffers,
213 After the serialized dicts are zero to many raw data buffers,
212 which can be used by message types that support binary data (mainly apply and data_pub).
214 which can be used by message types that support binary data (mainly apply and data_pub).
213
215
214
216
215 Python functional API
217 Python functional API
216 =====================
218 =====================
217
219
218 As messages are dicts, they map naturally to a ``func(**kw)`` call form. We
220 As messages are dicts, they map naturally to a ``func(**kw)`` call form. We
219 should develop, at a few key points, functional forms of all the requests that
221 should develop, at a few key points, functional forms of all the requests that
220 take arguments in this manner and automatically construct the necessary dict
222 take arguments in this manner and automatically construct the necessary dict
221 for sending.
223 for sending.
222
224
223 In addition, the Python implementation of the message specification extends
225 In addition, the Python implementation of the message specification extends
224 messages upon deserialization to the following form for convenience::
226 messages upon deserialization to the following form for convenience::
225
227
226 {
228 {
227 'header' : dict,
229 'header' : dict,
228 # The msg's unique identifier and type are always stored in the header,
230 # The msg's unique identifier and type are always stored in the header,
229 # but the Python implementation copies them to the top level.
231 # but the Python implementation copies them to the top level.
230 'msg_id' : uuid,
232 'msg_id' : uuid,
231 'msg_type' : str,
233 'msg_type' : str,
232 'parent_header' : dict,
234 'parent_header' : dict,
233 'content' : dict,
235 'content' : dict,
234 'metadata' : dict,
236 'metadata' : dict,
235 }
237 }
236
238
237 All messages sent to or received by any IPython process should have this
239 All messages sent to or received by any IPython process should have this
238 extended structure.
240 extended structure.
239
241
240
242
241 Messages on the shell ROUTER/DEALER sockets
243 Messages on the shell ROUTER/DEALER sockets
242 ===========================================
244 ===========================================
243
245
244 .. _execute:
246 .. _execute:
245
247
246 Execute
248 Execute
247 -------
249 -------
248
250
249 This message type is used by frontends to ask the kernel to execute code on
251 This message type is used by frontends to ask the kernel to execute code on
250 behalf of the user, in a namespace reserved to the user's variables (and thus
252 behalf of the user, in a namespace reserved to the user's variables (and thus
251 separate from the kernel's own internal code and variables).
253 separate from the kernel's own internal code and variables).
252
254
253 Message type: ``execute_request``::
255 Message type: ``execute_request``::
254
256
255 content = {
257 content = {
256 # Source code to be executed by the kernel, one or more lines.
258 # Source code to be executed by the kernel, one or more lines.
257 'code' : str,
259 'code' : str,
258
260
259 # A boolean flag which, if True, signals the kernel to execute
261 # A boolean flag which, if True, signals the kernel to execute
260 # this code as quietly as possible.
262 # this code as quietly as possible.
261 # silent=True forces store_history to be False,
263 # silent=True forces store_history to be False,
262 # and will *not*:
264 # and will *not*:
263 # - broadcast output on the IOPUB channel
265 # - broadcast output on the IOPUB channel
264 # - have an execute_result
266 # - have an execute_result
265 # The default is False.
267 # The default is False.
266 'silent' : bool,
268 'silent' : bool,
267
269
268 # A boolean flag which, if True, signals the kernel to populate history
270 # A boolean flag which, if True, signals the kernel to populate history
269 # The default is True if silent is False. If silent is True, store_history
271 # The default is True if silent is False. If silent is True, store_history
270 # is forced to be False.
272 # is forced to be False.
271 'store_history' : bool,
273 'store_history' : bool,
272
274
273 # A dict mapping names to expressions to be evaluated in the
275 # A dict mapping names to expressions to be evaluated in the
274 # user's dict. The rich display-data representation of each will be evaluated after execution.
276 # user's dict. The rich display-data representation of each will be evaluated after execution.
275 # See the display_data content for the structure of the representation data.
277 # See the display_data content for the structure of the representation data.
276 'user_expressions' : dict,
278 'user_expressions' : dict,
277
279
278 # Some frontends do not support stdin requests.
280 # Some frontends do not support stdin requests.
279 # If raw_input is called from code executed from such a frontend,
281 # If raw_input is called from code executed from such a frontend,
280 # a StdinNotImplementedError will be raised.
282 # a StdinNotImplementedError will be raised.
281 'allow_stdin' : True,
283 'allow_stdin' : True,
282 }
284 }
283
285
284 .. versionchanged:: 5.0
286 .. versionchanged:: 5.0
285
287
286 ``user_variables`` removed, because it is redundant with user_expressions.
288 ``user_variables`` removed, because it is redundant with user_expressions.
287
289
288 The ``code`` field contains a single string (possibly multiline) to be executed.
290 The ``code`` field contains a single string (possibly multiline) to be executed.
289
291
290 The ``user_expressions`` field deserves a detailed explanation. In the past, IPython had
292 The ``user_expressions`` field deserves a detailed explanation. In the past, IPython had
291 the notion of a prompt string that allowed arbitrary code to be evaluated, and
293 the notion of a prompt string that allowed arbitrary code to be evaluated, and
292 this was put to good use by many in creating prompts that displayed system
294 this was put to good use by many in creating prompts that displayed system
293 status, path information, and even more esoteric uses like remote instrument
295 status, path information, and even more esoteric uses like remote instrument
294 status acquired over the network. But now that IPython has a clean separation
296 status acquired over the network. But now that IPython has a clean separation
295 between the kernel and the clients, the kernel has no prompt knowledge; prompts
297 between the kernel and the clients, the kernel has no prompt knowledge; prompts
296 are a frontend feature, and it should be even possible for different
298 are a frontend feature, and it should be even possible for different
297 frontends to display different prompts while interacting with the same kernel.
299 frontends to display different prompts while interacting with the same kernel.
298 ``user_expressions`` can be used to retrieve this information.
300 ``user_expressions`` can be used to retrieve this information.
299
301
300 Any error in evaluating any expression in ``user_expressions`` will result in
302 Any error in evaluating any expression in ``user_expressions`` will result in
301 only that key containing a standard error message, of the form::
303 only that key containing a standard error message, of the form::
302
304
303 {
305 {
304 'status' : 'error',
306 'status' : 'error',
305 'ename' : 'NameError',
307 'ename' : 'NameError',
306 'evalue' : 'foo',
308 'evalue' : 'foo',
307 'traceback' : ...
309 'traceback' : ...
308 }
310 }
309
311
310 .. Note::
312 .. Note::
311
313
312 In order to obtain the current execution counter for the purposes of
314 In order to obtain the current execution counter for the purposes of
313 displaying input prompts, frontends may make an execution request with an
315 displaying input prompts, frontends may make an execution request with an
314 empty code string and ``silent=True``.
316 empty code string and ``silent=True``.
315
317
316 Upon completion of the execution request, the kernel *always* sends a reply,
318 Upon completion of the execution request, the kernel *always* sends a reply,
317 with a status code indicating what happened and additional data depending on
319 with a status code indicating what happened and additional data depending on
318 the outcome. See :ref:`below <execution_results>` for the possible return
320 the outcome. See :ref:`below <execution_results>` for the possible return
319 codes and associated data.
321 codes and associated data.
320
322
321 .. seealso::
323 .. seealso::
322
324
323 :ref:`execution_semantics`
325 :ref:`execution_semantics`
324
326
325 .. _execution_counter:
327 .. _execution_counter:
326
328
327 Execution counter (prompt number)
329 Execution counter (prompt number)
328 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
330 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
329
331
330 The kernel should have a single, monotonically increasing counter of all execution
332 The kernel should have a single, monotonically increasing counter of all execution
331 requests that are made with ``store_history=True``. This counter is used to populate
333 requests that are made with ``store_history=True``. This counter is used to populate
332 the ``In[n]`` and ``Out[n]`` prompts. The value of this counter will be returned as the
334 the ``In[n]`` and ``Out[n]`` prompts. The value of this counter will be returned as the
333 ``execution_count`` field of all ``execute_reply`` and ``execute_input`` messages.
335 ``execution_count`` field of all ``execute_reply`` and ``execute_input`` messages.
334
336
335 .. _execution_results:
337 .. _execution_results:
336
338
337 Execution results
339 Execution results
338 ~~~~~~~~~~~~~~~~~
340 ~~~~~~~~~~~~~~~~~
339
341
340 Message type: ``execute_reply``::
342 Message type: ``execute_reply``::
341
343
342 content = {
344 content = {
343 # One of: 'ok' OR 'error' OR 'abort'
345 # One of: 'ok' OR 'error' OR 'abort'
344 'status' : str,
346 'status' : str,
345
347
346 # The global kernel counter that increases by one with each request that
348 # The global kernel counter that increases by one with each request that
347 # stores history. This will typically be used by clients to display
349 # stores history. This will typically be used by clients to display
348 # prompt numbers to the user. If the request did not store history, this will
350 # prompt numbers to the user. If the request did not store history, this will
349 # be the current value of the counter in the kernel.
351 # be the current value of the counter in the kernel.
350 'execution_count' : int,
352 'execution_count' : int,
351 }
353 }
352
354
353 When status is 'ok', the following extra fields are present::
355 When status is 'ok', the following extra fields are present::
354
356
355 {
357 {
356 # 'payload' will be a list of payload dicts.
358 # 'payload' will be a list of payload dicts.
357 # Each execution payload is a dict with string keys that may have been
359 # Each execution payload is a dict with string keys that may have been
358 # produced by the code being executed. It is retrieved by the kernel at
360 # produced by the code being executed. It is retrieved by the kernel at
359 # the end of the execution and sent back to the front end, which can take
361 # the end of the execution and sent back to the front end, which can take
360 # action on it as needed.
362 # action on it as needed.
361 # The only requirement of each payload dict is that it have a 'source' key,
363 # The only requirement of each payload dict is that it have a 'source' key,
362 # which is a string classifying the payload (e.g. 'pager').
364 # which is a string classifying the payload (e.g. 'pager').
363 'payload' : list(dict),
365 'payload' : list(dict),
364
366
365 # Results for the user_expressions.
367 # Results for the user_expressions.
366 'user_expressions' : dict,
368 'user_expressions' : dict,
367 }
369 }
368
370
369 .. versionchanged:: 5.0
371 .. versionchanged:: 5.0
370
372
371 ``user_variables`` is removed, use user_expressions instead.
373 ``user_variables`` is removed, use user_expressions instead.
372
374
373 .. admonition:: Execution payloads
375 .. admonition:: Execution payloads
374
376
375 The notion of an 'execution payload' is different from a return value of a
377 The notion of an 'execution payload' is different from a return value of a
376 given set of code, which normally is just displayed on the execute_result stream
378 given set of code, which normally is just displayed on the execute_result stream
377 through the PUB socket. The idea of a payload is to allow special types of
379 through the PUB socket. The idea of a payload is to allow special types of
378 code, typically magics, to populate a data container in the IPython kernel
380 code, typically magics, to populate a data container in the IPython kernel
379 that will be shipped back to the caller via this channel. The kernel
381 that will be shipped back to the caller via this channel. The kernel
380 has an API for this in the PayloadManager::
382 has an API for this in the PayloadManager::
381
383
382 ip.payload_manager.write_payload(payload_dict)
384 ip.payload_manager.write_payload(payload_dict)
383
385
384 which appends a dictionary to the list of payloads.
386 which appends a dictionary to the list of payloads.
385
387
386 The payload API is not yet stabilized,
388 The payload API is not yet stabilized,
387 and should probably not be supported by non-Python kernels at this time.
389 and should probably not be supported by non-Python kernels at this time.
388 In such cases, the payload list should always be empty.
390 In such cases, the payload list should always be empty.
389
391
390
392
391 When status is 'error', the following extra fields are present::
393 When status is 'error', the following extra fields are present::
392
394
393 {
395 {
394 'ename' : str, # Exception name, as a string
396 'ename' : str, # Exception name, as a string
395 'evalue' : str, # Exception value, as a string
397 'evalue' : str, # Exception value, as a string
396
398
397 # The traceback will contain a list of frames, represented each as a
399 # The traceback will contain a list of frames, represented each as a
398 # string. For now we'll stick to the existing design of ultraTB, which
400 # string. For now we'll stick to the existing design of ultraTB, which
399 # controls exception level of detail statefully. But eventually we'll
401 # controls exception level of detail statefully. But eventually we'll
400 # want to grow into a model where more information is collected and
402 # want to grow into a model where more information is collected and
401 # packed into the traceback object, with clients deciding how little or
403 # packed into the traceback object, with clients deciding how little or
402 # how much of it to unpack. But for now, let's start with a simple list
404 # how much of it to unpack. But for now, let's start with a simple list
403 # of strings, since that requires only minimal changes to ultratb as
405 # of strings, since that requires only minimal changes to ultratb as
404 # written.
406 # written.
405 'traceback' : list,
407 'traceback' : list,
406 }
408 }
407
409
408
410
409 When status is 'abort', there are for now no additional data fields. This
411 When status is 'abort', there are for now no additional data fields. This
410 happens when the kernel was interrupted by a signal.
412 happens when the kernel was interrupted by a signal.
411
413
412 .. _msging_inspection:
414 .. _msging_inspection:
413
415
414 Introspection
416 Introspection
415 -------------
417 -------------
416
418
417 Code can be inspected to show useful information to the user.
419 Code can be inspected to show useful information to the user.
418 It is up to the Kernel to decide what information should be displayed, and its formatting.
420 It is up to the Kernel to decide what information should be displayed, and its formatting.
419
421
420 Message type: ``inspect_request``::
422 Message type: ``inspect_request``::
421
423
422 content = {
424 content = {
423 # The code context in which introspection is requested
425 # The code context in which introspection is requested
424 # this may be up to an entire multiline cell.
426 # this may be up to an entire multiline cell.
425 'code' : str,
427 'code' : str,
426
428
427 # The cursor position within 'code' (in unicode characters) where inspection is requested
429 # The cursor position within 'code' (in unicode characters) where inspection is requested
428 'cursor_pos' : int,
430 'cursor_pos' : int,
429
431
430 # The level of detail desired. In IPython, the default (0) is equivalent to typing
432 # The level of detail desired. In IPython, the default (0) is equivalent to typing
431 # 'x?' at the prompt, 1 is equivalent to 'x??'.
433 # 'x?' at the prompt, 1 is equivalent to 'x??'.
432 # The difference is up to kernels, but in IPython level 1 includes the source code
434 # The difference is up to kernels, but in IPython level 1 includes the source code
433 # if available.
435 # if available.
434 'detail_level' : 0 or 1,
436 'detail_level' : 0 or 1,
435 }
437 }
436
438
437 .. versionchanged:: 5.0
439 .. versionchanged:: 5.0
438
440
439 ``object_info_request`` renamed to ``inspect_request``.
441 ``object_info_request`` renamed to ``inspect_request``.
440
442
441 .. versionchanged:: 5.0
443 .. versionchanged:: 5.0
442
444
443 ``name`` key replaced with ``code`` and ``cursor_pos``,
445 ``name`` key replaced with ``code`` and ``cursor_pos``,
444 moving the lexing responsibility to the kernel.
446 moving the lexing responsibility to the kernel.
445
447
446 The reply is a mime-bundle, like a `display_data`_ message,
448 The reply is a mime-bundle, like a `display_data`_ message,
447 which should be a formatted representation of information about the context.
449 which should be a formatted representation of information about the context.
448 In the notebook, this is used to show tooltips over function calls, etc.
450 In the notebook, this is used to show tooltips over function calls, etc.
449
451
450 Message type: ``inspect_reply``::
452 Message type: ``inspect_reply``::
451
453
452 content = {
454 content = {
453 # 'ok' if the request succeeded or 'error', with error information as in all other replies.
455 # 'ok' if the request succeeded or 'error', with error information as in all other replies.
454 'status' : 'ok',
456 'status' : 'ok',
455
457
456 # data can be empty if nothing is found
458 # data can be empty if nothing is found
457 'data' : dict,
459 'data' : dict,
458 'metadata' : dict,
460 'metadata' : dict,
459 }
461 }
460
462
461 .. versionchanged:: 5.0
463 .. versionchanged:: 5.0
462
464
463 ``object_info_reply`` renamed to ``inspect_reply``.
465 ``object_info_reply`` renamed to ``inspect_reply``.
464
466
465 .. versionchanged:: 5.0
467 .. versionchanged:: 5.0
466
468
467 Reply is changed from structured data to a mime bundle, allowing formatting decisions to be made by the kernel.
469 Reply is changed from structured data to a mime bundle, allowing formatting decisions to be made by the kernel.
468
470
469 .. _msging_completion:
471 .. _msging_completion:
470
472
471 Completion
473 Completion
472 ----------
474 ----------
473
475
474 Message type: ``complete_request``::
476 Message type: ``complete_request``::
475
477
476 content = {
478 content = {
477 # The code context in which completion is requested
479 # The code context in which completion is requested
478 # this may be up to an entire multiline cell, such as
480 # this may be up to an entire multiline cell, such as
479 # 'foo = a.isal'
481 # 'foo = a.isal'
480 'code' : str,
482 'code' : str,
481
483
482 # The cursor position within 'code' (in unicode characters) where completion is requested
484 # The cursor position within 'code' (in unicode characters) where completion is requested
483 'cursor_pos' : int,
485 'cursor_pos' : int,
484 }
486 }
485
487
486 .. versionchanged:: 5.0
488 .. versionchanged:: 5.0
487
489
488 ``line``, ``block``, and ``text`` keys are removed in favor of a single ``code`` for context.
490 ``line``, ``block``, and ``text`` keys are removed in favor of a single ``code`` for context.
489 Lexing is up to the kernel.
491 Lexing is up to the kernel.
490
492
491
493
492 Message type: ``complete_reply``::
494 Message type: ``complete_reply``::
493
495
494 content = {
496 content = {
495 # The list of all matches to the completion request, such as
497 # The list of all matches to the completion request, such as
496 # ['a.isalnum', 'a.isalpha'] for the above example.
498 # ['a.isalnum', 'a.isalpha'] for the above example.
497 'matches' : list,
499 'matches' : list,
498
500
499 # The range of text that should be replaced by the above matches when a completion is accepted.
501 # The range of text that should be replaced by the above matches when a completion is accepted.
500 # typically cursor_end is the same as cursor_pos in the request.
502 # typically cursor_end is the same as cursor_pos in the request.
501 'cursor_start' : int,
503 'cursor_start' : int,
502 'cursor_end' : int,
504 'cursor_end' : int,
503
505
504 # Information that frontend plugins might use for extra display information about completions.
506 # Information that frontend plugins might use for extra display information about completions.
505 'metadata' : dict,
507 'metadata' : dict,
506
508
507 # status should be 'ok' unless an exception was raised during the request,
509 # status should be 'ok' unless an exception was raised during the request,
508 # in which case it should be 'error', along with the usual error message content
510 # in which case it should be 'error', along with the usual error message content
509 # in other messages.
511 # in other messages.
510 'status' : 'ok'
512 'status' : 'ok'
511 }
513 }
512
514
513 .. versionchanged:: 5.0
515 .. versionchanged:: 5.0
514
516
515 - ``matched_text`` is removed in favor of ``cursor_start`` and ``cursor_end``.
517 - ``matched_text`` is removed in favor of ``cursor_start`` and ``cursor_end``.
516 - ``metadata`` is added for extended information.
518 - ``metadata`` is added for extended information.
517
519
518 .. _msging_history:
520 .. _msging_history:
519
521
520 History
522 History
521 -------
523 -------
522
524
523 For clients to explicitly request history from a kernel. The kernel has all
525 For clients to explicitly request history from a kernel. The kernel has all
524 the actual execution history stored in a single location, so clients can
526 the actual execution history stored in a single location, so clients can
525 request it from the kernel when needed.
527 request it from the kernel when needed.
526
528
527 Message type: ``history_request``::
529 Message type: ``history_request``::
528
530
529 content = {
531 content = {
530
532
531 # If True, also return output history in the resulting dict.
533 # If True, also return output history in the resulting dict.
532 'output' : bool,
534 'output' : bool,
533
535
534 # If True, return the raw input history, else the transformed input.
536 # If True, return the raw input history, else the transformed input.
535 'raw' : bool,
537 'raw' : bool,
536
538
537 # So far, this can be 'range', 'tail' or 'search'.
539 # So far, this can be 'range', 'tail' or 'search'.
538 'hist_access_type' : str,
540 'hist_access_type' : str,
539
541
540 # If hist_access_type is 'range', get a range of input cells. session can
542 # If hist_access_type is 'range', get a range of input cells. session can
541 # be a positive session number, or a negative number to count back from
543 # be a positive session number, or a negative number to count back from
542 # the current session.
544 # the current session.
543 'session' : int,
545 'session' : int,
544 # start and stop are line numbers within that session.
546 # start and stop are line numbers within that session.
545 'start' : int,
547 'start' : int,
546 'stop' : int,
548 'stop' : int,
547
549
548 # If hist_access_type is 'tail' or 'search', get the last n cells.
550 # If hist_access_type is 'tail' or 'search', get the last n cells.
549 'n' : int,
551 'n' : int,
550
552
551 # If hist_access_type is 'search', get cells matching the specified glob
553 # If hist_access_type is 'search', get cells matching the specified glob
552 # pattern (with * and ? as wildcards).
554 # pattern (with * and ? as wildcards).
553 'pattern' : str,
555 'pattern' : str,
554
556
555 # If hist_access_type is 'search' and unique is true, do not
557 # If hist_access_type is 'search' and unique is true, do not
556 # include duplicated history. Default is false.
558 # include duplicated history. Default is false.
557 'unique' : bool,
559 'unique' : bool,
558
560
559 }
561 }
560
562
561 .. versionadded:: 4.0
563 .. versionadded:: 4.0
562 The key ``unique`` for ``history_request``.
564 The key ``unique`` for ``history_request``.
563
565
564 Message type: ``history_reply``::
566 Message type: ``history_reply``::
565
567
566 content = {
568 content = {
567 # A list of 3 tuples, either:
569 # A list of 3 tuples, either:
568 # (session, line_number, input) or
570 # (session, line_number, input) or
569 # (session, line_number, (input, output)),
571 # (session, line_number, (input, output)),
570 # depending on whether output was False or True, respectively.
572 # depending on whether output was False or True, respectively.
571 'history' : list,
573 'history' : list,
572 }
574 }
573
575
574
576
575 Connect
577 Connect
576 -------
578 -------
577
579
578 When a client connects to the request/reply socket of the kernel, it can issue
580 When a client connects to the request/reply socket of the kernel, it can issue
579 a connect request to get basic information about the kernel, such as the ports
581 a connect request to get basic information about the kernel, such as the ports
580 the other ZeroMQ sockets are listening on. This allows clients to only have
582 the other ZeroMQ sockets are listening on. This allows clients to only have
581 to know about a single port (the shell channel) to connect to a kernel.
583 to know about a single port (the shell channel) to connect to a kernel.
582
584
583 Message type: ``connect_request``::
585 Message type: ``connect_request``::
584
586
585 content = {
587 content = {
586 }
588 }
587
589
588 Message type: ``connect_reply``::
590 Message type: ``connect_reply``::
589
591
590 content = {
592 content = {
591 'shell_port' : int, # The port the shell ROUTER socket is listening on.
593 'shell_port' : int, # The port the shell ROUTER socket is listening on.
592 'iopub_port' : int, # The port the PUB socket is listening on.
594 'iopub_port' : int, # The port the PUB socket is listening on.
593 'stdin_port' : int, # The port the stdin ROUTER socket is listening on.
595 'stdin_port' : int, # The port the stdin ROUTER socket is listening on.
594 'hb_port' : int, # The port the heartbeat socket is listening on.
596 'hb_port' : int, # The port the heartbeat socket is listening on.
595 }
597 }
596
598
597 .. _msging_kernel_info:
599 .. _msging_kernel_info:
598
600
599 Kernel info
601 Kernel info
600 -----------
602 -----------
601
603
602 If a client needs to know information about the kernel, it can
604 If a client needs to know information about the kernel, it can
603 make a request of the kernel's information.
605 make a request of the kernel's information.
604 This message can be used to fetch core information of the
606 This message can be used to fetch core information of the
605 kernel, including language (e.g., Python), language version number and
607 kernel, including language (e.g., Python), language version number and
606 IPython version number, and the IPython message spec version number.
608 IPython version number, and the IPython message spec version number.
607
609
608 Message type: ``kernel_info_request``::
610 Message type: ``kernel_info_request``::
609
611
610 content = {
612 content = {
611 }
613 }
612
614
613 Message type: ``kernel_info_reply``::
615 Message type: ``kernel_info_reply``::
614
616
615 content = {
617 content = {
616 # Version of messaging protocol.
618 # Version of messaging protocol.
617 # The first integer indicates major version. It is incremented when
619 # The first integer indicates major version. It is incremented when
618 # there is any backward incompatible change.
620 # there is any backward incompatible change.
619 # The second integer indicates minor version. It is incremented when
621 # The second integer indicates minor version. It is incremented when
620 # there is any backward compatible change.
622 # there is any backward compatible change.
621 'protocol_version': 'X.Y.Z',
623 'protocol_version': 'X.Y.Z',
622
624
623 # The kernel implementation name
625 # The kernel implementation name
624 # (e.g. 'ipython' for the IPython kernel)
626 # (e.g. 'ipython' for the IPython kernel)
625 'implementation': str,
627 'implementation': str,
626
628
627 # Implementation version number.
629 # Implementation version number.
628 # The version number of the kernel's implementation
630 # The version number of the kernel's implementation
629 # (e.g. IPython.__version__ for the IPython kernel)
631 # (e.g. IPython.__version__ for the IPython kernel)
630 'implementation_version': 'X.Y.Z',
632 'implementation_version': 'X.Y.Z',
631
633
632 # Programming language in which kernel is implemented.
634 # Programming language in which kernel is implemented.
633 # Kernel included in IPython returns 'python'.
635 # Kernel included in IPython returns 'python'.
634 'language': str,
636 'language': str,
635
637
636 # Language version number.
638 # Language version number.
637 # It is Python version number (e.g., '2.7.3') for the kernel
639 # It is Python version number (e.g., '2.7.3') for the kernel
638 # included in IPython.
640 # included in IPython.
639 'language_version': 'X.Y.Z',
641 'language_version': 'X.Y.Z',
640
642
641 # A banner of information about the kernel,
643 # A banner of information about the kernel,
642 # which may be desplayed in console environments.
644 # which may be desplayed in console environments.
643 'banner' : str,
645 'banner' : str,
644 }
646 }
645
647
646 .. versionchanged:: 5.0
648 .. versionchanged:: 5.0
647
649
648 Versions changed from lists of integers to strings.
650 Versions changed from lists of integers to strings.
649
651
650 .. versionchanged:: 5.0
652 .. versionchanged:: 5.0
651
653
652 ``ipython_version`` is removed.
654 ``ipython_version`` is removed.
653
655
654 .. versionchanged:: 5.0
656 .. versionchanged:: 5.0
655
657
656 ``implementation``, ``implementation_version``, and ``banner`` keys are added.
658 ``implementation``, ``implementation_version``, and ``banner`` keys are added.
657
659
658 .. _msging_shutdown:
660 .. _msging_shutdown:
659
661
660 Kernel shutdown
662 Kernel shutdown
661 ---------------
663 ---------------
662
664
663 The clients can request the kernel to shut itself down; this is used in
665 The clients can request the kernel to shut itself down; this is used in
664 multiple cases:
666 multiple cases:
665
667
666 - when the user chooses to close the client application via a menu or window
668 - when the user chooses to close the client application via a menu or window
667 control.
669 control.
668 - when the user types 'exit' or 'quit' (or their uppercase magic equivalents).
670 - when the user types 'exit' or 'quit' (or their uppercase magic equivalents).
669 - when the user chooses a GUI method (like the 'Ctrl-C' shortcut in the
671 - when the user chooses a GUI method (like the 'Ctrl-C' shortcut in the
670 IPythonQt client) to force a kernel restart to get a clean kernel without
672 IPythonQt client) to force a kernel restart to get a clean kernel without
671 losing client-side state like history or inlined figures.
673 losing client-side state like history or inlined figures.
672
674
673 The client sends a shutdown request to the kernel, and once it receives the
675 The client sends a shutdown request to the kernel, and once it receives the
674 reply message (which is otherwise empty), it can assume that the kernel has
676 reply message (which is otherwise empty), it can assume that the kernel has
675 completed shutdown safely.
677 completed shutdown safely.
676
678
677 Upon their own shutdown, client applications will typically execute a last
679 Upon their own shutdown, client applications will typically execute a last
678 minute sanity check and forcefully terminate any kernel that is still alive, to
680 minute sanity check and forcefully terminate any kernel that is still alive, to
679 avoid leaving stray processes in the user's machine.
681 avoid leaving stray processes in the user's machine.
680
682
681 Message type: ``shutdown_request``::
683 Message type: ``shutdown_request``::
682
684
683 content = {
685 content = {
684 'restart' : bool # whether the shutdown is final, or precedes a restart
686 'restart' : bool # whether the shutdown is final, or precedes a restart
685 }
687 }
686
688
687 Message type: ``shutdown_reply``::
689 Message type: ``shutdown_reply``::
688
690
689 content = {
691 content = {
690 'restart' : bool # whether the shutdown is final, or precedes a restart
692 'restart' : bool # whether the shutdown is final, or precedes a restart
691 }
693 }
692
694
693 .. Note::
695 .. Note::
694
696
695 When the clients detect a dead kernel thanks to inactivity on the heartbeat
697 When the clients detect a dead kernel thanks to inactivity on the heartbeat
696 socket, they simply send a forceful process termination signal, since a dead
698 socket, they simply send a forceful process termination signal, since a dead
697 process is unlikely to respond in any useful way to messages.
699 process is unlikely to respond in any useful way to messages.
698
700
699
701
700 Messages on the PUB/SUB socket
702 Messages on the PUB/SUB socket
701 ==============================
703 ==============================
702
704
703 Streams (stdout, stderr, etc)
705 Streams (stdout, stderr, etc)
704 ------------------------------
706 ------------------------------
705
707
706 Message type: ``stream``::
708 Message type: ``stream``::
707
709
708 content = {
710 content = {
709 # The name of the stream is one of 'stdout', 'stderr'
711 # The name of the stream is one of 'stdout', 'stderr'
710 'name' : str,
712 'name' : str,
711
713
712 # The data is an arbitrary string to be written to that stream
714 # The data is an arbitrary string to be written to that stream
713 'data' : str,
715 'data' : str,
714 }
716 }
715
717
716 Display Data
718 Display Data
717 ------------
719 ------------
718
720
719 This type of message is used to bring back data that should be displayed (text,
721 This type of message is used to bring back data that should be displayed (text,
720 html, svg, etc.) in the frontends. This data is published to all frontends.
722 html, svg, etc.) in the frontends. This data is published to all frontends.
721 Each message can have multiple representations of the data; it is up to the
723 Each message can have multiple representations of the data; it is up to the
722 frontend to decide which to use and how. A single message should contain all
724 frontend to decide which to use and how. A single message should contain all
723 possible representations of the same information. Each representation should
725 possible representations of the same information. Each representation should
724 be a JSON'able data structure, and should be a valid MIME type.
726 be a JSON'able data structure, and should be a valid MIME type.
725
727
726 Some questions remain about this design:
728 Some questions remain about this design:
727
729
728 * Do we use this message type for execute_result/displayhook? Probably not, because
730 * Do we use this message type for execute_result/displayhook? Probably not, because
729 the displayhook also has to handle the Out prompt display. On the other hand
731 the displayhook also has to handle the Out prompt display. On the other hand
730 we could put that information into the metadata section.
732 we could put that information into the metadata section.
731
733
732 .. _display_data:
734 .. _display_data:
733
735
734 Message type: ``display_data``::
736 Message type: ``display_data``::
735
737
736 content = {
738 content = {
737
739
738 # Who create the data
740 # Who create the data
739 'source' : str,
741 'source' : str,
740
742
741 # The data dict contains key/value pairs, where the keys are MIME
743 # The data dict contains key/value pairs, where the keys are MIME
742 # types and the values are the raw data of the representation in that
744 # types and the values are the raw data of the representation in that
743 # format.
745 # format.
744 'data' : dict,
746 'data' : dict,
745
747
746 # Any metadata that describes the data
748 # Any metadata that describes the data
747 'metadata' : dict
749 'metadata' : dict
748 }
750 }
749
751
750
752
751 The ``metadata`` contains any metadata that describes the output.
753 The ``metadata`` contains any metadata that describes the output.
752 Global keys are assumed to apply to the output as a whole.
754 Global keys are assumed to apply to the output as a whole.
753 The ``metadata`` dict can also contain mime-type keys, which will be sub-dictionaries,
755 The ``metadata`` dict can also contain mime-type keys, which will be sub-dictionaries,
754 which are interpreted as applying only to output of that type.
756 which are interpreted as applying only to output of that type.
755 Third parties should put any data they write into a single dict
757 Third parties should put any data they write into a single dict
756 with a reasonably unique name to avoid conflicts.
758 with a reasonably unique name to avoid conflicts.
757
759
758 The only metadata keys currently defined in IPython are the width and height
760 The only metadata keys currently defined in IPython are the width and height
759 of images::
761 of images::
760
762
761 metadata = {
763 metadata = {
762 'image/png' : {
764 'image/png' : {
763 'width': 640,
765 'width': 640,
764 'height': 480
766 'height': 480
765 }
767 }
766 }
768 }
767
769
768
770
769 .. versionchanged:: 5.0
771 .. versionchanged:: 5.0
770
772
771 `application/json` data should be unpacked JSON data,
773 `application/json` data should be unpacked JSON data,
772 not double-serialized as a JSON string.
774 not double-serialized as a JSON string.
773
775
774
776
775 Raw Data Publication
777 Raw Data Publication
776 --------------------
778 --------------------
777
779
778 ``display_data`` lets you publish *representations* of data, such as images and html.
780 ``display_data`` lets you publish *representations* of data, such as images and html.
779 This ``data_pub`` message lets you publish *actual raw data*, sent via message buffers.
781 This ``data_pub`` message lets you publish *actual raw data*, sent via message buffers.
780
782
781 data_pub messages are constructed via the :func:`IPython.lib.datapub.publish_data` function:
783 data_pub messages are constructed via the :func:`IPython.lib.datapub.publish_data` function:
782
784
783 .. sourcecode:: python
785 .. sourcecode:: python
784
786
785 from IPython.kernel.zmq.datapub import publish_data
787 from IPython.kernel.zmq.datapub import publish_data
786 ns = dict(x=my_array)
788 ns = dict(x=my_array)
787 publish_data(ns)
789 publish_data(ns)
788
790
789
791
790 Message type: ``data_pub``::
792 Message type: ``data_pub``::
791
793
792 content = {
794 content = {
793 # the keys of the data dict, after it has been unserialized
795 # the keys of the data dict, after it has been unserialized
794 'keys' : ['a', 'b']
796 'keys' : ['a', 'b']
795 }
797 }
796 # the namespace dict will be serialized in the message buffers,
798 # the namespace dict will be serialized in the message buffers,
797 # which will have a length of at least one
799 # which will have a length of at least one
798 buffers = [b'pdict', ...]
800 buffers = [b'pdict', ...]
799
801
800
802
801 The interpretation of a sequence of data_pub messages for a given parent request should be
803 The interpretation of a sequence of data_pub messages for a given parent request should be
802 to update a single namespace with subsequent results.
804 to update a single namespace with subsequent results.
803
805
804 .. note::
806 .. note::
805
807
806 No frontends directly handle data_pub messages at this time.
808 No frontends directly handle data_pub messages at this time.
807 It is currently only used by the client/engines in :mod:`IPython.parallel`,
809 It is currently only used by the client/engines in :mod:`IPython.parallel`,
808 where engines may publish *data* to the Client,
810 where engines may publish *data* to the Client,
809 of which the Client can then publish *representations* via ``display_data``
811 of which the Client can then publish *representations* via ``display_data``
810 to various frontends.
812 to various frontends.
811
813
812 Code inputs
814 Code inputs
813 -----------
815 -----------
814
816
815 To let all frontends know what code is being executed at any given time, these
817 To let all frontends know what code is being executed at any given time, these
816 messages contain a re-broadcast of the ``code`` portion of an
818 messages contain a re-broadcast of the ``code`` portion of an
817 :ref:`execute_request <execute>`, along with the :ref:`execution_count
819 :ref:`execute_request <execute>`, along with the :ref:`execution_count
818 <execution_counter>`.
820 <execution_counter>`.
819
821
820 Message type: ``execute_input``::
822 Message type: ``execute_input``::
821
823
822 content = {
824 content = {
823 'code' : str, # Source code to be executed, one or more lines
825 'code' : str, # Source code to be executed, one or more lines
824
826
825 # The counter for this execution is also provided so that clients can
827 # The counter for this execution is also provided so that clients can
826 # display it, since IPython automatically creates variables called _iN
828 # display it, since IPython automatically creates variables called _iN
827 # (for input prompt In[N]).
829 # (for input prompt In[N]).
828 'execution_count' : int
830 'execution_count' : int
829 }
831 }
830
832
831 .. versionchanged:: 5.0
833 .. versionchanged:: 5.0
832
834
833 ``pyin`` is renamed to ``execute_input``.
835 ``pyin`` is renamed to ``execute_input``.
834
836
835
837
836 Execution results
838 Execution results
837 -----------------
839 -----------------
838
840
839 Results of an execution are published as an ``execute_result``.
841 Results of an execution are published as an ``execute_result``.
840 These are identical to `display_data`_ messages, with the addition of an ``execution_count`` key.
842 These are identical to `display_data`_ messages, with the addition of an ``execution_count`` key.
841
843
842 Results can have multiple simultaneous formats depending on its
844 Results can have multiple simultaneous formats depending on its
843 configuration. A plain text representation should always be provided
845 configuration. A plain text representation should always be provided
844 in the ``text/plain`` mime-type. Frontends are free to display any or all of these
846 in the ``text/plain`` mime-type. Frontends are free to display any or all of these
845 according to its capabilities.
847 according to its capabilities.
846 Frontends should ignore mime-types they do not understand. The data itself is
848 Frontends should ignore mime-types they do not understand. The data itself is
847 any JSON object and depends on the format. It is often, but not always a string.
849 any JSON object and depends on the format. It is often, but not always a string.
848
850
849 Message type: ``execute_result``::
851 Message type: ``execute_result``::
850
852
851 content = {
853 content = {
852
854
853 # The counter for this execution is also provided so that clients can
855 # The counter for this execution is also provided so that clients can
854 # display it, since IPython automatically creates variables called _N
856 # display it, since IPython automatically creates variables called _N
855 # (for prompt N).
857 # (for prompt N).
856 'execution_count' : int,
858 'execution_count' : int,
857
859
858 # data and metadata are identical to a display_data message.
860 # data and metadata are identical to a display_data message.
859 # the object being displayed is that passed to the display hook,
861 # the object being displayed is that passed to the display hook,
860 # i.e. the *result* of the execution.
862 # i.e. the *result* of the execution.
861 'data' : dict,
863 'data' : dict,
862 'metadata' : dict,
864 'metadata' : dict,
863 }
865 }
864
866
865 Execution errors
867 Execution errors
866 ----------------
868 ----------------
867
869
868 When an error occurs during code execution
870 When an error occurs during code execution
869
871
870 Message type: ``error``::
872 Message type: ``error``::
871
873
872 content = {
874 content = {
873 # Similar content to the execute_reply messages for the 'error' case,
875 # Similar content to the execute_reply messages for the 'error' case,
874 # except the 'status' field is omitted.
876 # except the 'status' field is omitted.
875 }
877 }
876
878
877 .. versionchanged:: 5.0
879 .. versionchanged:: 5.0
878
880
879 ``pyerr`` renamed to ``error``
881 ``pyerr`` renamed to ``error``
880
882
881 Kernel status
883 Kernel status
882 -------------
884 -------------
883
885
884 This message type is used by frontends to monitor the status of the kernel.
886 This message type is used by frontends to monitor the status of the kernel.
885
887
886 Message type: ``status``::
888 Message type: ``status``::
887
889
888 content = {
890 content = {
889 # When the kernel starts to handle a message, it will enter the 'busy'
891 # When the kernel starts to handle a message, it will enter the 'busy'
890 # state and when it finishes, it will enter the 'idle' state.
892 # state and when it finishes, it will enter the 'idle' state.
891 # The kernel will publish state 'starting' exactly once at process startup.
893 # The kernel will publish state 'starting' exactly once at process startup.
892 execution_state : ('busy', 'idle', 'starting')
894 execution_state : ('busy', 'idle', 'starting')
893 }
895 }
894
896
895 .. versionchanged:: 5.0
897 .. versionchanged:: 5.0
896
898
897 Busy and idle messages should be sent before/after handling every message,
899 Busy and idle messages should be sent before/after handling every message,
898 not just execution.
900 not just execution.
899
901
900 Clear output
902 Clear output
901 ------------
903 ------------
902
904
903 This message type is used to clear the output that is visible on the frontend.
905 This message type is used to clear the output that is visible on the frontend.
904
906
905 Message type: ``clear_output``::
907 Message type: ``clear_output``::
906
908
907 content = {
909 content = {
908
910
909 # Wait to clear the output until new output is available. Clears the
911 # Wait to clear the output until new output is available. Clears the
910 # existing output immediately before the new output is displayed.
912 # existing output immediately before the new output is displayed.
911 # Useful for creating simple animations with minimal flickering.
913 # Useful for creating simple animations with minimal flickering.
912 'wait' : bool,
914 'wait' : bool,
913 }
915 }
914
916
915 .. versionchanged:: 4.1
917 .. versionchanged:: 4.1
916
918
917 ``stdout``, ``stderr``, and ``display`` boolean keys for selective clearing are removed,
919 ``stdout``, ``stderr``, and ``display`` boolean keys for selective clearing are removed,
918 and ``wait`` is added.
920 and ``wait`` is added.
919 The selective clearing keys are ignored in v4 and the default behavior remains the same,
921 The selective clearing keys are ignored in v4 and the default behavior remains the same,
920 so v4 clear_output messages will be safely handled by a v4.1 frontend.
922 so v4 clear_output messages will be safely handled by a v4.1 frontend.
921
923
922
924
923 Messages on the stdin ROUTER/DEALER sockets
925 Messages on the stdin ROUTER/DEALER sockets
924 ===========================================
926 ===========================================
925
927
926 This is a socket where the request/reply pattern goes in the opposite direction:
928 This is a socket where the request/reply pattern goes in the opposite direction:
927 from the kernel to a *single* frontend, and its purpose is to allow
929 from the kernel to a *single* frontend, and its purpose is to allow
928 ``raw_input`` and similar operations that read from ``sys.stdin`` on the kernel
930 ``raw_input`` and similar operations that read from ``sys.stdin`` on the kernel
929 to be fulfilled by the client. The request should be made to the frontend that
931 to be fulfilled by the client. The request should be made to the frontend that
930 made the execution request that prompted ``raw_input`` to be called. For now we
932 made the execution request that prompted ``raw_input`` to be called. For now we
931 will keep these messages as simple as possible, since they only mean to convey
933 will keep these messages as simple as possible, since they only mean to convey
932 the ``raw_input(prompt)`` call.
934 the ``raw_input(prompt)`` call.
933
935
934 Message type: ``input_request``::
936 Message type: ``input_request``::
935
937
936 content = {
938 content = {
937 # the text to show at the prompt
939 # the text to show at the prompt
938 'prompt' : str,
940 'prompt' : str,
939 # Is the request for a password?
941 # Is the request for a password?
940 # If so, the frontend shouldn't echo input.
942 # If so, the frontend shouldn't echo input.
941 'password' : bool
943 'password' : bool
942 }
944 }
943
945
944 Message type: ``input_reply``::
946 Message type: ``input_reply``::
945
947
946 content = { 'value' : str }
948 content = { 'value' : str }
947
949
948
950
949 When ``password`` is True, the frontend should not echo the input as it is entered.
951 When ``password`` is True, the frontend should not echo the input as it is entered.
950
952
951 .. versionchanged:: 5.0
953 .. versionchanged:: 5.0
952
954
953 ``password`` key added.
955 ``password`` key added.
954
956
955 .. note::
957 .. note::
956
958
957 The stdin socket of the client is required to have the same zmq IDENTITY
959 The stdin socket of the client is required to have the same zmq IDENTITY
958 as the client's shell socket.
960 as the client's shell socket.
959 Because of this, the ``input_request`` must be sent with the same IDENTITY
961 Because of this, the ``input_request`` must be sent with the same IDENTITY
960 routing prefix as the ``execute_reply`` in order for the frontend to receive
962 routing prefix as the ``execute_reply`` in order for the frontend to receive
961 the message.
963 the message.
962
964
963 .. note::
965 .. note::
964
966
965 We do not explicitly try to forward the raw ``sys.stdin`` object, because in
967 We do not explicitly try to forward the raw ``sys.stdin`` object, because in
966 practice the kernel should behave like an interactive program. When a
968 practice the kernel should behave like an interactive program. When a
967 program is opened on the console, the keyboard effectively takes over the
969 program is opened on the console, the keyboard effectively takes over the
968 ``stdin`` file descriptor, and it can't be used for raw reading anymore.
970 ``stdin`` file descriptor, and it can't be used for raw reading anymore.
969 Since the IPython kernel effectively behaves like a console program (albeit
971 Since the IPython kernel effectively behaves like a console program (albeit
970 one whose "keyboard" is actually living in a separate process and
972 one whose "keyboard" is actually living in a separate process and
971 transported over the zmq connection), raw ``stdin`` isn't expected to be
973 transported over the zmq connection), raw ``stdin`` isn't expected to be
972 available.
974 available.
973
975
976 .. _kernel_heartbeat:
974
977
975 Heartbeat for kernels
978 Heartbeat for kernels
976 =====================
979 =====================
977
980
978 Clients send ping messages on a REQ socket, which are echoed right back
981 Clients send ping messages on a REQ socket, which are echoed right back
979 from the Kernel's REP socket. These are simple bytestrings, not full JSON messages described above.
982 from the Kernel's REP socket. These are simple bytestrings, not full JSON messages described above.
980
983
981
984
982 Custom Messages
985 Custom Messages
983 ===============
986 ===============
984
987
985 .. versionadded:: 4.1
988 .. versionadded:: 4.1
986
989
987 IPython 2.0 (msgspec v4.1) adds a messaging system for developers to add their own objects with Frontend
990 IPython 2.0 (msgspec v4.1) adds a messaging system for developers to add their own objects with Frontend
988 and Kernel-side components, and allow them to communicate with each other.
991 and Kernel-side components, and allow them to communicate with each other.
989 To do this, IPython adds a notion of a ``Comm``, which exists on both sides,
992 To do this, IPython adds a notion of a ``Comm``, which exists on both sides,
990 and can communicate in either direction.
993 and can communicate in either direction.
991
994
992 These messages are fully symmetrical - both the Kernel and the Frontend can send each message,
995 These messages are fully symmetrical - both the Kernel and the Frontend can send each message,
993 and no messages expect a reply.
996 and no messages expect a reply.
994 The Kernel listens for these messages on the Shell channel,
997 The Kernel listens for these messages on the Shell channel,
995 and the Frontend listens for them on the IOPub channel.
998 and the Frontend listens for them on the IOPub channel.
996
999
997 Opening a Comm
1000 Opening a Comm
998 --------------
1001 --------------
999
1002
1000 Opening a Comm produces a ``comm_open`` message, to be sent to the other side::
1003 Opening a Comm produces a ``comm_open`` message, to be sent to the other side::
1001
1004
1002 {
1005 {
1003 'comm_id' : 'u-u-i-d',
1006 'comm_id' : 'u-u-i-d',
1004 'target_name' : 'my_comm',
1007 'target_name' : 'my_comm',
1005 'data' : {}
1008 'data' : {}
1006 }
1009 }
1007
1010
1008 Every Comm has an ID and a target name.
1011 Every Comm has an ID and a target name.
1009 The code handling the message on the receiving side is responsible for maintaining a mapping
1012 The code handling the message on the receiving side is responsible for maintaining a mapping
1010 of target_name keys to constructors.
1013 of target_name keys to constructors.
1011 After a ``comm_open`` message has been sent,
1014 After a ``comm_open`` message has been sent,
1012 there should be a corresponding Comm instance on both sides.
1015 there should be a corresponding Comm instance on both sides.
1013 The ``data`` key is always a dict and can be any extra JSON information used in initialization of the comm.
1016 The ``data`` key is always a dict and can be any extra JSON information used in initialization of the comm.
1014
1017
1015 If the ``target_name`` key is not found on the receiving side,
1018 If the ``target_name`` key is not found on the receiving side,
1016 then it should immediately reply with a ``comm_close`` message to avoid an inconsistent state.
1019 then it should immediately reply with a ``comm_close`` message to avoid an inconsistent state.
1017
1020
1018 Comm Messages
1021 Comm Messages
1019 -------------
1022 -------------
1020
1023
1021 Comm messages are one-way communications to update comm state,
1024 Comm messages are one-way communications to update comm state,
1022 used for synchronizing widget state, or simply requesting actions of a comm's counterpart.
1025 used for synchronizing widget state, or simply requesting actions of a comm's counterpart.
1023
1026
1024 Essentially, each comm pair defines their own message specification implemented inside the ``data`` dict.
1027 Essentially, each comm pair defines their own message specification implemented inside the ``data`` dict.
1025
1028
1026 There are no expected replies (of course, one side can send another ``comm_msg`` in reply).
1029 There are no expected replies (of course, one side can send another ``comm_msg`` in reply).
1027
1030
1028 Message type: ``comm_msg``::
1031 Message type: ``comm_msg``::
1029
1032
1030 {
1033 {
1031 'comm_id' : 'u-u-i-d',
1034 'comm_id' : 'u-u-i-d',
1032 'data' : {}
1035 'data' : {}
1033 }
1036 }
1034
1037
1035 Tearing Down Comms
1038 Tearing Down Comms
1036 ------------------
1039 ------------------
1037
1040
1038 Since comms live on both sides, when a comm is destroyed the other side must be notified.
1041 Since comms live on both sides, when a comm is destroyed the other side must be notified.
1039 This is done with a ``comm_close`` message.
1042 This is done with a ``comm_close`` message.
1040
1043
1041 Message type: ``comm_close``::
1044 Message type: ``comm_close``::
1042
1045
1043 {
1046 {
1044 'comm_id' : 'u-u-i-d',
1047 'comm_id' : 'u-u-i-d',
1045 'data' : {}
1048 'data' : {}
1046 }
1049 }
1047
1050
1048 Output Side Effects
1051 Output Side Effects
1049 -------------------
1052 -------------------
1050
1053
1051 Since comm messages can execute arbitrary user code,
1054 Since comm messages can execute arbitrary user code,
1052 handlers should set the parent header and publish status busy / idle,
1055 handlers should set the parent header and publish status busy / idle,
1053 just like an execute request.
1056 just like an execute request.
1054
1057
1055
1058
1056 To Do
1059 To Do
1057 =====
1060 =====
1058
1061
1059 Missing things include:
1062 Missing things include:
1060
1063
1061 * Important: finish thinking through the payload concept and API.
1064 * Important: finish thinking through the payload concept and API.
1062
1065
1063 .. include:: ../links.txt
1066 .. include:: ../links.txt
@@ -1,148 +1,153 b''
1 Making simple Python wrapper kernels
1 Making simple Python wrapper kernels
2 ====================================
2 ====================================
3
3
4 .. versionadded:: 3.0
4 .. versionadded:: 3.0
5
5
6 You can now re-use the kernel machinery in IPython to easily make new kernels.
6 You can now re-use the kernel machinery in IPython to easily make new kernels.
7 This is useful for languages that have Python bindings, such as `Octave
7 This is useful for languages that have Python bindings, such as `Octave
8 <http://www.gnu.org/software/octave/>`_ (via
8 <http://www.gnu.org/software/octave/>`_ (via
9 `Oct2Py <http://blink1073.github.io/oct2py/docs/index.html>`_), or languages
9 `Oct2Py <http://blink1073.github.io/oct2py/docs/index.html>`_), or languages
10 where the REPL can be controlled in a tty using `pexpect <http://pexpect.readthedocs.org/en/latest/>`_,
10 where the REPL can be controlled in a tty using `pexpect <http://pexpect.readthedocs.org/en/latest/>`_,
11 such as bash.
11 such as bash.
12
12
13 .. seealso::
14
15 `bash_kernel <https://github.com/takluyver/bash_kernel>`_
16 A simple kernel for bash, written using this machinery
17
13 Required steps
18 Required steps
14 --------------
19 --------------
15
20
16 Subclass :class:`IPython.kernel.zmq.kernelbase.Kernel`, and implement the
21 Subclass :class:`IPython.kernel.zmq.kernelbase.Kernel`, and implement the
17 following methods and attributes:
22 following methods and attributes:
18
23
19 .. class:: MyKernel
24 .. class:: MyKernel
20
25
21 .. attribute:: implementation
26 .. attribute:: implementation
22 implementation_version
27 implementation_version
23 language
28 language
24 language_version
29 language_version
25 banner
30 banner
26
31
27 Information for :ref:`msging_kernel_info` replies. 'Implementation' refers
32 Information for :ref:`msging_kernel_info` replies. 'Implementation' refers
28 to the kernel (e.g. IPython), and 'language' refers to the language it
33 to the kernel (e.g. IPython), and 'language' refers to the language it
29 interprets (e.g. Python). The 'banner' is displayed to the user in console
34 interprets (e.g. Python). The 'banner' is displayed to the user in console
30 UIs before the first prompt. All of these values are strings.
35 UIs before the first prompt. All of these values are strings.
31
36
32 .. method:: do_execute(code, silent, store_history=True, user_expressions=None, allow_stdin=False)
37 .. method:: do_execute(code, silent, store_history=True, user_expressions=None, allow_stdin=False)
33
38
34 Execute user code.
39 Execute user code.
35
40
36 :param str code: The code to be executed.
41 :param str code: The code to be executed.
37 :param bool silent: Whether to display output.
42 :param bool silent: Whether to display output.
38 :param bool store_history: Whether to record this code in history and
43 :param bool store_history: Whether to record this code in history and
39 increase the execution count. If silent is True, this is implicitly
44 increase the execution count. If silent is True, this is implicitly
40 False.
45 False.
41 :param dict user_expressions: Mapping of names to expressions to evaluate
46 :param dict user_expressions: Mapping of names to expressions to evaluate
42 after the code has run. You can ignore this if you need to.
47 after the code has run. You can ignore this if you need to.
43 :param bool allow_stdin: Whether the frontend can provide input on request
48 :param bool allow_stdin: Whether the frontend can provide input on request
44 (e.g. for Python's :func:`raw_input`).
49 (e.g. for Python's :func:`raw_input`).
45
50
46 Your method should return a dict containing the fields described in
51 Your method should return a dict containing the fields described in
47 :ref:`execution_results`. To display output, it can send messages
52 :ref:`execution_results`. To display output, it can send messages
48 using :meth:`~IPython.kernel.zmq.kernelbase.Kernel.send_response`.
53 using :meth:`~IPython.kernel.zmq.kernelbase.Kernel.send_response`.
49 See :doc:`messaging` for details of the different message types.
54 See :doc:`messaging` for details of the different message types.
50
55
51 To launch your kernel, add this at the end of your module::
56 To launch your kernel, add this at the end of your module::
52
57
53 if __name__ == '__main__':
58 if __name__ == '__main__':
54 from IPython.kernel.zmq.kernelapp import IPKernelApp
59 from IPython.kernel.zmq.kernelapp import IPKernelApp
55 IPKernelApp.launch_instance(kernel_class=MyKernel)
60 IPKernelApp.launch_instance(kernel_class=MyKernel)
56
61
57 Example
62 Example
58 -------
63 -------
59
64
60 ``echokernel.py`` will simply echo any input it's given to stdout::
65 ``echokernel.py`` will simply echo any input it's given to stdout::
61
66
62 from IPython.kernel.zmq.kernelbase import Kernel
67 from IPython.kernel.zmq.kernelbase import Kernel
63
68
64 class EchoKernel(Kernel):
69 class EchoKernel(Kernel):
65 implementation = 'Echo'
70 implementation = 'Echo'
66 implementation_version = '1.0'
71 implementation_version = '1.0'
67 language = 'no-op'
72 language = 'no-op'
68 language_version = '0.1'
73 language_version = '0.1'
69 banner = "Echo kernel - as useful as a parrot"
74 banner = "Echo kernel - as useful as a parrot"
70
75
71 def do_execute(self, code, silent, store_history=True, user_experssions=None,
76 def do_execute(self, code, silent, store_history=True, user_experssions=None,
72 allow_stdin=False):
77 allow_stdin=False):
73 if not silent:
78 if not silent:
74 stream_content = {'name': 'stdout', 'data':code}
79 stream_content = {'name': 'stdout', 'data':code}
75 self.send_response(self.iopub_socket, 'stream', stream_content)
80 self.send_response(self.iopub_socket, 'stream', stream_content)
76
81
77 return {'status': 'ok',
82 return {'status': 'ok',
78 # The base class increments the execution count
83 # The base class increments the execution count
79 'execution_count': self.execution_count,
84 'execution_count': self.execution_count,
80 'payload': [],
85 'payload': [],
81 'user_expressions': {},
86 'user_expressions': {},
82 }
87 }
83
88
84 if __name__ == '__main__':
89 if __name__ == '__main__':
85 from IPython.kernel.zmq.kernelapp import IPKernelApp
90 from IPython.kernel.zmq.kernelapp import IPKernelApp
86 IPKernelApp.launch_instance(kernel_class=EchoKernel)
91 IPKernelApp.launch_instance(kernel_class=EchoKernel)
87
92
88 Here's the Kernel spec ``kernel.json`` file for this::
93 Here's the Kernel spec ``kernel.json`` file for this::
89
94
90 {"argv":["python","-m","echokernel", "-f", "{connection_file}"],
95 {"argv":["python","-m","echokernel", "-f", "{connection_file}"],
91 "display_name":"Echo",
96 "display_name":"Echo",
92 "language":"no-op"
97 "language":"no-op"
93 }
98 }
94
99
95
100
96 Optional steps
101 Optional steps
97 --------------
102 --------------
98
103
99 You can override a number of other methods to improve the functionality of your
104 You can override a number of other methods to improve the functionality of your
100 kernel. All of these methods should return a dictionary as described in the
105 kernel. All of these methods should return a dictionary as described in the
101 relevant section of the :doc:`messaging spec <messaging>`.
106 relevant section of the :doc:`messaging spec <messaging>`.
102
107
103 .. class:: MyKernel
108 .. class:: MyKernel
104
109
105 .. method:: do_complete(code, cusor_pos)
110 .. method:: do_complete(code, cusor_pos)
106
111
107 Code completion
112 Code completion
108
113
109 :param str code: The code already present
114 :param str code: The code already present
110 :param int cursor_pos: The position in the code where completion is requested
115 :param int cursor_pos: The position in the code where completion is requested
111
116
112 .. seealso::
117 .. seealso::
113
118
114 :ref:`msging_completion` messages
119 :ref:`msging_completion` messages
115
120
116 .. method:: do_inspect(code, cusor_pos, detail_level=0)
121 .. method:: do_inspect(code, cusor_pos, detail_level=0)
117
122
118 Object introspection
123 Object introspection
119
124
120 :param str code: The code
125 :param str code: The code
121 :param int cursor_pos: The position in the code where introspection is requested
126 :param int cursor_pos: The position in the code where introspection is requested
122 :param int detail_level: 0 or 1 for more or less detail. In IPython, 1 gets
127 :param int detail_level: 0 or 1 for more or less detail. In IPython, 1 gets
123 the source code.
128 the source code.
124
129
125 .. seealso::
130 .. seealso::
126
131
127 :ref:`msging_inspection` messages
132 :ref:`msging_inspection` messages
128
133
129 .. method:: do_history(hist_access_type, output, raw, session=None, start=None, stop=None, n=None, pattern=None, unique=False)
134 .. method:: do_history(hist_access_type, output, raw, session=None, start=None, stop=None, n=None, pattern=None, unique=False)
130
135
131 History access. Only the relevant parameters for the type of history
136 History access. Only the relevant parameters for the type of history
132 request concerned will be passed, so your method definition must have defaults
137 request concerned will be passed, so your method definition must have defaults
133 for all the arguments shown with defaults here.
138 for all the arguments shown with defaults here.
134
139
135 .. seealso::
140 .. seealso::
136
141
137 :ref:`msging_history` messages
142 :ref:`msging_history` messages
138
143
139 .. method:: do_shutdown(restart)
144 .. method:: do_shutdown(restart)
140
145
141 Shutdown the kernel. You only need to handle your own clean up - the kernel
146 Shutdown the kernel. You only need to handle your own clean up - the kernel
142 machinery will take care of cleaning up its own things before stopping.
147 machinery will take care of cleaning up its own things before stopping.
143
148
144 :param bool restart: Whether the kernel will be started again afterwards
149 :param bool restart: Whether the kernel will be started again afterwards
145
150
146 .. seealso::
151 .. seealso::
147
152
148 :ref:`msging_shutdown` messages
153 :ref:`msging_shutdown` messages
General Comments 0
You need to be logged in to leave comments. Login now