##// END OF EJS Templates
Document is_complete messages...
Thomas Kluyver -
Show More
@@ -1,150 +1,150 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Release data for the IPython project."""
2 """Release data for the IPython project."""
3
3
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (c) 2008, IPython Development Team.
5 # Copyright (c) 2008, IPython Development Team.
6 # Copyright (c) 2001, Fernando Perez <fernando.perez@colorado.edu>
6 # Copyright (c) 2001, Fernando Perez <fernando.perez@colorado.edu>
7 # Copyright (c) 2001, Janko Hauser <jhauser@zscout.de>
7 # Copyright (c) 2001, Janko Hauser <jhauser@zscout.de>
8 # Copyright (c) 2001, Nathaniel Gray <n8gray@caltech.edu>
8 # Copyright (c) 2001, Nathaniel Gray <n8gray@caltech.edu>
9 #
9 #
10 # Distributed under the terms of the Modified BSD License.
10 # Distributed under the terms of the Modified BSD License.
11 #
11 #
12 # The full license is in the file COPYING.txt, distributed with this software.
12 # The full license is in the file COPYING.txt, distributed with this software.
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14
14
15 # Name of the package for release purposes. This is the name which labels
15 # Name of the package for release purposes. This is the name which labels
16 # the tarballs and RPMs made by distutils, so it's best to lowercase it.
16 # the tarballs and RPMs made by distutils, so it's best to lowercase it.
17 name = 'ipython'
17 name = 'ipython'
18
18
19 # IPython version information. An empty _version_extra corresponds to a full
19 # IPython version information. An empty _version_extra corresponds to a full
20 # release. 'dev' as a _version_extra string means this is a development
20 # release. 'dev' as a _version_extra string means this is a development
21 # version
21 # version
22 _version_major = 3
22 _version_major = 3
23 _version_minor = 0
23 _version_minor = 0
24 _version_patch = 0
24 _version_patch = 0
25 _version_extra = 'dev'
25 _version_extra = 'dev'
26 # _version_extra = 'rc1'
26 # _version_extra = 'rc1'
27 # _version_extra = '' # Uncomment this for full releases
27 # _version_extra = '' # Uncomment this for full releases
28
28
29 # release.codename is deprecated in 2.0, will be removed in 3.0
29 # release.codename is deprecated in 2.0, will be removed in 3.0
30 codename = ''
30 codename = ''
31
31
32 # Construct full version string from these.
32 # Construct full version string from these.
33 _ver = [_version_major, _version_minor, _version_patch]
33 _ver = [_version_major, _version_minor, _version_patch]
34
34
35 __version__ = '.'.join(map(str, _ver))
35 __version__ = '.'.join(map(str, _ver))
36 if _version_extra:
36 if _version_extra:
37 __version__ = __version__ + '-' + _version_extra
37 __version__ = __version__ + '-' + _version_extra
38
38
39 version = __version__ # backwards compatibility name
39 version = __version__ # backwards compatibility name
40 version_info = (_version_major, _version_minor, _version_patch, _version_extra)
40 version_info = (_version_major, _version_minor, _version_patch, _version_extra)
41
41
42 # Change this when incrementing the kernel protocol version
42 # Change this when incrementing the kernel protocol version
43 kernel_protocol_version_info = (5, 0)
43 kernel_protocol_version_info = (5, 1)
44 kernel_protocol_version = "%i.%i" % kernel_protocol_version_info
44 kernel_protocol_version = "%i.%i" % kernel_protocol_version_info
45
45
46 description = "IPython: Productive Interactive Computing"
46 description = "IPython: Productive Interactive Computing"
47
47
48 long_description = \
48 long_description = \
49 """
49 """
50 IPython provides a rich toolkit to help you make the most out of using Python
50 IPython provides a rich toolkit to help you make the most out of using Python
51 interactively. Its main components are:
51 interactively. Its main components are:
52
52
53 * Powerful interactive Python shells (terminal- and Qt-based).
53 * Powerful interactive Python shells (terminal- and Qt-based).
54 * A web-based interactive notebook environment with all shell features plus
54 * A web-based interactive notebook environment with all shell features plus
55 support for embedded figures, animations and rich media.
55 support for embedded figures, animations and rich media.
56 * Support for interactive data visualization and use of GUI toolkits.
56 * Support for interactive data visualization and use of GUI toolkits.
57 * Flexible, embeddable interpreters to load into your own projects.
57 * Flexible, embeddable interpreters to load into your own projects.
58 * A high-performance library for high level and interactive parallel computing
58 * A high-performance library for high level and interactive parallel computing
59 that works in multicore systems, clusters, supercomputing and cloud scenarios.
59 that works in multicore systems, clusters, supercomputing and cloud scenarios.
60
60
61 The enhanced interactive Python shells have the following main features:
61 The enhanced interactive Python shells have the following main features:
62
62
63 * Comprehensive object introspection.
63 * Comprehensive object introspection.
64
64
65 * Input history, persistent across sessions.
65 * Input history, persistent across sessions.
66
66
67 * Caching of output results during a session with automatically generated
67 * Caching of output results during a session with automatically generated
68 references.
68 references.
69
69
70 * Extensible tab completion, with support by default for completion of python
70 * Extensible tab completion, with support by default for completion of python
71 variables and keywords, filenames and function keywords.
71 variables and keywords, filenames and function keywords.
72
72
73 * Extensible system of 'magic' commands for controlling the environment and
73 * Extensible system of 'magic' commands for controlling the environment and
74 performing many tasks related either to IPython or the operating system.
74 performing many tasks related either to IPython or the operating system.
75
75
76 * A rich configuration system with easy switching between different setups
76 * A rich configuration system with easy switching between different setups
77 (simpler than changing $PYTHONSTARTUP environment variables every time).
77 (simpler than changing $PYTHONSTARTUP environment variables every time).
78
78
79 * Session logging and reloading.
79 * Session logging and reloading.
80
80
81 * Extensible syntax processing for special purpose situations.
81 * Extensible syntax processing for special purpose situations.
82
82
83 * Access to the system shell with user-extensible alias system.
83 * Access to the system shell with user-extensible alias system.
84
84
85 * Easily embeddable in other Python programs and GUIs.
85 * Easily embeddable in other Python programs and GUIs.
86
86
87 * Integrated access to the pdb debugger and the Python profiler.
87 * Integrated access to the pdb debugger and the Python profiler.
88
88
89 The parallel computing architecture has the following main features:
89 The parallel computing architecture has the following main features:
90
90
91 * Quickly parallelize Python code from an interactive Python/IPython session.
91 * Quickly parallelize Python code from an interactive Python/IPython session.
92
92
93 * A flexible and dynamic process model that be deployed on anything from
93 * A flexible and dynamic process model that be deployed on anything from
94 multicore workstations to supercomputers.
94 multicore workstations to supercomputers.
95
95
96 * An architecture that supports many different styles of parallelism, from
96 * An architecture that supports many different styles of parallelism, from
97 message passing to task farming.
97 message passing to task farming.
98
98
99 * Both blocking and fully asynchronous interfaces.
99 * Both blocking and fully asynchronous interfaces.
100
100
101 * High level APIs that enable many things to be parallelized in a few lines
101 * High level APIs that enable many things to be parallelized in a few lines
102 of code.
102 of code.
103
103
104 * Share live parallel jobs with other users securely.
104 * Share live parallel jobs with other users securely.
105
105
106 * Dynamically load balanced task farming system.
106 * Dynamically load balanced task farming system.
107
107
108 * Robust error handling in parallel code.
108 * Robust error handling in parallel code.
109
109
110 The latest development version is always available from IPython's `GitHub
110 The latest development version is always available from IPython's `GitHub
111 site <http://github.com/ipython>`_.
111 site <http://github.com/ipython>`_.
112 """
112 """
113
113
114 license = 'BSD'
114 license = 'BSD'
115
115
116 authors = {'Fernando' : ('Fernando Perez','fperez.net@gmail.com'),
116 authors = {'Fernando' : ('Fernando Perez','fperez.net@gmail.com'),
117 'Janko' : ('Janko Hauser','jhauser@zscout.de'),
117 'Janko' : ('Janko Hauser','jhauser@zscout.de'),
118 'Nathan' : ('Nathaniel Gray','n8gray@caltech.edu'),
118 'Nathan' : ('Nathaniel Gray','n8gray@caltech.edu'),
119 'Ville' : ('Ville Vainio','vivainio@gmail.com'),
119 'Ville' : ('Ville Vainio','vivainio@gmail.com'),
120 'Brian' : ('Brian E Granger', 'ellisonbg@gmail.com'),
120 'Brian' : ('Brian E Granger', 'ellisonbg@gmail.com'),
121 'Min' : ('Min Ragan-Kelley', 'benjaminrk@gmail.com'),
121 'Min' : ('Min Ragan-Kelley', 'benjaminrk@gmail.com'),
122 'Thomas' : ('Thomas A. Kluyver', 'takowl@gmail.com'),
122 'Thomas' : ('Thomas A. Kluyver', 'takowl@gmail.com'),
123 'Jorgen' : ('Jorgen Stenarson', 'jorgen.stenarson@bostream.nu'),
123 'Jorgen' : ('Jorgen Stenarson', 'jorgen.stenarson@bostream.nu'),
124 'Matthias' : ('Matthias Bussonnier', 'bussonniermatthias@gmail.com'),
124 'Matthias' : ('Matthias Bussonnier', 'bussonniermatthias@gmail.com'),
125 }
125 }
126
126
127 author = 'The IPython Development Team'
127 author = 'The IPython Development Team'
128
128
129 author_email = 'ipython-dev@scipy.org'
129 author_email = 'ipython-dev@scipy.org'
130
130
131 url = 'http://ipython.org'
131 url = 'http://ipython.org'
132
132
133 download_url = 'https://github.com/ipython/ipython/downloads'
133 download_url = 'https://github.com/ipython/ipython/downloads'
134
134
135 platforms = ['Linux','Mac OSX','Windows XP/Vista/7/8']
135 platforms = ['Linux','Mac OSX','Windows XP/Vista/7/8']
136
136
137 keywords = ['Interactive','Interpreter','Shell','Parallel','Distributed',
137 keywords = ['Interactive','Interpreter','Shell','Parallel','Distributed',
138 'Web-based computing', 'Qt console', 'Embedding']
138 'Web-based computing', 'Qt console', 'Embedding']
139
139
140 classifiers = [
140 classifiers = [
141 'Intended Audience :: Developers',
141 'Intended Audience :: Developers',
142 'Intended Audience :: Science/Research',
142 'Intended Audience :: Science/Research',
143 'License :: OSI Approved :: BSD License',
143 'License :: OSI Approved :: BSD License',
144 'Programming Language :: Python',
144 'Programming Language :: Python',
145 'Programming Language :: Python :: 2',
145 'Programming Language :: Python :: 2',
146 'Programming Language :: Python :: 2.7',
146 'Programming Language :: Python :: 2.7',
147 'Programming Language :: Python :: 3',
147 'Programming Language :: Python :: 3',
148 'Topic :: System :: Distributed Computing',
148 'Topic :: System :: Distributed Computing',
149 'Topic :: System :: Shells'
149 'Topic :: System :: Shells'
150 ]
150 ]
@@ -1,1066 +1,1095 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.1.
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:
129 .. _wire_protocol:
130
130
131 The Wire Protocol
131 The Wire Protocol
132 =================
132 =================
133
133
134
134
135 This message format exists at a high level,
135 This message format exists at a high level,
136 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.
137 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.
138
138
139 .. note::
139 .. note::
140
140
141 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.
142 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
143 in the :class:`IPython.kernel.zmq.session.Session` object.
143 in the :class:`IPython.kernel.zmq.session.Session` object.
144
144
145 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:
146
146
147 .. sourcecode:: python
147 .. sourcecode:: python
148
148
149 [
149 [
150 b'u-u-i-d', # zmq identity(ies)
150 b'u-u-i-d', # zmq identity(ies)
151 b'<IDS|MSG>', # delimiter
151 b'<IDS|MSG>', # delimiter
152 b'baddad42', # HMAC signature
152 b'baddad42', # HMAC signature
153 b'{header}', # serialized header dict
153 b'{header}', # serialized header dict
154 b'{parent_header}', # serialized parent header dict
154 b'{parent_header}', # serialized parent header dict
155 b'{metadata}', # serialized metadata dict
155 b'{metadata}', # serialized metadata dict
156 b'{content}, # serialized content dict
156 b'{content}, # serialized content dict
157 b'blob', # extra raw data buffer(s)
157 b'blob', # extra raw data buffer(s)
158 ...
158 ...
159 ]
159 ]
160
160
161 The front of the message is the ZeroMQ routing prefix,
161 The front of the message is the ZeroMQ routing prefix,
162 which can be zero or more socket identities.
162 which can be zero or more socket identities.
163 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>``.
164 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,
165 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``.
166
166
167 .. note::
167 .. note::
168
168
169 In most cases, the IOPub topics are irrelevant and completely ignored,
169 In most cases, the IOPub topics are irrelevant and completely ignored,
170 because frontends just subscribe to all topics.
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,
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``
172 and possibly extra information about the message, e.g. ``execute_result`` or ``stream.stdout``
173
173
174 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.
175 If authentication is disabled, this should be an empty string.
175 If authentication is disabled, this should be an empty string.
176 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.
177
177
178 .. _HMAC: http://en.wikipedia.org/wiki/HMAC
178 .. _HMAC: http://en.wikipedia.org/wiki/HMAC
179
179
180 .. note::
180 .. note::
181
181
182 To disable authentication and signature checking,
182 To disable authentication and signature checking,
183 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.
184
184
185 The signature is the HMAC hex digest of the concatenation of:
185 The signature is the HMAC hex digest of the concatenation of:
186
186
187 - A shared key (typically the ``key`` field of a connection file)
187 - A shared key (typically the ``key`` field of a connection file)
188 - The serialized header dict
188 - The serialized header dict
189 - The serialized parent header dict
189 - The serialized parent header dict
190 - The serialized metadata dict
190 - The serialized metadata dict
191 - The serialized content dict
191 - The serialized content dict
192
192
193 In Python, this is implemented via:
193 In Python, this is implemented via:
194
194
195 .. sourcecode:: python
195 .. sourcecode:: python
196
196
197 # once:
197 # once:
198 digester = HMAC(key, digestmod=hashlib.sha256)
198 digester = HMAC(key, digestmod=hashlib.sha256)
199
199
200 # for each message
200 # for each message
201 d = digester.copy()
201 d = digester.copy()
202 for serialized_dict in (header, parent, metadata, content):
202 for serialized_dict in (header, parent, metadata, content):
203 d.update(serialized_dict)
203 d.update(serialized_dict)
204 signature = d.hexdigest()
204 signature = d.hexdigest()
205
205
206 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.
207 The four dictionaries that compose a message are serialized separately,
207 The four dictionaries that compose a message are serialized separately,
208 in the order of header, parent header, metadata, and content.
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.
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
210 The default and most common serialization is JSON, but msgpack and pickle
211 are common alternatives.
211 are common alternatives.
212
212
213 After the serialized dicts are zero to many raw data buffers,
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).
214 which can be used by message types that support binary data (mainly apply and data_pub).
215
215
216
216
217 Python functional API
217 Python functional API
218 =====================
218 =====================
219
219
220 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
221 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
222 take arguments in this manner and automatically construct the necessary dict
222 take arguments in this manner and automatically construct the necessary dict
223 for sending.
223 for sending.
224
224
225 In addition, the Python implementation of the message specification extends
225 In addition, the Python implementation of the message specification extends
226 messages upon deserialization to the following form for convenience::
226 messages upon deserialization to the following form for convenience::
227
227
228 {
228 {
229 'header' : dict,
229 'header' : dict,
230 # 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,
231 # but the Python implementation copies them to the top level.
231 # but the Python implementation copies them to the top level.
232 'msg_id' : uuid,
232 'msg_id' : uuid,
233 'msg_type' : str,
233 'msg_type' : str,
234 'parent_header' : dict,
234 'parent_header' : dict,
235 'content' : dict,
235 'content' : dict,
236 'metadata' : dict,
236 'metadata' : dict,
237 }
237 }
238
238
239 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
240 extended structure.
240 extended structure.
241
241
242
242
243 Messages on the shell ROUTER/DEALER sockets
243 Messages on the shell ROUTER/DEALER sockets
244 ===========================================
244 ===========================================
245
245
246 .. _execute:
246 .. _execute:
247
247
248 Execute
248 Execute
249 -------
249 -------
250
250
251 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
252 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
253 separate from the kernel's own internal code and variables).
253 separate from the kernel's own internal code and variables).
254
254
255 Message type: ``execute_request``::
255 Message type: ``execute_request``::
256
256
257 content = {
257 content = {
258 # 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.
259 'code' : str,
259 'code' : str,
260
260
261 # A boolean flag which, if True, signals the kernel to execute
261 # A boolean flag which, if True, signals the kernel to execute
262 # this code as quietly as possible.
262 # this code as quietly as possible.
263 # silent=True forces store_history to be False,
263 # silent=True forces store_history to be False,
264 # and will *not*:
264 # and will *not*:
265 # - broadcast output on the IOPUB channel
265 # - broadcast output on the IOPUB channel
266 # - have an execute_result
266 # - have an execute_result
267 # The default is False.
267 # The default is False.
268 'silent' : bool,
268 'silent' : bool,
269
269
270 # 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
271 # 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
272 # is forced to be False.
272 # is forced to be False.
273 'store_history' : bool,
273 'store_history' : bool,
274
274
275 # A dict mapping names to expressions to be evaluated in the
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.
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.
277 # See the display_data content for the structure of the representation data.
278 'user_expressions' : dict,
278 'user_expressions' : dict,
279
279
280 # Some frontends do not support stdin requests.
280 # Some frontends do not support stdin requests.
281 # 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,
282 # a StdinNotImplementedError will be raised.
282 # a StdinNotImplementedError will be raised.
283 'allow_stdin' : True,
283 'allow_stdin' : True,
284 }
284 }
285
285
286 .. versionchanged:: 5.0
286 .. versionchanged:: 5.0
287
287
288 ``user_variables`` removed, because it is redundant with user_expressions.
288 ``user_variables`` removed, because it is redundant with user_expressions.
289
289
290 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.
291
291
292 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
293 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
294 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
295 status, path information, and even more esoteric uses like remote instrument
295 status, path information, and even more esoteric uses like remote instrument
296 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
297 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
298 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
299 frontends to display different prompts while interacting with the same kernel.
299 frontends to display different prompts while interacting with the same kernel.
300 ``user_expressions`` can be used to retrieve this information.
300 ``user_expressions`` can be used to retrieve this information.
301
301
302 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
303 only that key containing a standard error message, of the form::
303 only that key containing a standard error message, of the form::
304
304
305 {
305 {
306 'status' : 'error',
306 'status' : 'error',
307 'ename' : 'NameError',
307 'ename' : 'NameError',
308 'evalue' : 'foo',
308 'evalue' : 'foo',
309 'traceback' : ...
309 'traceback' : ...
310 }
310 }
311
311
312 .. Note::
312 .. Note::
313
313
314 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
315 displaying input prompts, frontends may make an execution request with an
315 displaying input prompts, frontends may make an execution request with an
316 empty code string and ``silent=True``.
316 empty code string and ``silent=True``.
317
317
318 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,
319 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
320 the outcome. See :ref:`below <execution_results>` for the possible return
320 the outcome. See :ref:`below <execution_results>` for the possible return
321 codes and associated data.
321 codes and associated data.
322
322
323 .. seealso::
323 .. seealso::
324
324
325 :ref:`execution_semantics`
325 :ref:`execution_semantics`
326
326
327 .. _execution_counter:
327 .. _execution_counter:
328
328
329 Execution counter (prompt number)
329 Execution counter (prompt number)
330 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
330 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
331
331
332 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
333 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
334 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
335 ``execution_count`` field of all ``execute_reply`` and ``execute_input`` messages.
335 ``execution_count`` field of all ``execute_reply`` and ``execute_input`` messages.
336
336
337 .. _execution_results:
337 .. _execution_results:
338
338
339 Execution results
339 Execution results
340 ~~~~~~~~~~~~~~~~~
340 ~~~~~~~~~~~~~~~~~
341
341
342 Message type: ``execute_reply``::
342 Message type: ``execute_reply``::
343
343
344 content = {
344 content = {
345 # One of: 'ok' OR 'error' OR 'abort'
345 # One of: 'ok' OR 'error' OR 'abort'
346 'status' : str,
346 'status' : str,
347
347
348 # 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
349 # stores history. This will typically be used by clients to display
349 # stores history. This will typically be used by clients to display
350 # 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
351 # be the current value of the counter in the kernel.
351 # be the current value of the counter in the kernel.
352 'execution_count' : int,
352 'execution_count' : int,
353 }
353 }
354
354
355 When status is 'ok', the following extra fields are present::
355 When status is 'ok', the following extra fields are present::
356
356
357 {
357 {
358 # 'payload' will be a list of payload dicts.
358 # 'payload' will be a list of payload dicts.
359 # 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
360 # 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
361 # 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
362 # action on it as needed.
362 # action on it as needed.
363 # 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,
364 # which is a string classifying the payload (e.g. 'pager').
364 # which is a string classifying the payload (e.g. 'pager').
365 'payload' : list(dict),
365 'payload' : list(dict),
366
366
367 # Results for the user_expressions.
367 # Results for the user_expressions.
368 'user_expressions' : dict,
368 'user_expressions' : dict,
369 }
369 }
370
370
371 .. versionchanged:: 5.0
371 .. versionchanged:: 5.0
372
372
373 ``user_variables`` is removed, use user_expressions instead.
373 ``user_variables`` is removed, use user_expressions instead.
374
374
375 .. admonition:: Execution payloads
375 .. admonition:: Execution payloads
376
376
377 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
378 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
379 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
380 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
381 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
382 has an API for this in the PayloadManager::
382 has an API for this in the PayloadManager::
383
383
384 ip.payload_manager.write_payload(payload_dict)
384 ip.payload_manager.write_payload(payload_dict)
385
385
386 which appends a dictionary to the list of payloads.
386 which appends a dictionary to the list of payloads.
387
387
388 The payload API is not yet stabilized,
388 The payload API is not yet stabilized,
389 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.
390 In such cases, the payload list should always be empty.
390 In such cases, the payload list should always be empty.
391
391
392
392
393 When status is 'error', the following extra fields are present::
393 When status is 'error', the following extra fields are present::
394
394
395 {
395 {
396 'ename' : str, # Exception name, as a string
396 'ename' : str, # Exception name, as a string
397 'evalue' : str, # Exception value, as a string
397 'evalue' : str, # Exception value, as a string
398
398
399 # 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
400 # 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
401 # controls exception level of detail statefully. But eventually we'll
401 # controls exception level of detail statefully. But eventually we'll
402 # 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
403 # packed into the traceback object, with clients deciding how little or
403 # packed into the traceback object, with clients deciding how little or
404 # 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
405 # of strings, since that requires only minimal changes to ultratb as
405 # of strings, since that requires only minimal changes to ultratb as
406 # written.
406 # written.
407 'traceback' : list,
407 'traceback' : list,
408 }
408 }
409
409
410
410
411 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
412 happens when the kernel was interrupted by a signal.
412 happens when the kernel was interrupted by a signal.
413
413
414 .. _msging_inspection:
414 .. _msging_inspection:
415
415
416 Introspection
416 Introspection
417 -------------
417 -------------
418
418
419 Code can be inspected to show useful information to the user.
419 Code can be inspected to show useful information to the user.
420 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.
421
421
422 Message type: ``inspect_request``::
422 Message type: ``inspect_request``::
423
423
424 content = {
424 content = {
425 # The code context in which introspection is requested
425 # The code context in which introspection is requested
426 # this may be up to an entire multiline cell.
426 # this may be up to an entire multiline cell.
427 'code' : str,
427 'code' : str,
428
428
429 # 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
430 'cursor_pos' : int,
430 'cursor_pos' : int,
431
431
432 # 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
433 # 'x?' at the prompt, 1 is equivalent to 'x??'.
433 # 'x?' at the prompt, 1 is equivalent to 'x??'.
434 # 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
435 # if available.
435 # if available.
436 'detail_level' : 0 or 1,
436 'detail_level' : 0 or 1,
437 }
437 }
438
438
439 .. versionchanged:: 5.0
439 .. versionchanged:: 5.0
440
440
441 ``object_info_request`` renamed to ``inspect_request``.
441 ``object_info_request`` renamed to ``inspect_request``.
442
442
443 .. versionchanged:: 5.0
443 .. versionchanged:: 5.0
444
444
445 ``name`` key replaced with ``code`` and ``cursor_pos``,
445 ``name`` key replaced with ``code`` and ``cursor_pos``,
446 moving the lexing responsibility to the kernel.
446 moving the lexing responsibility to the kernel.
447
447
448 The reply is a mime-bundle, like a `display_data`_ message,
448 The reply is a mime-bundle, like a `display_data`_ message,
449 which should be a formatted representation of information about the context.
449 which should be a formatted representation of information about the context.
450 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.
451
451
452 Message type: ``inspect_reply``::
452 Message type: ``inspect_reply``::
453
453
454 content = {
454 content = {
455 # '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.
456 'status' : 'ok',
456 'status' : 'ok',
457
457
458 # data can be empty if nothing is found
458 # data can be empty if nothing is found
459 'data' : dict,
459 'data' : dict,
460 'metadata' : dict,
460 'metadata' : dict,
461 }
461 }
462
462
463 .. versionchanged:: 5.0
463 .. versionchanged:: 5.0
464
464
465 ``object_info_reply`` renamed to ``inspect_reply``.
465 ``object_info_reply`` renamed to ``inspect_reply``.
466
466
467 .. versionchanged:: 5.0
467 .. versionchanged:: 5.0
468
468
469 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.
470
470
471 .. _msging_completion:
471 .. _msging_completion:
472
472
473 Completion
473 Completion
474 ----------
474 ----------
475
475
476 Message type: ``complete_request``::
476 Message type: ``complete_request``::
477
477
478 content = {
478 content = {
479 # The code context in which completion is requested
479 # The code context in which completion is requested
480 # this may be up to an entire multiline cell, such as
480 # this may be up to an entire multiline cell, such as
481 # 'foo = a.isal'
481 # 'foo = a.isal'
482 'code' : str,
482 'code' : str,
483
483
484 # 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
485 'cursor_pos' : int,
485 'cursor_pos' : int,
486 }
486 }
487
487
488 .. versionchanged:: 5.0
488 .. versionchanged:: 5.0
489
489
490 ``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.
491 Lexing is up to the kernel.
491 Lexing is up to the kernel.
492
492
493
493
494 Message type: ``complete_reply``::
494 Message type: ``complete_reply``::
495
495
496 content = {
496 content = {
497 # The list of all matches to the completion request, such as
497 # The list of all matches to the completion request, such as
498 # ['a.isalnum', 'a.isalpha'] for the above example.
498 # ['a.isalnum', 'a.isalpha'] for the above example.
499 'matches' : list,
499 'matches' : list,
500
500
501 # 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.
502 # 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.
503 'cursor_start' : int,
503 'cursor_start' : int,
504 'cursor_end' : int,
504 'cursor_end' : int,
505
505
506 # 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.
507 'metadata' : dict,
507 'metadata' : dict,
508
508
509 # 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,
510 # 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
511 # in other messages.
511 # in other messages.
512 'status' : 'ok'
512 'status' : 'ok'
513 }
513 }
514
514
515 .. versionchanged:: 5.0
515 .. versionchanged:: 5.0
516
516
517 - ``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``.
518 - ``metadata`` is added for extended information.
518 - ``metadata`` is added for extended information.
519
519
520 .. _msging_history:
520 .. _msging_history:
521
521
522 History
522 History
523 -------
523 -------
524
524
525 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
526 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
527 request it from the kernel when needed.
527 request it from the kernel when needed.
528
528
529 Message type: ``history_request``::
529 Message type: ``history_request``::
530
530
531 content = {
531 content = {
532
532
533 # If True, also return output history in the resulting dict.
533 # If True, also return output history in the resulting dict.
534 'output' : bool,
534 'output' : bool,
535
535
536 # If True, return the raw input history, else the transformed input.
536 # If True, return the raw input history, else the transformed input.
537 'raw' : bool,
537 'raw' : bool,
538
538
539 # So far, this can be 'range', 'tail' or 'search'.
539 # So far, this can be 'range', 'tail' or 'search'.
540 'hist_access_type' : str,
540 'hist_access_type' : str,
541
541
542 # 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
543 # 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
544 # the current session.
544 # the current session.
545 'session' : int,
545 'session' : int,
546 # start and stop are line numbers within that session.
546 # start and stop are line numbers within that session.
547 'start' : int,
547 'start' : int,
548 'stop' : int,
548 'stop' : int,
549
549
550 # 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.
551 'n' : int,
551 'n' : int,
552
552
553 # 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
554 # pattern (with * and ? as wildcards).
554 # pattern (with * and ? as wildcards).
555 'pattern' : str,
555 'pattern' : str,
556
556
557 # 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
558 # include duplicated history. Default is false.
558 # include duplicated history. Default is false.
559 'unique' : bool,
559 'unique' : bool,
560
560
561 }
561 }
562
562
563 .. versionadded:: 4.0
563 .. versionadded:: 4.0
564 The key ``unique`` for ``history_request``.
564 The key ``unique`` for ``history_request``.
565
565
566 Message type: ``history_reply``::
566 Message type: ``history_reply``::
567
567
568 content = {
568 content = {
569 # A list of 3 tuples, either:
569 # A list of 3 tuples, either:
570 # (session, line_number, input) or
570 # (session, line_number, input) or
571 # (session, line_number, (input, output)),
571 # (session, line_number, (input, output)),
572 # depending on whether output was False or True, respectively.
572 # depending on whether output was False or True, respectively.
573 'history' : list,
573 'history' : list,
574 }
574 }
575
575
576 .. _msging_is_complete:
577
578 Code completeness
579 -----------------
580
581 .. versionadded:: 5.1
582
583 When the user enters a line in a console style interface, the console must
584 decide whether to immediately execute the current code, or whether to show a
585 continuation prompt for further input. For instance, in Python ``a = 5`` would
586 be executed immediately, while ``for i in range(5):`` would expect further input.
587
588 Frontends may have ways to override this, forcing the code to be sent for
589 execution or forcing a continuation prompt. If the kernel does not reply promptly,
590 the frontend will probably default to sending the code to be executed.
591
592 Message type: ``is_complete_request``::
593
594 content = {
595 # The code entered so far as a multiline string
596 'code' : str,
597 }
598
599 Message type: ``complete_reply``::
600
601 content = {
602 # True if the code is ready to execute, False if not
603 'complete' : bool,
604 }
576
605
577 Connect
606 Connect
578 -------
607 -------
579
608
580 When a client connects to the request/reply socket of the kernel, it can issue
609 When a client connects to the request/reply socket of the kernel, it can issue
581 a connect request to get basic information about the kernel, such as the ports
610 a connect request to get basic information about the kernel, such as the ports
582 the other ZeroMQ sockets are listening on. This allows clients to only have
611 the other ZeroMQ sockets are listening on. This allows clients to only have
583 to know about a single port (the shell channel) to connect to a kernel.
612 to know about a single port (the shell channel) to connect to a kernel.
584
613
585 Message type: ``connect_request``::
614 Message type: ``connect_request``::
586
615
587 content = {
616 content = {
588 }
617 }
589
618
590 Message type: ``connect_reply``::
619 Message type: ``connect_reply``::
591
620
592 content = {
621 content = {
593 'shell_port' : int, # The port the shell ROUTER socket is listening on.
622 'shell_port' : int, # The port the shell ROUTER socket is listening on.
594 'iopub_port' : int, # The port the PUB socket is listening on.
623 'iopub_port' : int, # The port the PUB socket is listening on.
595 'stdin_port' : int, # The port the stdin ROUTER socket is listening on.
624 'stdin_port' : int, # The port the stdin ROUTER socket is listening on.
596 'hb_port' : int, # The port the heartbeat socket is listening on.
625 'hb_port' : int, # The port the heartbeat socket is listening on.
597 }
626 }
598
627
599 .. _msging_kernel_info:
628 .. _msging_kernel_info:
600
629
601 Kernel info
630 Kernel info
602 -----------
631 -----------
603
632
604 If a client needs to know information about the kernel, it can
633 If a client needs to know information about the kernel, it can
605 make a request of the kernel's information.
634 make a request of the kernel's information.
606 This message can be used to fetch core information of the
635 This message can be used to fetch core information of the
607 kernel, including language (e.g., Python), language version number and
636 kernel, including language (e.g., Python), language version number and
608 IPython version number, and the IPython message spec version number.
637 IPython version number, and the IPython message spec version number.
609
638
610 Message type: ``kernel_info_request``::
639 Message type: ``kernel_info_request``::
611
640
612 content = {
641 content = {
613 }
642 }
614
643
615 Message type: ``kernel_info_reply``::
644 Message type: ``kernel_info_reply``::
616
645
617 content = {
646 content = {
618 # Version of messaging protocol.
647 # Version of messaging protocol.
619 # The first integer indicates major version. It is incremented when
648 # The first integer indicates major version. It is incremented when
620 # there is any backward incompatible change.
649 # there is any backward incompatible change.
621 # The second integer indicates minor version. It is incremented when
650 # The second integer indicates minor version. It is incremented when
622 # there is any backward compatible change.
651 # there is any backward compatible change.
623 'protocol_version': 'X.Y.Z',
652 'protocol_version': 'X.Y.Z',
624
653
625 # The kernel implementation name
654 # The kernel implementation name
626 # (e.g. 'ipython' for the IPython kernel)
655 # (e.g. 'ipython' for the IPython kernel)
627 'implementation': str,
656 'implementation': str,
628
657
629 # Implementation version number.
658 # Implementation version number.
630 # The version number of the kernel's implementation
659 # The version number of the kernel's implementation
631 # (e.g. IPython.__version__ for the IPython kernel)
660 # (e.g. IPython.__version__ for the IPython kernel)
632 'implementation_version': 'X.Y.Z',
661 'implementation_version': 'X.Y.Z',
633
662
634 # Programming language in which kernel is implemented.
663 # Programming language in which kernel is implemented.
635 # Kernel included in IPython returns 'python'.
664 # Kernel included in IPython returns 'python'.
636 'language': str,
665 'language': str,
637
666
638 # Language version number.
667 # Language version number.
639 # It is Python version number (e.g., '2.7.3') for the kernel
668 # It is Python version number (e.g., '2.7.3') for the kernel
640 # included in IPython.
669 # included in IPython.
641 'language_version': 'X.Y.Z',
670 'language_version': 'X.Y.Z',
642
671
643 # A banner of information about the kernel,
672 # A banner of information about the kernel,
644 # which may be desplayed in console environments.
673 # which may be desplayed in console environments.
645 'banner' : str,
674 'banner' : str,
646 }
675 }
647
676
648 .. versionchanged:: 5.0
677 .. versionchanged:: 5.0
649
678
650 Versions changed from lists of integers to strings.
679 Versions changed from lists of integers to strings.
651
680
652 .. versionchanged:: 5.0
681 .. versionchanged:: 5.0
653
682
654 ``ipython_version`` is removed.
683 ``ipython_version`` is removed.
655
684
656 .. versionchanged:: 5.0
685 .. versionchanged:: 5.0
657
686
658 ``implementation``, ``implementation_version``, and ``banner`` keys are added.
687 ``implementation``, ``implementation_version``, and ``banner`` keys are added.
659
688
660 .. _msging_shutdown:
689 .. _msging_shutdown:
661
690
662 Kernel shutdown
691 Kernel shutdown
663 ---------------
692 ---------------
664
693
665 The clients can request the kernel to shut itself down; this is used in
694 The clients can request the kernel to shut itself down; this is used in
666 multiple cases:
695 multiple cases:
667
696
668 - when the user chooses to close the client application via a menu or window
697 - when the user chooses to close the client application via a menu or window
669 control.
698 control.
670 - when the user types 'exit' or 'quit' (or their uppercase magic equivalents).
699 - when the user types 'exit' or 'quit' (or their uppercase magic equivalents).
671 - when the user chooses a GUI method (like the 'Ctrl-C' shortcut in the
700 - when the user chooses a GUI method (like the 'Ctrl-C' shortcut in the
672 IPythonQt client) to force a kernel restart to get a clean kernel without
701 IPythonQt client) to force a kernel restart to get a clean kernel without
673 losing client-side state like history or inlined figures.
702 losing client-side state like history or inlined figures.
674
703
675 The client sends a shutdown request to the kernel, and once it receives the
704 The client sends a shutdown request to the kernel, and once it receives the
676 reply message (which is otherwise empty), it can assume that the kernel has
705 reply message (which is otherwise empty), it can assume that the kernel has
677 completed shutdown safely.
706 completed shutdown safely.
678
707
679 Upon their own shutdown, client applications will typically execute a last
708 Upon their own shutdown, client applications will typically execute a last
680 minute sanity check and forcefully terminate any kernel that is still alive, to
709 minute sanity check and forcefully terminate any kernel that is still alive, to
681 avoid leaving stray processes in the user's machine.
710 avoid leaving stray processes in the user's machine.
682
711
683 Message type: ``shutdown_request``::
712 Message type: ``shutdown_request``::
684
713
685 content = {
714 content = {
686 'restart' : bool # whether the shutdown is final, or precedes a restart
715 'restart' : bool # whether the shutdown is final, or precedes a restart
687 }
716 }
688
717
689 Message type: ``shutdown_reply``::
718 Message type: ``shutdown_reply``::
690
719
691 content = {
720 content = {
692 'restart' : bool # whether the shutdown is final, or precedes a restart
721 'restart' : bool # whether the shutdown is final, or precedes a restart
693 }
722 }
694
723
695 .. Note::
724 .. Note::
696
725
697 When the clients detect a dead kernel thanks to inactivity on the heartbeat
726 When the clients detect a dead kernel thanks to inactivity on the heartbeat
698 socket, they simply send a forceful process termination signal, since a dead
727 socket, they simply send a forceful process termination signal, since a dead
699 process is unlikely to respond in any useful way to messages.
728 process is unlikely to respond in any useful way to messages.
700
729
701
730
702 Messages on the PUB/SUB socket
731 Messages on the PUB/SUB socket
703 ==============================
732 ==============================
704
733
705 Streams (stdout, stderr, etc)
734 Streams (stdout, stderr, etc)
706 ------------------------------
735 ------------------------------
707
736
708 Message type: ``stream``::
737 Message type: ``stream``::
709
738
710 content = {
739 content = {
711 # The name of the stream is one of 'stdout', 'stderr'
740 # The name of the stream is one of 'stdout', 'stderr'
712 'name' : str,
741 'name' : str,
713
742
714 # The data is an arbitrary string to be written to that stream
743 # The data is an arbitrary string to be written to that stream
715 'data' : str,
744 'data' : str,
716 }
745 }
717
746
718 Display Data
747 Display Data
719 ------------
748 ------------
720
749
721 This type of message is used to bring back data that should be displayed (text,
750 This type of message is used to bring back data that should be displayed (text,
722 html, svg, etc.) in the frontends. This data is published to all frontends.
751 html, svg, etc.) in the frontends. This data is published to all frontends.
723 Each message can have multiple representations of the data; it is up to the
752 Each message can have multiple representations of the data; it is up to the
724 frontend to decide which to use and how. A single message should contain all
753 frontend to decide which to use and how. A single message should contain all
725 possible representations of the same information. Each representation should
754 possible representations of the same information. Each representation should
726 be a JSON'able data structure, and should be a valid MIME type.
755 be a JSON'able data structure, and should be a valid MIME type.
727
756
728 Some questions remain about this design:
757 Some questions remain about this design:
729
758
730 * Do we use this message type for execute_result/displayhook? Probably not, because
759 * Do we use this message type for execute_result/displayhook? Probably not, because
731 the displayhook also has to handle the Out prompt display. On the other hand
760 the displayhook also has to handle the Out prompt display. On the other hand
732 we could put that information into the metadata section.
761 we could put that information into the metadata section.
733
762
734 .. _display_data:
763 .. _display_data:
735
764
736 Message type: ``display_data``::
765 Message type: ``display_data``::
737
766
738 content = {
767 content = {
739
768
740 # Who create the data
769 # Who create the data
741 'source' : str,
770 'source' : str,
742
771
743 # The data dict contains key/value pairs, where the keys are MIME
772 # The data dict contains key/value pairs, where the keys are MIME
744 # types and the values are the raw data of the representation in that
773 # types and the values are the raw data of the representation in that
745 # format.
774 # format.
746 'data' : dict,
775 'data' : dict,
747
776
748 # Any metadata that describes the data
777 # Any metadata that describes the data
749 'metadata' : dict
778 'metadata' : dict
750 }
779 }
751
780
752
781
753 The ``metadata`` contains any metadata that describes the output.
782 The ``metadata`` contains any metadata that describes the output.
754 Global keys are assumed to apply to the output as a whole.
783 Global keys are assumed to apply to the output as a whole.
755 The ``metadata`` dict can also contain mime-type keys, which will be sub-dictionaries,
784 The ``metadata`` dict can also contain mime-type keys, which will be sub-dictionaries,
756 which are interpreted as applying only to output of that type.
785 which are interpreted as applying only to output of that type.
757 Third parties should put any data they write into a single dict
786 Third parties should put any data they write into a single dict
758 with a reasonably unique name to avoid conflicts.
787 with a reasonably unique name to avoid conflicts.
759
788
760 The only metadata keys currently defined in IPython are the width and height
789 The only metadata keys currently defined in IPython are the width and height
761 of images::
790 of images::
762
791
763 metadata = {
792 metadata = {
764 'image/png' : {
793 'image/png' : {
765 'width': 640,
794 'width': 640,
766 'height': 480
795 'height': 480
767 }
796 }
768 }
797 }
769
798
770
799
771 .. versionchanged:: 5.0
800 .. versionchanged:: 5.0
772
801
773 `application/json` data should be unpacked JSON data,
802 `application/json` data should be unpacked JSON data,
774 not double-serialized as a JSON string.
803 not double-serialized as a JSON string.
775
804
776
805
777 Raw Data Publication
806 Raw Data Publication
778 --------------------
807 --------------------
779
808
780 ``display_data`` lets you publish *representations* of data, such as images and html.
809 ``display_data`` lets you publish *representations* of data, such as images and html.
781 This ``data_pub`` message lets you publish *actual raw data*, sent via message buffers.
810 This ``data_pub`` message lets you publish *actual raw data*, sent via message buffers.
782
811
783 data_pub messages are constructed via the :func:`IPython.lib.datapub.publish_data` function:
812 data_pub messages are constructed via the :func:`IPython.lib.datapub.publish_data` function:
784
813
785 .. sourcecode:: python
814 .. sourcecode:: python
786
815
787 from IPython.kernel.zmq.datapub import publish_data
816 from IPython.kernel.zmq.datapub import publish_data
788 ns = dict(x=my_array)
817 ns = dict(x=my_array)
789 publish_data(ns)
818 publish_data(ns)
790
819
791
820
792 Message type: ``data_pub``::
821 Message type: ``data_pub``::
793
822
794 content = {
823 content = {
795 # the keys of the data dict, after it has been unserialized
824 # the keys of the data dict, after it has been unserialized
796 'keys' : ['a', 'b']
825 'keys' : ['a', 'b']
797 }
826 }
798 # the namespace dict will be serialized in the message buffers,
827 # the namespace dict will be serialized in the message buffers,
799 # which will have a length of at least one
828 # which will have a length of at least one
800 buffers = [b'pdict', ...]
829 buffers = [b'pdict', ...]
801
830
802
831
803 The interpretation of a sequence of data_pub messages for a given parent request should be
832 The interpretation of a sequence of data_pub messages for a given parent request should be
804 to update a single namespace with subsequent results.
833 to update a single namespace with subsequent results.
805
834
806 .. note::
835 .. note::
807
836
808 No frontends directly handle data_pub messages at this time.
837 No frontends directly handle data_pub messages at this time.
809 It is currently only used by the client/engines in :mod:`IPython.parallel`,
838 It is currently only used by the client/engines in :mod:`IPython.parallel`,
810 where engines may publish *data* to the Client,
839 where engines may publish *data* to the Client,
811 of which the Client can then publish *representations* via ``display_data``
840 of which the Client can then publish *representations* via ``display_data``
812 to various frontends.
841 to various frontends.
813
842
814 Code inputs
843 Code inputs
815 -----------
844 -----------
816
845
817 To let all frontends know what code is being executed at any given time, these
846 To let all frontends know what code is being executed at any given time, these
818 messages contain a re-broadcast of the ``code`` portion of an
847 messages contain a re-broadcast of the ``code`` portion of an
819 :ref:`execute_request <execute>`, along with the :ref:`execution_count
848 :ref:`execute_request <execute>`, along with the :ref:`execution_count
820 <execution_counter>`.
849 <execution_counter>`.
821
850
822 Message type: ``execute_input``::
851 Message type: ``execute_input``::
823
852
824 content = {
853 content = {
825 'code' : str, # Source code to be executed, one or more lines
854 'code' : str, # Source code to be executed, one or more lines
826
855
827 # The counter for this execution is also provided so that clients can
856 # The counter for this execution is also provided so that clients can
828 # display it, since IPython automatically creates variables called _iN
857 # display it, since IPython automatically creates variables called _iN
829 # (for input prompt In[N]).
858 # (for input prompt In[N]).
830 'execution_count' : int
859 'execution_count' : int
831 }
860 }
832
861
833 .. versionchanged:: 5.0
862 .. versionchanged:: 5.0
834
863
835 ``pyin`` is renamed to ``execute_input``.
864 ``pyin`` is renamed to ``execute_input``.
836
865
837
866
838 Execution results
867 Execution results
839 -----------------
868 -----------------
840
869
841 Results of an execution are published as an ``execute_result``.
870 Results of an execution are published as an ``execute_result``.
842 These are identical to `display_data`_ messages, with the addition of an ``execution_count`` key.
871 These are identical to `display_data`_ messages, with the addition of an ``execution_count`` key.
843
872
844 Results can have multiple simultaneous formats depending on its
873 Results can have multiple simultaneous formats depending on its
845 configuration. A plain text representation should always be provided
874 configuration. A plain text representation should always be provided
846 in the ``text/plain`` mime-type. Frontends are free to display any or all of these
875 in the ``text/plain`` mime-type. Frontends are free to display any or all of these
847 according to its capabilities.
876 according to its capabilities.
848 Frontends should ignore mime-types they do not understand. The data itself is
877 Frontends should ignore mime-types they do not understand. The data itself is
849 any JSON object and depends on the format. It is often, but not always a string.
878 any JSON object and depends on the format. It is often, but not always a string.
850
879
851 Message type: ``execute_result``::
880 Message type: ``execute_result``::
852
881
853 content = {
882 content = {
854
883
855 # The counter for this execution is also provided so that clients can
884 # The counter for this execution is also provided so that clients can
856 # display it, since IPython automatically creates variables called _N
885 # display it, since IPython automatically creates variables called _N
857 # (for prompt N).
886 # (for prompt N).
858 'execution_count' : int,
887 'execution_count' : int,
859
888
860 # data and metadata are identical to a display_data message.
889 # data and metadata are identical to a display_data message.
861 # the object being displayed is that passed to the display hook,
890 # the object being displayed is that passed to the display hook,
862 # i.e. the *result* of the execution.
891 # i.e. the *result* of the execution.
863 'data' : dict,
892 'data' : dict,
864 'metadata' : dict,
893 'metadata' : dict,
865 }
894 }
866
895
867 Execution errors
896 Execution errors
868 ----------------
897 ----------------
869
898
870 When an error occurs during code execution
899 When an error occurs during code execution
871
900
872 Message type: ``error``::
901 Message type: ``error``::
873
902
874 content = {
903 content = {
875 # Similar content to the execute_reply messages for the 'error' case,
904 # Similar content to the execute_reply messages for the 'error' case,
876 # except the 'status' field is omitted.
905 # except the 'status' field is omitted.
877 }
906 }
878
907
879 .. versionchanged:: 5.0
908 .. versionchanged:: 5.0
880
909
881 ``pyerr`` renamed to ``error``
910 ``pyerr`` renamed to ``error``
882
911
883 Kernel status
912 Kernel status
884 -------------
913 -------------
885
914
886 This message type is used by frontends to monitor the status of the kernel.
915 This message type is used by frontends to monitor the status of the kernel.
887
916
888 Message type: ``status``::
917 Message type: ``status``::
889
918
890 content = {
919 content = {
891 # When the kernel starts to handle a message, it will enter the 'busy'
920 # When the kernel starts to handle a message, it will enter the 'busy'
892 # state and when it finishes, it will enter the 'idle' state.
921 # state and when it finishes, it will enter the 'idle' state.
893 # The kernel will publish state 'starting' exactly once at process startup.
922 # The kernel will publish state 'starting' exactly once at process startup.
894 execution_state : ('busy', 'idle', 'starting')
923 execution_state : ('busy', 'idle', 'starting')
895 }
924 }
896
925
897 .. versionchanged:: 5.0
926 .. versionchanged:: 5.0
898
927
899 Busy and idle messages should be sent before/after handling every message,
928 Busy and idle messages should be sent before/after handling every message,
900 not just execution.
929 not just execution.
901
930
902 Clear output
931 Clear output
903 ------------
932 ------------
904
933
905 This message type is used to clear the output that is visible on the frontend.
934 This message type is used to clear the output that is visible on the frontend.
906
935
907 Message type: ``clear_output``::
936 Message type: ``clear_output``::
908
937
909 content = {
938 content = {
910
939
911 # Wait to clear the output until new output is available. Clears the
940 # Wait to clear the output until new output is available. Clears the
912 # existing output immediately before the new output is displayed.
941 # existing output immediately before the new output is displayed.
913 # Useful for creating simple animations with minimal flickering.
942 # Useful for creating simple animations with minimal flickering.
914 'wait' : bool,
943 'wait' : bool,
915 }
944 }
916
945
917 .. versionchanged:: 4.1
946 .. versionchanged:: 4.1
918
947
919 ``stdout``, ``stderr``, and ``display`` boolean keys for selective clearing are removed,
948 ``stdout``, ``stderr``, and ``display`` boolean keys for selective clearing are removed,
920 and ``wait`` is added.
949 and ``wait`` is added.
921 The selective clearing keys are ignored in v4 and the default behavior remains the same,
950 The selective clearing keys are ignored in v4 and the default behavior remains the same,
922 so v4 clear_output messages will be safely handled by a v4.1 frontend.
951 so v4 clear_output messages will be safely handled by a v4.1 frontend.
923
952
924
953
925 Messages on the stdin ROUTER/DEALER sockets
954 Messages on the stdin ROUTER/DEALER sockets
926 ===========================================
955 ===========================================
927
956
928 This is a socket where the request/reply pattern goes in the opposite direction:
957 This is a socket where the request/reply pattern goes in the opposite direction:
929 from the kernel to a *single* frontend, and its purpose is to allow
958 from the kernel to a *single* frontend, and its purpose is to allow
930 ``raw_input`` and similar operations that read from ``sys.stdin`` on the kernel
959 ``raw_input`` and similar operations that read from ``sys.stdin`` on the kernel
931 to be fulfilled by the client. The request should be made to the frontend that
960 to be fulfilled by the client. The request should be made to the frontend that
932 made the execution request that prompted ``raw_input`` to be called. For now we
961 made the execution request that prompted ``raw_input`` to be called. For now we
933 will keep these messages as simple as possible, since they only mean to convey
962 will keep these messages as simple as possible, since they only mean to convey
934 the ``raw_input(prompt)`` call.
963 the ``raw_input(prompt)`` call.
935
964
936 Message type: ``input_request``::
965 Message type: ``input_request``::
937
966
938 content = {
967 content = {
939 # the text to show at the prompt
968 # the text to show at the prompt
940 'prompt' : str,
969 'prompt' : str,
941 # Is the request for a password?
970 # Is the request for a password?
942 # If so, the frontend shouldn't echo input.
971 # If so, the frontend shouldn't echo input.
943 'password' : bool
972 'password' : bool
944 }
973 }
945
974
946 Message type: ``input_reply``::
975 Message type: ``input_reply``::
947
976
948 content = { 'value' : str }
977 content = { 'value' : str }
949
978
950
979
951 When ``password`` is True, the frontend should not echo the input as it is entered.
980 When ``password`` is True, the frontend should not echo the input as it is entered.
952
981
953 .. versionchanged:: 5.0
982 .. versionchanged:: 5.0
954
983
955 ``password`` key added.
984 ``password`` key added.
956
985
957 .. note::
986 .. note::
958
987
959 The stdin socket of the client is required to have the same zmq IDENTITY
988 The stdin socket of the client is required to have the same zmq IDENTITY
960 as the client's shell socket.
989 as the client's shell socket.
961 Because of this, the ``input_request`` must be sent with the same IDENTITY
990 Because of this, the ``input_request`` must be sent with the same IDENTITY
962 routing prefix as the ``execute_reply`` in order for the frontend to receive
991 routing prefix as the ``execute_reply`` in order for the frontend to receive
963 the message.
992 the message.
964
993
965 .. note::
994 .. note::
966
995
967 We do not explicitly try to forward the raw ``sys.stdin`` object, because in
996 We do not explicitly try to forward the raw ``sys.stdin`` object, because in
968 practice the kernel should behave like an interactive program. When a
997 practice the kernel should behave like an interactive program. When a
969 program is opened on the console, the keyboard effectively takes over the
998 program is opened on the console, the keyboard effectively takes over the
970 ``stdin`` file descriptor, and it can't be used for raw reading anymore.
999 ``stdin`` file descriptor, and it can't be used for raw reading anymore.
971 Since the IPython kernel effectively behaves like a console program (albeit
1000 Since the IPython kernel effectively behaves like a console program (albeit
972 one whose "keyboard" is actually living in a separate process and
1001 one whose "keyboard" is actually living in a separate process and
973 transported over the zmq connection), raw ``stdin`` isn't expected to be
1002 transported over the zmq connection), raw ``stdin`` isn't expected to be
974 available.
1003 available.
975
1004
976 .. _kernel_heartbeat:
1005 .. _kernel_heartbeat:
977
1006
978 Heartbeat for kernels
1007 Heartbeat for kernels
979 =====================
1008 =====================
980
1009
981 Clients send ping messages on a REQ socket, which are echoed right back
1010 Clients send ping messages on a REQ socket, which are echoed right back
982 from the Kernel's REP socket. These are simple bytestrings, not full JSON messages described above.
1011 from the Kernel's REP socket. These are simple bytestrings, not full JSON messages described above.
983
1012
984
1013
985 Custom Messages
1014 Custom Messages
986 ===============
1015 ===============
987
1016
988 .. versionadded:: 4.1
1017 .. versionadded:: 4.1
989
1018
990 IPython 2.0 (msgspec v4.1) adds a messaging system for developers to add their own objects with Frontend
1019 IPython 2.0 (msgspec v4.1) adds a messaging system for developers to add their own objects with Frontend
991 and Kernel-side components, and allow them to communicate with each other.
1020 and Kernel-side components, and allow them to communicate with each other.
992 To do this, IPython adds a notion of a ``Comm``, which exists on both sides,
1021 To do this, IPython adds a notion of a ``Comm``, which exists on both sides,
993 and can communicate in either direction.
1022 and can communicate in either direction.
994
1023
995 These messages are fully symmetrical - both the Kernel and the Frontend can send each message,
1024 These messages are fully symmetrical - both the Kernel and the Frontend can send each message,
996 and no messages expect a reply.
1025 and no messages expect a reply.
997 The Kernel listens for these messages on the Shell channel,
1026 The Kernel listens for these messages on the Shell channel,
998 and the Frontend listens for them on the IOPub channel.
1027 and the Frontend listens for them on the IOPub channel.
999
1028
1000 Opening a Comm
1029 Opening a Comm
1001 --------------
1030 --------------
1002
1031
1003 Opening a Comm produces a ``comm_open`` message, to be sent to the other side::
1032 Opening a Comm produces a ``comm_open`` message, to be sent to the other side::
1004
1033
1005 {
1034 {
1006 'comm_id' : 'u-u-i-d',
1035 'comm_id' : 'u-u-i-d',
1007 'target_name' : 'my_comm',
1036 'target_name' : 'my_comm',
1008 'data' : {}
1037 'data' : {}
1009 }
1038 }
1010
1039
1011 Every Comm has an ID and a target name.
1040 Every Comm has an ID and a target name.
1012 The code handling the message on the receiving side is responsible for maintaining a mapping
1041 The code handling the message on the receiving side is responsible for maintaining a mapping
1013 of target_name keys to constructors.
1042 of target_name keys to constructors.
1014 After a ``comm_open`` message has been sent,
1043 After a ``comm_open`` message has been sent,
1015 there should be a corresponding Comm instance on both sides.
1044 there should be a corresponding Comm instance on both sides.
1016 The ``data`` key is always a dict and can be any extra JSON information used in initialization of the comm.
1045 The ``data`` key is always a dict and can be any extra JSON information used in initialization of the comm.
1017
1046
1018 If the ``target_name`` key is not found on the receiving side,
1047 If the ``target_name`` key is not found on the receiving side,
1019 then it should immediately reply with a ``comm_close`` message to avoid an inconsistent state.
1048 then it should immediately reply with a ``comm_close`` message to avoid an inconsistent state.
1020
1049
1021 Comm Messages
1050 Comm Messages
1022 -------------
1051 -------------
1023
1052
1024 Comm messages are one-way communications to update comm state,
1053 Comm messages are one-way communications to update comm state,
1025 used for synchronizing widget state, or simply requesting actions of a comm's counterpart.
1054 used for synchronizing widget state, or simply requesting actions of a comm's counterpart.
1026
1055
1027 Essentially, each comm pair defines their own message specification implemented inside the ``data`` dict.
1056 Essentially, each comm pair defines their own message specification implemented inside the ``data`` dict.
1028
1057
1029 There are no expected replies (of course, one side can send another ``comm_msg`` in reply).
1058 There are no expected replies (of course, one side can send another ``comm_msg`` in reply).
1030
1059
1031 Message type: ``comm_msg``::
1060 Message type: ``comm_msg``::
1032
1061
1033 {
1062 {
1034 'comm_id' : 'u-u-i-d',
1063 'comm_id' : 'u-u-i-d',
1035 'data' : {}
1064 'data' : {}
1036 }
1065 }
1037
1066
1038 Tearing Down Comms
1067 Tearing Down Comms
1039 ------------------
1068 ------------------
1040
1069
1041 Since comms live on both sides, when a comm is destroyed the other side must be notified.
1070 Since comms live on both sides, when a comm is destroyed the other side must be notified.
1042 This is done with a ``comm_close`` message.
1071 This is done with a ``comm_close`` message.
1043
1072
1044 Message type: ``comm_close``::
1073 Message type: ``comm_close``::
1045
1074
1046 {
1075 {
1047 'comm_id' : 'u-u-i-d',
1076 'comm_id' : 'u-u-i-d',
1048 'data' : {}
1077 'data' : {}
1049 }
1078 }
1050
1079
1051 Output Side Effects
1080 Output Side Effects
1052 -------------------
1081 -------------------
1053
1082
1054 Since comm messages can execute arbitrary user code,
1083 Since comm messages can execute arbitrary user code,
1055 handlers should set the parent header and publish status busy / idle,
1084 handlers should set the parent header and publish status busy / idle,
1056 just like an execute request.
1085 just like an execute request.
1057
1086
1058
1087
1059 To Do
1088 To Do
1060 =====
1089 =====
1061
1090
1062 Missing things include:
1091 Missing things include:
1063
1092
1064 * Important: finish thinking through the payload concept and API.
1093 * Important: finish thinking through the payload concept and API.
1065
1094
1066 .. include:: ../links.txt
1095 .. include:: ../links.txt
@@ -1,153 +1,164 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::
13 .. seealso::
14
14
15 `bash_kernel <https://github.com/takluyver/bash_kernel>`_
15 `bash_kernel <https://github.com/takluyver/bash_kernel>`_
16 A simple kernel for bash, written using this machinery
16 A simple kernel for bash, written using this machinery
17
17
18 Required steps
18 Required steps
19 --------------
19 --------------
20
20
21 Subclass :class:`IPython.kernel.zmq.kernelbase.Kernel`, and implement the
21 Subclass :class:`IPython.kernel.zmq.kernelbase.Kernel`, and implement the
22 following methods and attributes:
22 following methods and attributes:
23
23
24 .. class:: MyKernel
24 .. class:: MyKernel
25
25
26 .. attribute:: implementation
26 .. attribute:: implementation
27 implementation_version
27 implementation_version
28 language
28 language
29 language_version
29 language_version
30 banner
30 banner
31
31
32 Information for :ref:`msging_kernel_info` replies. 'Implementation' refers
32 Information for :ref:`msging_kernel_info` replies. 'Implementation' refers
33 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
34 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
35 UIs before the first prompt. All of these values are strings.
35 UIs before the first prompt. All of these values are strings.
36
36
37 .. 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)
38
38
39 Execute user code.
39 Execute user code.
40
40
41 :param str code: The code to be executed.
41 :param str code: The code to be executed.
42 :param bool silent: Whether to display output.
42 :param bool silent: Whether to display output.
43 :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
44 increase the execution count. If silent is True, this is implicitly
44 increase the execution count. If silent is True, this is implicitly
45 False.
45 False.
46 :param dict user_expressions: Mapping of names to expressions to evaluate
46 :param dict user_expressions: Mapping of names to expressions to evaluate
47 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.
48 :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
49 (e.g. for Python's :func:`raw_input`).
49 (e.g. for Python's :func:`raw_input`).
50
50
51 Your method should return a dict containing the fields described in
51 Your method should return a dict containing the fields described in
52 :ref:`execution_results`. To display output, it can send messages
52 :ref:`execution_results`. To display output, it can send messages
53 using :meth:`~IPython.kernel.zmq.kernelbase.Kernel.send_response`.
53 using :meth:`~IPython.kernel.zmq.kernelbase.Kernel.send_response`.
54 See :doc:`messaging` for details of the different message types.
54 See :doc:`messaging` for details of the different message types.
55
55
56 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::
57
57
58 if __name__ == '__main__':
58 if __name__ == '__main__':
59 from IPython.kernel.zmq.kernelapp import IPKernelApp
59 from IPython.kernel.zmq.kernelapp import IPKernelApp
60 IPKernelApp.launch_instance(kernel_class=MyKernel)
60 IPKernelApp.launch_instance(kernel_class=MyKernel)
61
61
62 Example
62 Example
63 -------
63 -------
64
64
65 ``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::
66
66
67 from IPython.kernel.zmq.kernelbase import Kernel
67 from IPython.kernel.zmq.kernelbase import Kernel
68
68
69 class EchoKernel(Kernel):
69 class EchoKernel(Kernel):
70 implementation = 'Echo'
70 implementation = 'Echo'
71 implementation_version = '1.0'
71 implementation_version = '1.0'
72 language = 'no-op'
72 language = 'no-op'
73 language_version = '0.1'
73 language_version = '0.1'
74 banner = "Echo kernel - as useful as a parrot"
74 banner = "Echo kernel - as useful as a parrot"
75
75
76 def do_execute(self, code, silent, store_history=True, user_expressions=None,
76 def do_execute(self, code, silent, store_history=True, user_expressions=None,
77 allow_stdin=False):
77 allow_stdin=False):
78 if not silent:
78 if not silent:
79 stream_content = {'name': 'stdout', 'data':code}
79 stream_content = {'name': 'stdout', 'data':code}
80 self.send_response(self.iopub_socket, 'stream', stream_content)
80 self.send_response(self.iopub_socket, 'stream', stream_content)
81
81
82 return {'status': 'ok',
82 return {'status': 'ok',
83 # The base class increments the execution count
83 # The base class increments the execution count
84 'execution_count': self.execution_count,
84 'execution_count': self.execution_count,
85 'payload': [],
85 'payload': [],
86 'user_expressions': {},
86 'user_expressions': {},
87 }
87 }
88
88
89 if __name__ == '__main__':
89 if __name__ == '__main__':
90 from IPython.kernel.zmq.kernelapp import IPKernelApp
90 from IPython.kernel.zmq.kernelapp import IPKernelApp
91 IPKernelApp.launch_instance(kernel_class=EchoKernel)
91 IPKernelApp.launch_instance(kernel_class=EchoKernel)
92
92
93 Here's the Kernel spec ``kernel.json`` file for this::
93 Here's the Kernel spec ``kernel.json`` file for this::
94
94
95 {"argv":["python","-m","echokernel", "-f", "{connection_file}"],
95 {"argv":["python","-m","echokernel", "-f", "{connection_file}"],
96 "display_name":"Echo",
96 "display_name":"Echo",
97 "language":"no-op"
97 "language":"no-op"
98 }
98 }
99
99
100
100
101 Optional steps
101 Optional steps
102 --------------
102 --------------
103
103
104 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
105 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
106 relevant section of the :doc:`messaging spec <messaging>`.
106 relevant section of the :doc:`messaging spec <messaging>`.
107
107
108 .. class:: MyKernel
108 .. class:: MyKernel
109
109
110 .. method:: do_complete(code, cusor_pos)
110 .. method:: do_complete(code, cusor_pos)
111
111
112 Code completion
112 Code completion
113
113
114 :param str code: The code already present
114 :param str code: The code already present
115 :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
116
116
117 .. seealso::
117 .. seealso::
118
118
119 :ref:`msging_completion` messages
119 :ref:`msging_completion` messages
120
120
121 .. method:: do_inspect(code, cusor_pos, detail_level=0)
121 .. method:: do_inspect(code, cusor_pos, detail_level=0)
122
122
123 Object introspection
123 Object introspection
124
124
125 :param str code: The code
125 :param str code: The code
126 :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
127 :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
128 the source code.
128 the source code.
129
129
130 .. seealso::
130 .. seealso::
131
131
132 :ref:`msging_inspection` messages
132 :ref:`msging_inspection` messages
133
133
134 .. 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)
135
135
136 History access. Only the relevant parameters for the type of history
136 History access. Only the relevant parameters for the type of history
137 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
138 for all the arguments shown with defaults here.
138 for all the arguments shown with defaults here.
139
139
140 .. seealso::
140 .. seealso::
141
141
142 :ref:`msging_history` messages
142 :ref:`msging_history` messages
143
143
144 .. method:: do_is_complete(code)
145
146 Is code entered in a console-like interface complete and ready to execute,
147 or should a continuation prompt be shown?
148
149 :param str code: The code entered so far - possibly multiple lines
150
151 .. seealso::
152
153 :ref:`msging_is_complete` messages
154
144 .. method:: do_shutdown(restart)
155 .. method:: do_shutdown(restart)
145
156
146 Shutdown the kernel. You only need to handle your own clean up - the kernel
157 Shutdown the kernel. You only need to handle your own clean up - the kernel
147 machinery will take care of cleaning up its own things before stopping.
158 machinery will take care of cleaning up its own things before stopping.
148
159
149 :param bool restart: Whether the kernel will be started again afterwards
160 :param bool restart: Whether the kernel will be started again afterwards
150
161
151 .. seealso::
162 .. seealso::
152
163
153 :ref:`msging_shutdown` messages
164 :ref:`msging_shutdown` messages
General Comments 0
You need to be logged in to leave comments. Login now