##// END OF EJS Templates
Refer to jupyter_client docs for message spec...
Thomas Kluyver -
Show More
@@ -193,6 +193,7 b" htmlhelp_basename = 'ipythondoc'"
193 intersphinx_mapping = {'python': ('http://docs.python.org/2/', None),
193 intersphinx_mapping = {'python': ('http://docs.python.org/2/', None),
194 'rpy2': ('http://rpy.sourceforge.net/rpy2/doc-2.4/html/', None),
194 'rpy2': ('http://rpy.sourceforge.net/rpy2/doc-2.4/html/', None),
195 'traitlets': ('http://traitlets.readthedocs.org/en/latest/', None),
195 'traitlets': ('http://traitlets.readthedocs.org/en/latest/', None),
196 'jupyterclient': ('http://jupyter-client.readthedocs.org/en/latest/', None),
196 }
197 }
197
198
198 # Options for LaTeX output
199 # Options for LaTeX output
@@ -20,7 +20,6 b' on the IPython GitHub wiki.'
20 :maxdepth: 1
20 :maxdepth: 1
21
21
22 how_ipython_works
22 how_ipython_works
23 messaging
24 kernels
23 kernels
25 wrapperkernels
24 wrapperkernels
26 execution
25 execution
This diff has been collapsed as it changes many lines, (1222 lines changed) Show them Hide them
@@ -1,1219 +1,7 b''
1 .. _messaging:
1 :orphan:
2
2
3 ======================
3 Messaging in IPython
4 Messaging in IPython
4 ====================
5 ======================
6
5
7
6 The message specification is now part of Jupyter - see
8 Versioning
7 :ref:`jupyterclient:messaging` for the documentation.
9 ==========
10
11 The IPython message specification is versioned independently of IPython.
12 The current version of the specification is 5.0.
13
14
15 Introduction
16 ============
17
18 This document explains the basic communications design and messaging
19 specification for how the various IPython objects interact over a network
20 transport. The current implementation uses the ZeroMQ_ library for messaging
21 within and between hosts.
22
23 .. Note::
24
25 This document should be considered the authoritative description of the
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
28 common reference for all protocol details.
29
30 The basic design is explained in the following diagram:
31
32 .. image:: figs/frontend-kernel.png
33 :width: 450px
34 :alt: IPython kernel/frontend messaging architecture.
35 :align: center
36 :target: ../_images/frontend-kernel.png
37
38 A single kernel can be simultaneously connected to one or more frontends. The
39 kernel has three sockets that serve the following functions:
40
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
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
45 each frontend and the kernel.
46
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
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`
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
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
55 about communications taking place with one client over the shell channel
56 to be made available to all clients in a uniform manner.
57
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.
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
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
64 otherwise indicating that the user is to type input for the kernel instead
65 of normal commands in the frontend.
66
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
69 which ones are from other clients, so they can display each type
70 appropriately.
71
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).
74
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
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
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
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).
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.
85
86 .. Note::
87
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.
90
91 General Message Format
92 ======================
93
94 A message is defined by the following four-dictionary structure::
95
96 {
97 # The message header contains a pair of unique identifiers for 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
100 # collaborative settings where multiple users may be interacting with the
101 # same kernel simultaneously, so that frontends can label the various
102 # messages in a meaningful way.
103 'header' : {
104 'msg_id' : uuid,
105 'username' : str,
106 'session' : uuid,
107 # All recognized message type strings are listed below.
108 'msg_type' : str,
109 # the message protocol version
110 'version' : '5.0',
111 },
112
113 # In a chain of messages, the header from the parent is copied so that
114 # clients can track where messages come from.
115 'parent_header' : dict,
116
117 # Any metadata associated with the message.
118 'metadata' : dict,
119
120 # The actual content of the message must be a dict, whose structure
121 # depends on the message type.
122 'content' : dict,
123 }
124
125 .. versionchanged:: 5.0
126
127 ``version`` key added to the header.
128
129 .. _wire_protocol:
130
131 The Wire Protocol
132 =================
133
134
135 This message format exists at a high level,
136 but does not describe the actual *implementation* at the wire level in zeromq.
137 The canonical implementation of the message spec is our :class:`~IPython.kernel.zmq.session.Session` class.
138
139 .. note::
140
141 This section should only be relevant to non-Python consumers of the protocol.
142 Python consumers should simply import and use IPython's own implementation of the wire protocol
143 in the :class:`IPython.kernel.zmq.session.Session` object.
144
145 Every message is serialized to a sequence of at least six blobs of bytes:
146
147 .. sourcecode:: python
148
149 [
150 b'u-u-i-d', # zmq identity(ies)
151 b'<IDS|MSG>', # delimiter
152 b'baddad42', # HMAC signature
153 b'{header}', # serialized header dict
154 b'{parent_header}', # serialized parent header dict
155 b'{metadata}', # serialized metadata dict
156 b'{content}', # serialized content dict
157 b'blob', # extra raw data buffer(s)
158 ...
159 ]
160
161 The front of the message is the ZeroMQ routing prefix,
162 which can be zero or more socket identities.
163 This is every piece of the message prior to the delimiter key ``<IDS|MSG>``.
164 In the case of IOPub, there should be just one prefix component,
165 which is the topic for IOPub subscribers, e.g. ``execute_result``, ``display_data``.
166
167 .. note::
168
169 In most cases, the IOPub topics are irrelevant and completely ignored,
170 because frontends just subscribe to all topics.
171 The convention used in the IPython kernel is to use the msg_type as the topic,
172 and possibly extra information about the message, e.g. ``execute_result`` or ``stream.stdout``
173
174 After the delimiter is the `HMAC`_ signature of the message, used for authentication.
175 If authentication is disabled, this should be an empty string.
176 By default, the hashing function used for computing these signatures is sha256.
177
178 .. _HMAC: http://en.wikipedia.org/wiki/HMAC
179
180 .. note::
181
182 To disable authentication and signature checking,
183 set the `key` field of a connection file to an empty string.
184
185 The signature is the HMAC hex digest of the concatenation of:
186
187 - A shared key (typically the ``key`` field of a connection file)
188 - The serialized header dict
189 - The serialized parent header dict
190 - The serialized metadata dict
191 - The serialized content dict
192
193 In Python, this is implemented via:
194
195 .. sourcecode:: python
196
197 # once:
198 digester = HMAC(key, digestmod=hashlib.sha256)
199
200 # for each message
201 d = digester.copy()
202 for serialized_dict in (header, parent, metadata, content):
203 d.update(serialized_dict)
204 signature = d.hexdigest()
205
206 After the signature is the actual message, always in four frames of bytes.
207 The four dictionaries that compose a message are serialized separately,
208 in the order of header, parent header, metadata, and content.
209 These can be serialized by any function that turns a dict into bytes.
210 The default and most common serialization is JSON, but msgpack and pickle
211 are common alternatives.
212
213 After the serialized dicts are zero to many raw data buffers,
214 which can be used by message types that support binary data (mainly apply and data_pub).
215
216
217 Python functional API
218 =====================
219
220 As messages are dicts, they map naturally to a ``func(**kw)`` call form. We
221 should develop, at a few key points, functional forms of all the requests that
222 take arguments in this manner and automatically construct the necessary dict
223 for sending.
224
225 In addition, the Python implementation of the message specification extends
226 messages upon deserialization to the following form for convenience::
227
228 {
229 'header' : dict,
230 # The msg's unique identifier and type are always stored in the header,
231 # but the Python implementation copies them to the top level.
232 'msg_id' : uuid,
233 'msg_type' : str,
234 'parent_header' : dict,
235 'content' : dict,
236 'metadata' : dict,
237 }
238
239 All messages sent to or received by any IPython process should have this
240 extended structure.
241
242
243 Messages on the shell ROUTER/DEALER sockets
244 ===========================================
245
246 .. _execute:
247
248 Execute
249 -------
250
251 This message type is used by frontends to ask the kernel to execute code on
252 behalf of the user, in a namespace reserved to the user's variables (and thus
253 separate from the kernel's own internal code and variables).
254
255 Message type: ``execute_request``::
256
257 content = {
258 # Source code to be executed by the kernel, one or more lines.
259 'code' : str,
260
261 # A boolean flag which, if True, signals the kernel to execute
262 # this code as quietly as possible.
263 # silent=True forces store_history to be False,
264 # and will *not*:
265 # - broadcast output on the IOPUB channel
266 # - have an execute_result
267 # The default is False.
268 'silent' : bool,
269
270 # A boolean flag which, if True, signals the kernel to populate history
271 # The default is True if silent is False. If silent is True, store_history
272 # is forced to be False.
273 'store_history' : bool,
274
275 # A dict mapping names to expressions to be evaluated in the
276 # user's dict. The rich display-data representation of each will be evaluated after execution.
277 # See the display_data content for the structure of the representation data.
278 'user_expressions' : dict,
279
280 # Some frontends do not support stdin requests.
281 # If raw_input is called from code executed from such a frontend,
282 # a StdinNotImplementedError will be raised.
283 'allow_stdin' : True,
284
285 # A boolean flag, which, if True, does not abort the execution queue, if an exception is encountered.
286 # This allows the queued execution of multiple execute_requests, even if they generate exceptions.
287 'stop_on_error' : False,
288 }
289
290 .. versionchanged:: 5.0
291
292 ``user_variables`` removed, because it is redundant with user_expressions.
293
294 The ``code`` field contains a single string (possibly multiline) to be executed.
295
296 The ``user_expressions`` field deserves a detailed explanation. In the past, IPython had
297 the notion of a prompt string that allowed arbitrary code to be evaluated, and
298 this was put to good use by many in creating prompts that displayed system
299 status, path information, and even more esoteric uses like remote instrument
300 status acquired over the network. But now that IPython has a clean separation
301 between the kernel and the clients, the kernel has no prompt knowledge; prompts
302 are a frontend feature, and it should be even possible for different
303 frontends to display different prompts while interacting with the same kernel.
304 ``user_expressions`` can be used to retrieve this information.
305
306 Any error in evaluating any expression in ``user_expressions`` will result in
307 only that key containing a standard error message, of the form::
308
309 {
310 'status' : 'error',
311 'ename' : 'NameError',
312 'evalue' : 'foo',
313 'traceback' : ...
314 }
315
316 .. Note::
317
318 In order to obtain the current execution counter for the purposes of
319 displaying input prompts, frontends may make an execution request with an
320 empty code string and ``silent=True``.
321
322 Upon completion of the execution request, the kernel *always* sends a reply,
323 with a status code indicating what happened and additional data depending on
324 the outcome. See :ref:`below <execution_results>` for the possible return
325 codes and associated data.
326
327 .. seealso::
328
329 :ref:`execution_semantics`
330
331 .. _execution_counter:
332
333 Execution counter (prompt number)
334 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
335
336 The kernel should have a single, monotonically increasing counter of all execution
337 requests that are made with ``store_history=True``. This counter is used to populate
338 the ``In[n]`` and ``Out[n]`` prompts. The value of this counter will be returned as the
339 ``execution_count`` field of all ``execute_reply`` and ``execute_input`` messages.
340
341 .. _execution_results:
342
343 Execution results
344 ~~~~~~~~~~~~~~~~~
345
346 Message type: ``execute_reply``::
347
348 content = {
349 # One of: 'ok' OR 'error' OR 'abort'
350 'status' : str,
351
352 # The global kernel counter that increases by one with each request that
353 # stores history. This will typically be used by clients to display
354 # prompt numbers to the user. If the request did not store history, this will
355 # be the current value of the counter in the kernel.
356 'execution_count' : int,
357 }
358
359 When status is 'ok', the following extra fields are present::
360
361 {
362 # 'payload' will be a list of payload dicts, and is optional.
363 # payloads are considered deprecated.
364 # The only requirement of each payload dict is that it have a 'source' key,
365 # which is a string classifying the payload (e.g. 'page').
366
367 'payload' : list(dict),
368
369 # Results for the user_expressions.
370 'user_expressions' : dict,
371 }
372
373 .. versionchanged:: 5.0
374
375 ``user_variables`` is removed, use user_expressions instead.
376
377 When status is 'error', the following extra fields are present::
378
379 {
380 'ename' : str, # Exception name, as a string
381 'evalue' : str, # Exception value, as a string
382
383 # The traceback will contain a list of frames, represented each as a
384 # string. For now we'll stick to the existing design of ultraTB, which
385 # controls exception level of detail statefully. But eventually we'll
386 # want to grow into a model where more information is collected and
387 # packed into the traceback object, with clients deciding how little or
388 # how much of it to unpack. But for now, let's start with a simple list
389 # of strings, since that requires only minimal changes to ultratb as
390 # written.
391 'traceback' : list,
392 }
393
394
395 When status is 'abort', there are for now no additional data fields. This
396 happens when the kernel was interrupted by a signal.
397
398 Payloads
399 ********
400
401 .. admonition:: Execution payloads
402
403 Payloads are considered deprecated, though their replacement is not yet implemented.
404
405 Payloads are a way to trigger frontend actions from the kernel. Current payloads:
406
407 **page**: display data in a pager.
408
409 Pager output is used for introspection, or other displayed information that's not considered output.
410 Pager payloads are generally displayed in a separate pane, that can be viewed alongside code,
411 and are not included in notebook documents.
412
413 .. sourcecode:: python
414
415 {
416 "source": "page",
417 # mime-bundle of data to display in the pager.
418 # Must include text/plain.
419 "data": mimebundle,
420 # line offset to start from
421 "start": int,
422 }
423
424 **set_next_input**: create a new output
425
426 used to create new cells in the notebook,
427 or set the next input in a console interface.
428 The main example being ``%load``.
429
430 .. sourcecode:: python
431
432 {
433 "source": "set_next_input",
434 # the text contents of the cell to create
435 "text": "some cell content",
436 # If true, replace the current cell in document UIs instead of inserting
437 # a cell. Ignored in console UIs.
438 "replace": bool,
439 }
440
441 **edit**: open a file for editing.
442
443 Triggered by `%edit`. Only the QtConsole currently supports edit payloads.
444
445 .. sourcecode:: python
446
447 {
448 "source": "edit",
449 "filename": "/path/to/file.py", # the file to edit
450 "line_number": int, # the line number to start with
451 }
452
453 **ask_exit**: instruct the frontend to prompt the user for exit
454
455 Allows the kernel to request exit, e.g. via ``%exit`` in IPython.
456 Only for console frontends.
457
458 .. sourcecode:: python
459
460 {
461 "source": "ask_exit",
462 # whether the kernel should be left running, only closing the client
463 "keepkernel": bool,
464 }
465
466
467 .. _msging_inspection:
468
469 Introspection
470 -------------
471
472 Code can be inspected to show useful information to the user.
473 It is up to the Kernel to decide what information should be displayed, and its formatting.
474
475 Message type: ``inspect_request``::
476
477 content = {
478 # The code context in which introspection is requested
479 # this may be up to an entire multiline cell.
480 'code' : str,
481
482 # The cursor position within 'code' (in unicode characters) where inspection is requested
483 'cursor_pos' : int,
484
485 # The level of detail desired. In IPython, the default (0) is equivalent to typing
486 # 'x?' at the prompt, 1 is equivalent to 'x??'.
487 # The difference is up to kernels, but in IPython level 1 includes the source code
488 # if available.
489 'detail_level' : 0 or 1,
490 }
491
492 .. versionchanged:: 5.0
493
494 ``object_info_request`` renamed to ``inspect_request``.
495
496 .. versionchanged:: 5.0
497
498 ``name`` key replaced with ``code`` and ``cursor_pos``,
499 moving the lexing responsibility to the kernel.
500
501 The reply is a mime-bundle, like a `display_data`_ message,
502 which should be a formatted representation of information about the context.
503 In the notebook, this is used to show tooltips over function calls, etc.
504
505 Message type: ``inspect_reply``::
506
507 content = {
508 # 'ok' if the request succeeded or 'error', with error information as in all other replies.
509 'status' : 'ok',
510
511 # found should be true if an object was found, false otherwise
512 'found' : bool,
513
514 # data can be empty if nothing is found
515 'data' : dict,
516 'metadata' : dict,
517 }
518
519 .. versionchanged:: 5.0
520
521 ``object_info_reply`` renamed to ``inspect_reply``.
522
523 .. versionchanged:: 5.0
524
525 Reply is changed from structured data to a mime bundle, allowing formatting decisions to be made by the kernel.
526
527 .. _msging_completion:
528
529 Completion
530 ----------
531
532 Message type: ``complete_request``::
533
534 content = {
535 # The code context in which completion is requested
536 # this may be up to an entire multiline cell, such as
537 # 'foo = a.isal'
538 'code' : str,
539
540 # The cursor position within 'code' (in unicode characters) where completion is requested
541 'cursor_pos' : int,
542 }
543
544 .. versionchanged:: 5.0
545
546 ``line``, ``block``, and ``text`` keys are removed in favor of a single ``code`` for context.
547 Lexing is up to the kernel.
548
549
550 Message type: ``complete_reply``::
551
552 content = {
553 # The list of all matches to the completion request, such as
554 # ['a.isalnum', 'a.isalpha'] for the above example.
555 'matches' : list,
556
557 # The range of text that should be replaced by the above matches when a completion is accepted.
558 # typically cursor_end is the same as cursor_pos in the request.
559 'cursor_start' : int,
560 'cursor_end' : int,
561
562 # Information that frontend plugins might use for extra display information about completions.
563 'metadata' : dict,
564
565 # status should be 'ok' unless an exception was raised during the request,
566 # in which case it should be 'error', along with the usual error message content
567 # in other messages.
568 'status' : 'ok'
569 }
570
571 .. versionchanged:: 5.0
572
573 - ``matched_text`` is removed in favor of ``cursor_start`` and ``cursor_end``.
574 - ``metadata`` is added for extended information.
575
576 .. _msging_history:
577
578 History
579 -------
580
581 For clients to explicitly request history from a kernel. The kernel has all
582 the actual execution history stored in a single location, so clients can
583 request it from the kernel when needed.
584
585 Message type: ``history_request``::
586
587 content = {
588
589 # If True, also return output history in the resulting dict.
590 'output' : bool,
591
592 # If True, return the raw input history, else the transformed input.
593 'raw' : bool,
594
595 # So far, this can be 'range', 'tail' or 'search'.
596 'hist_access_type' : str,
597
598 # If hist_access_type is 'range', get a range of input cells. session can
599 # be a positive session number, or a negative number to count back from
600 # the current session.
601 'session' : int,
602 # start and stop are line numbers within that session.
603 'start' : int,
604 'stop' : int,
605
606 # If hist_access_type is 'tail' or 'search', get the last n cells.
607 'n' : int,
608
609 # If hist_access_type is 'search', get cells matching the specified glob
610 # pattern (with * and ? as wildcards).
611 'pattern' : str,
612
613 # If hist_access_type is 'search' and unique is true, do not
614 # include duplicated history. Default is false.
615 'unique' : bool,
616
617 }
618
619 .. versionadded:: 4.0
620 The key ``unique`` for ``history_request``.
621
622 Message type: ``history_reply``::
623
624 content = {
625 # A list of 3 tuples, either:
626 # (session, line_number, input) or
627 # (session, line_number, (input, output)),
628 # depending on whether output was False or True, respectively.
629 'history' : list,
630 }
631
632 .. _msging_is_complete:
633
634 Code completeness
635 -----------------
636
637 .. versionadded:: 5.0
638
639 When the user enters a line in a console style interface, the console must
640 decide whether to immediately execute the current code, or whether to show a
641 continuation prompt for further input. For instance, in Python ``a = 5`` would
642 be executed immediately, while ``for i in range(5):`` would expect further input.
643
644 There are four possible replies:
645
646 - *complete* code is ready to be executed
647 - *incomplete* code should prompt for another line
648 - *invalid* code will typically be sent for execution, so that the user sees the
649 error soonest.
650 - *unknown* - if the kernel is not able to determine this. The frontend should
651 also handle the kernel not replying promptly. It may default to sending the
652 code for execution, or it may implement simple fallback heuristics for whether
653 to execute the code (e.g. execute after a blank line).
654
655 Frontends may have ways to override this, forcing the code to be sent for
656 execution or forcing a continuation prompt.
657
658 Message type: ``is_complete_request``::
659
660 content = {
661 # The code entered so far as a multiline string
662 'code' : str,
663 }
664
665 Message type: ``is_complete_reply``::
666
667 content = {
668 # One of 'complete', 'incomplete', 'invalid', 'unknown'
669 'status' : str,
670
671 # If status is 'incomplete', indent should contain the characters to use
672 # to indent the next line. This is only a hint: frontends may ignore it
673 # and use their own autoindentation rules. For other statuses, this
674 # field does not exist.
675 'indent': str,
676 }
677
678 Connect
679 -------
680
681 When a client connects to the request/reply socket of the kernel, it can issue
682 a connect request to get basic information about the kernel, such as the ports
683 the other ZeroMQ sockets are listening on. This allows clients to only have
684 to know about a single port (the shell channel) to connect to a kernel.
685
686 Message type: ``connect_request``::
687
688 content = {
689 }
690
691 Message type: ``connect_reply``::
692
693 content = {
694 'shell_port' : int, # The port the shell ROUTER socket is listening on.
695 'iopub_port' : int, # The port the PUB socket is listening on.
696 'stdin_port' : int, # The port the stdin ROUTER socket is listening on.
697 'hb_port' : int, # The port the heartbeat socket is listening on.
698 }
699
700 .. _msging_kernel_info:
701
702 Kernel info
703 -----------
704
705 If a client needs to know information about the kernel, it can
706 make a request of the kernel's information.
707 This message can be used to fetch core information of the
708 kernel, including language (e.g., Python), language version number and
709 IPython version number, and the IPython message spec version number.
710
711 Message type: ``kernel_info_request``::
712
713 content = {
714 }
715
716 Message type: ``kernel_info_reply``::
717
718 content = {
719 # Version of messaging protocol.
720 # The first integer indicates major version. It is incremented when
721 # there is any backward incompatible change.
722 # The second integer indicates minor version. It is incremented when
723 # there is any backward compatible change.
724 'protocol_version': 'X.Y.Z',
725
726 # The kernel implementation name
727 # (e.g. 'ipython' for the IPython kernel)
728 'implementation': str,
729
730 # Implementation version number.
731 # The version number of the kernel's implementation
732 # (e.g. IPython.__version__ for the IPython kernel)
733 'implementation_version': 'X.Y.Z',
734
735 # Information about the language of code for the kernel
736 'language_info': {
737 # Name of the programming language in which kernel is implemented.
738 # Kernel included in IPython returns 'python'.
739 'name': str,
740
741 # Language version number.
742 # It is Python version number (e.g., '2.7.3') for the kernel
743 # included in IPython.
744 'version': 'X.Y.Z',
745
746 # mimetype for script files in this language
747 'mimetype': str,
748
749 # Extension including the dot, e.g. '.py'
750 'file_extension': str,
751
752 # Pygments lexer, for highlighting
753 # Only needed if it differs from the top level 'language' field.
754 'pygments_lexer': str,
755
756 # Codemirror mode, for for highlighting in the notebook.
757 # Only needed if it differs from the top level 'language' field.
758 'codemirror_mode': str or dict,
759
760 # Nbconvert exporter, if notebooks written with this kernel should
761 # be exported with something other than the general 'script'
762 # exporter.
763 'nbconvert_exporter': str,
764 },
765
766 # A banner of information about the kernel,
767 # which may be desplayed in console environments.
768 'banner' : str,
769
770 # Optional: A list of dictionaries, each with keys 'text' and 'url'.
771 # These will be displayed in the help menu in the notebook UI.
772 'help_links': [
773 {'text': str, 'url': str}
774 ],
775 }
776
777 Refer to the lists of available `Pygments lexers <http://pygments.org/docs/lexers/>`_
778 and `codemirror modes <http://codemirror.net/mode/index.html>`_ for those fields.
779
780 .. versionchanged:: 5.0
781
782 Versions changed from lists of integers to strings.
783
784 .. versionchanged:: 5.0
785
786 ``ipython_version`` is removed.
787
788 .. versionchanged:: 5.0
789
790 ``language_info``, ``implementation``, ``implementation_version``, ``banner``
791 and ``help_links`` keys are added.
792
793 .. versionchanged:: 5.0
794
795 ``language_version`` moved to ``language_info.version``
796
797 .. versionchanged:: 5.0
798
799 ``language`` moved to ``language_info.name``
800
801 .. _msging_shutdown:
802
803 Kernel shutdown
804 ---------------
805
806 The clients can request the kernel to shut itself down; this is used in
807 multiple cases:
808
809 - when the user chooses to close the client application via a menu or window
810 control.
811 - when the user types 'exit' or 'quit' (or their uppercase magic equivalents).
812 - when the user chooses a GUI method (like the 'Ctrl-C' shortcut in the
813 IPythonQt client) to force a kernel restart to get a clean kernel without
814 losing client-side state like history or inlined figures.
815
816 The client sends a shutdown request to the kernel, and once it receives the
817 reply message (which is otherwise empty), it can assume that the kernel has
818 completed shutdown safely.
819
820 Upon their own shutdown, client applications will typically execute a last
821 minute sanity check and forcefully terminate any kernel that is still alive, to
822 avoid leaving stray processes in the user's machine.
823
824 Message type: ``shutdown_request``::
825
826 content = {
827 'restart' : bool # whether the shutdown is final, or precedes a restart
828 }
829
830 Message type: ``shutdown_reply``::
831
832 content = {
833 'restart' : bool # whether the shutdown is final, or precedes a restart
834 }
835
836 .. Note::
837
838 When the clients detect a dead kernel thanks to inactivity on the heartbeat
839 socket, they simply send a forceful process termination signal, since a dead
840 process is unlikely to respond in any useful way to messages.
841
842
843 Messages on the PUB/SUB socket
844 ==============================
845
846 Streams (stdout, stderr, etc)
847 ------------------------------
848
849 Message type: ``stream``::
850
851 content = {
852 # The name of the stream is one of 'stdout', 'stderr'
853 'name' : str,
854
855 # The text is an arbitrary string to be written to that stream
856 'text' : str,
857 }
858
859 .. versionchanged:: 5.0
860
861 'data' key renamed to 'text' for conistency with the notebook format.
862
863 Display Data
864 ------------
865
866 This type of message is used to bring back data that should be displayed (text,
867 html, svg, etc.) in the frontends. This data is published to all frontends.
868 Each message can have multiple representations of the data; it is up to the
869 frontend to decide which to use and how. A single message should contain all
870 possible representations of the same information. Each representation should
871 be a JSON'able data structure, and should be a valid MIME type.
872
873 Some questions remain about this design:
874
875 * Do we use this message type for execute_result/displayhook? Probably not, because
876 the displayhook also has to handle the Out prompt display. On the other hand
877 we could put that information into the metadata section.
878
879 .. _display_data:
880
881 Message type: ``display_data``::
882
883 content = {
884
885 # Who create the data
886 'source' : str,
887
888 # The data dict contains key/value pairs, where the keys are MIME
889 # types and the values are the raw data of the representation in that
890 # format.
891 'data' : dict,
892
893 # Any metadata that describes the data
894 'metadata' : dict
895 }
896
897
898 The ``metadata`` contains any metadata that describes the output.
899 Global keys are assumed to apply to the output as a whole.
900 The ``metadata`` dict can also contain mime-type keys, which will be sub-dictionaries,
901 which are interpreted as applying only to output of that type.
902 Third parties should put any data they write into a single dict
903 with a reasonably unique name to avoid conflicts.
904
905 The only metadata keys currently defined in IPython are the width and height
906 of images::
907
908 metadata = {
909 'image/png' : {
910 'width': 640,
911 'height': 480
912 }
913 }
914
915
916 .. versionchanged:: 5.0
917
918 `application/json` data should be unpacked JSON data,
919 not double-serialized as a JSON string.
920
921
922 Raw Data Publication
923 --------------------
924
925 ``display_data`` lets you publish *representations* of data, such as images and html.
926 This ``data_pub`` message lets you publish *actual raw data*, sent via message buffers.
927
928 data_pub messages are constructed via the :func:`IPython.lib.datapub.publish_data` function:
929
930 .. sourcecode:: python
931
932 from IPython.kernel.zmq.datapub import publish_data
933 ns = dict(x=my_array)
934 publish_data(ns)
935
936
937 Message type: ``data_pub``::
938
939 content = {
940 # the keys of the data dict, after it has been unserialized
941 'keys' : ['a', 'b']
942 }
943 # the namespace dict will be serialized in the message buffers,
944 # which will have a length of at least one
945 buffers = [b'pdict', ...]
946
947
948 The interpretation of a sequence of data_pub messages for a given parent request should be
949 to update a single namespace with subsequent results.
950
951 .. note::
952
953 No frontends directly handle data_pub messages at this time.
954 It is currently only used by the client/engines in :mod:`IPython.parallel`,
955 where engines may publish *data* to the Client,
956 of which the Client can then publish *representations* via ``display_data``
957 to various frontends.
958
959 Code inputs
960 -----------
961
962 To let all frontends know what code is being executed at any given time, these
963 messages contain a re-broadcast of the ``code`` portion of an
964 :ref:`execute_request <execute>`, along with the :ref:`execution_count
965 <execution_counter>`.
966
967 Message type: ``execute_input``::
968
969 content = {
970 'code' : str, # Source code to be executed, one or more lines
971
972 # The counter for this execution is also provided so that clients can
973 # display it, since IPython automatically creates variables called _iN
974 # (for input prompt In[N]).
975 'execution_count' : int
976 }
977
978 .. versionchanged:: 5.0
979
980 ``pyin`` is renamed to ``execute_input``.
981
982
983 Execution results
984 -----------------
985
986 Results of an execution are published as an ``execute_result``.
987 These are identical to `display_data`_ messages, with the addition of an ``execution_count`` key.
988
989 Results can have multiple simultaneous formats depending on its
990 configuration. A plain text representation should always be provided
991 in the ``text/plain`` mime-type. Frontends are free to display any or all of these
992 according to its capabilities.
993 Frontends should ignore mime-types they do not understand. The data itself is
994 any JSON object and depends on the format. It is often, but not always a string.
995
996 Message type: ``execute_result``::
997
998 content = {
999
1000 # The counter for this execution is also provided so that clients can
1001 # display it, since IPython automatically creates variables called _N
1002 # (for prompt N).
1003 'execution_count' : int,
1004
1005 # data and metadata are identical to a display_data message.
1006 # the object being displayed is that passed to the display hook,
1007 # i.e. the *result* of the execution.
1008 'data' : dict,
1009 'metadata' : dict,
1010 }
1011
1012 Execution errors
1013 ----------------
1014
1015 When an error occurs during code execution
1016
1017 Message type: ``error``::
1018
1019 content = {
1020 # Similar content to the execute_reply messages for the 'error' case,
1021 # except the 'status' field is omitted.
1022 }
1023
1024 .. versionchanged:: 5.0
1025
1026 ``pyerr`` renamed to ``error``
1027
1028 Kernel status
1029 -------------
1030
1031 This message type is used by frontends to monitor the status of the kernel.
1032
1033 Message type: ``status``::
1034
1035 content = {
1036 # When the kernel starts to handle a message, it will enter the 'busy'
1037 # state and when it finishes, it will enter the 'idle' state.
1038 # The kernel will publish state 'starting' exactly once at process startup.
1039 execution_state : ('busy', 'idle', 'starting')
1040 }
1041
1042 .. versionchanged:: 5.0
1043
1044 Busy and idle messages should be sent before/after handling every message,
1045 not just execution.
1046
1047 .. note::
1048
1049 Extra status messages are added between the notebook webserver and websocket clients
1050 that are not sent by the kernel. These are:
1051
1052 - restarting (kernel has died, but will be automatically restarted)
1053 - dead (kernel has died, restarting has failed)
1054
1055 Clear output
1056 ------------
1057
1058 This message type is used to clear the output that is visible on the frontend.
1059
1060 Message type: ``clear_output``::
1061
1062 content = {
1063
1064 # Wait to clear the output until new output is available. Clears the
1065 # existing output immediately before the new output is displayed.
1066 # Useful for creating simple animations with minimal flickering.
1067 'wait' : bool,
1068 }
1069
1070 .. versionchanged:: 4.1
1071
1072 ``stdout``, ``stderr``, and ``display`` boolean keys for selective clearing are removed,
1073 and ``wait`` is added.
1074 The selective clearing keys are ignored in v4 and the default behavior remains the same,
1075 so v4 clear_output messages will be safely handled by a v4.1 frontend.
1076
1077
1078 Messages on the stdin ROUTER/DEALER sockets
1079 ===========================================
1080
1081 This is a socket where the request/reply pattern goes in the opposite direction:
1082 from the kernel to a *single* frontend, and its purpose is to allow
1083 ``raw_input`` and similar operations that read from ``sys.stdin`` on the kernel
1084 to be fulfilled by the client. The request should be made to the frontend that
1085 made the execution request that prompted ``raw_input`` to be called. For now we
1086 will keep these messages as simple as possible, since they only mean to convey
1087 the ``raw_input(prompt)`` call.
1088
1089 Message type: ``input_request``::
1090
1091 content = {
1092 # the text to show at the prompt
1093 'prompt' : str,
1094 # Is the request for a password?
1095 # If so, the frontend shouldn't echo input.
1096 'password' : bool
1097 }
1098
1099 Message type: ``input_reply``::
1100
1101 content = { 'value' : str }
1102
1103
1104 When ``password`` is True, the frontend should not echo the input as it is entered.
1105
1106 .. versionchanged:: 5.0
1107
1108 ``password`` key added.
1109
1110 .. note::
1111
1112 The stdin socket of the client is required to have the same zmq IDENTITY
1113 as the client's shell socket.
1114 Because of this, the ``input_request`` must be sent with the same IDENTITY
1115 routing prefix as the ``execute_reply`` in order for the frontend to receive
1116 the message.
1117
1118 .. note::
1119
1120 We do not explicitly try to forward the raw ``sys.stdin`` object, because in
1121 practice the kernel should behave like an interactive program. When a
1122 program is opened on the console, the keyboard effectively takes over the
1123 ``stdin`` file descriptor, and it can't be used for raw reading anymore.
1124 Since the IPython kernel effectively behaves like a console program (albeit
1125 one whose "keyboard" is actually living in a separate process and
1126 transported over the zmq connection), raw ``stdin`` isn't expected to be
1127 available.
1128
1129 .. _kernel_heartbeat:
1130
1131 Heartbeat for kernels
1132 =====================
1133
1134 Clients send ping messages on a REQ socket, which are echoed right back
1135 from the Kernel's REP socket. These are simple bytestrings, not full JSON messages described above.
1136
1137
1138 Custom Messages
1139 ===============
1140
1141 .. versionadded:: 4.1
1142
1143 IPython 2.0 (msgspec v4.1) adds a messaging system for developers to add their own objects with Frontend
1144 and Kernel-side components, and allow them to communicate with each other.
1145 To do this, IPython adds a notion of a ``Comm``, which exists on both sides,
1146 and can communicate in either direction.
1147
1148 These messages are fully symmetrical - both the Kernel and the Frontend can send each message,
1149 and no messages expect a reply.
1150 The Kernel listens for these messages on the Shell channel,
1151 and the Frontend listens for them on the IOPub channel.
1152
1153 Opening a Comm
1154 --------------
1155
1156 Opening a Comm produces a ``comm_open`` message, to be sent to the other side::
1157
1158 {
1159 'comm_id' : 'u-u-i-d',
1160 'target_name' : 'my_comm',
1161 'data' : {}
1162 }
1163
1164 Every Comm has an ID and a target name.
1165 The code handling the message on the receiving side is responsible for maintaining a mapping
1166 of target_name keys to constructors.
1167 After a ``comm_open`` message has been sent,
1168 there should be a corresponding Comm instance on both sides.
1169 The ``data`` key is always a dict and can be any extra JSON information used in initialization of the comm.
1170
1171 If the ``target_name`` key is not found on the receiving side,
1172 then it should immediately reply with a ``comm_close`` message to avoid an inconsistent state.
1173
1174 Comm Messages
1175 -------------
1176
1177 Comm messages are one-way communications to update comm state,
1178 used for synchronizing widget state, or simply requesting actions of a comm's counterpart.
1179
1180 Essentially, each comm pair defines their own message specification implemented inside the ``data`` dict.
1181
1182 There are no expected replies (of course, one side can send another ``comm_msg`` in reply).
1183
1184 Message type: ``comm_msg``::
1185
1186 {
1187 'comm_id' : 'u-u-i-d',
1188 'data' : {}
1189 }
1190
1191 Tearing Down Comms
1192 ------------------
1193
1194 Since comms live on both sides, when a comm is destroyed the other side must be notified.
1195 This is done with a ``comm_close`` message.
1196
1197 Message type: ``comm_close``::
1198
1199 {
1200 'comm_id' : 'u-u-i-d',
1201 'data' : {}
1202 }
1203
1204 Output Side Effects
1205 -------------------
1206
1207 Since comm messages can execute arbitrary user code,
1208 handlers should set the parent header and publish status busy / idle,
1209 just like an execute request.
1210
1211
1212 To Do
1213 =====
1214
1215 Missing things include:
1216
1217 * Important: finish thinking through the payload concept and API.
1218
1219 .. include:: ../links.txt
1 NO CONTENT: file was removed, binary diff hidden
NO CONTENT: file was removed, binary diff hidden
1 NO CONTENT: file was removed
NO CONTENT: file was removed
This diff has been collapsed as it changes many lines, (6792 lines changed) Show them Hide them
General Comments 0
You need to be logged in to leave comments. Login now