##// END OF EJS Templates
Minor syntax cleanup and silification....
Matthias Bussonnier -
Show More
@@ -1,374 +1,382 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Top-level display functions for displaying object in different formats."""
2 """Top-level display functions for displaying object in different formats."""
3
3
4 # Copyright (c) IPython Development Team.
4 # Copyright (c) IPython Development Team.
5 # Distributed under the terms of the Modified BSD License.
5 # Distributed under the terms of the Modified BSD License.
6
6
7
7
8 from binascii import b2a_hex
8 from binascii import b2a_hex
9 import os
9 import os
10 import sys
10 import sys
11
11
12 __all__ = ['display', 'clear_output', 'publish_display_data', 'update_display', 'DisplayHandle']
12 __all__ = ['display', 'clear_output', 'publish_display_data', 'update_display', 'DisplayHandle']
13
13
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15 # utility functions
15 # utility functions
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17
17
18
18
19 def _merge(d1, d2):
19 def _merge(d1, d2):
20 """Like update, but merges sub-dicts instead of clobbering at the top level.
20 """Like update, but merges sub-dicts instead of clobbering at the top level.
21
21
22 Updates d1 in-place
22 Updates d1 in-place
23 """
23 """
24
24
25 if not isinstance(d2, dict) or not isinstance(d1, dict):
25 if not isinstance(d2, dict) or not isinstance(d1, dict):
26 return d2
26 return d2
27 for key, value in d2.items():
27 for key, value in d2.items():
28 d1[key] = _merge(d1.get(key), value)
28 d1[key] = _merge(d1.get(key), value)
29 return d1
29 return d1
30
30
31
31
32 #-----------------------------------------------------------------------------
32 #-----------------------------------------------------------------------------
33 # Main functions
33 # Main functions
34 #-----------------------------------------------------------------------------
34 #-----------------------------------------------------------------------------
35
35
36
36
37 # use * to indicate transient is keyword-only
37 # use * to indicate transient is keyword-only
38 def publish_display_data(data, metadata=None, source=None, *, transient=None, **kwargs):
38 def publish_display_data(data, metadata=None, source=None, *, transient=None, **kwargs):
39 """Publish data and metadata to all frontends.
39 """Publish data and metadata to all frontends.
40
40
41 See the ``display_data`` message in the messaging documentation for
41 See the ``display_data`` message in the messaging documentation for
42 more details about this message type.
42 more details about this message type.
43
43
44 Keys of data and metadata can be any mime-type.
44 Keys of data and metadata can be any mime-type.
45
45
46 Parameters
46 Parameters
47 ----------
47 ----------
48 data : dict
48 data : dict
49 A dictionary having keys that are valid MIME types (like
49 A dictionary having keys that are valid MIME types (like
50 'text/plain' or 'image/svg+xml') and values that are the data for
50 'text/plain' or 'image/svg+xml') and values that are the data for
51 that MIME type. The data itself must be a JSON'able data
51 that MIME type. The data itself must be a JSON'able data
52 structure. Minimally all data should have the 'text/plain' data,
52 structure. Minimally all data should have the 'text/plain' data,
53 which can be displayed by all frontends. If more than the plain
53 which can be displayed by all frontends. If more than the plain
54 text is given, it is up to the frontend to decide which
54 text is given, it is up to the frontend to decide which
55 representation to use.
55 representation to use.
56 metadata : dict
56 metadata : dict
57 A dictionary for metadata related to the data. This can contain
57 A dictionary for metadata related to the data. This can contain
58 arbitrary key, value pairs that frontends can use to interpret
58 arbitrary key, value pairs that frontends can use to interpret
59 the data. mime-type keys matching those in data can be used
59 the data. mime-type keys matching those in data can be used
60 to specify metadata about particular representations.
60 to specify metadata about particular representations.
61 source : str, deprecated
61 source : str, deprecated
62 Unused.
62 Unused.
63 transient : dict, keyword-only
63 transient : dict, keyword-only
64 A dictionary of transient data, such as display_id.
64 A dictionary of transient data, such as display_id.
65 """
65 """
66 from IPython.core.interactiveshell import InteractiveShell
66 from IPython.core.interactiveshell import InteractiveShell
67
67
68 display_pub = InteractiveShell.instance().display_pub
68 display_pub = InteractiveShell.instance().display_pub
69
69
70 # only pass transient if supplied,
70 # only pass transient if supplied,
71 # to avoid errors with older ipykernel.
71 # to avoid errors with older ipykernel.
72 # TODO: We could check for ipykernel version and provide a detailed upgrade message.
72 # TODO: We could check for ipykernel version and provide a detailed upgrade message.
73 if transient:
73 if transient:
74 kwargs['transient'] = transient
74 kwargs['transient'] = transient
75
75
76 display_pub.publish(
76 display_pub.publish(
77 data=data,
77 data=data,
78 metadata=metadata,
78 metadata=metadata,
79 **kwargs
79 **kwargs
80 )
80 )
81
81
82
82
83 def _new_id():
83 def _new_id():
84 """Generate a new random text id with urandom"""
84 """Generate a new random text id with urandom"""
85 return b2a_hex(os.urandom(16)).decode('ascii')
85 return b2a_hex(os.urandom(16)).decode('ascii')
86
86
87
87
88 def display(*objs, include=None, exclude=None, metadata=None, transient=None, display_id=None, **kwargs):
88 def display(
89 *objs,
90 include=None,
91 exclude=None,
92 metadata=None,
93 transient=None,
94 display_id=None,
95 raw=False,
96 clear=False,
97 **kwargs
98 ):
89 """Display a Python object in all frontends.
99 """Display a Python object in all frontends.
90
100
91 By default all representations will be computed and sent to the frontends.
101 By default all representations will be computed and sent to the frontends.
92 Frontends can decide which representation is used and how.
102 Frontends can decide which representation is used and how.
93
103
94 In terminal IPython this will be similar to using :func:`print`, for use in richer
104 In terminal IPython this will be similar to using :func:`print`, for use in richer
95 frontends see Jupyter notebook examples with rich display logic.
105 frontends see Jupyter notebook examples with rich display logic.
96
106
97 Parameters
107 Parameters
98 ----------
108 ----------
99 *objs : object
109 *objs : object
100 The Python objects to display.
110 The Python objects to display.
101 raw : bool, optional
111 raw : bool, optional
102 Are the objects to be displayed already mimetype-keyed dicts of raw display data,
112 Are the objects to be displayed already mimetype-keyed dicts of raw display data,
103 or Python objects that need to be formatted before display? [default: False]
113 or Python objects that need to be formatted before display? [default: False]
104 include : list, tuple or set, optional
114 include : list, tuple or set, optional
105 A list of format type strings (MIME types) to include in the
115 A list of format type strings (MIME types) to include in the
106 format data dict. If this is set *only* the format types included
116 format data dict. If this is set *only* the format types included
107 in this list will be computed.
117 in this list will be computed.
108 exclude : list, tuple or set, optional
118 exclude : list, tuple or set, optional
109 A list of format type strings (MIME types) to exclude in the format
119 A list of format type strings (MIME types) to exclude in the format
110 data dict. If this is set all format types will be computed,
120 data dict. If this is set all format types will be computed,
111 except for those included in this argument.
121 except for those included in this argument.
112 metadata : dict, optional
122 metadata : dict, optional
113 A dictionary of metadata to associate with the output.
123 A dictionary of metadata to associate with the output.
114 mime-type keys in this dictionary will be associated with the individual
124 mime-type keys in this dictionary will be associated with the individual
115 representation formats, if they exist.
125 representation formats, if they exist.
116 transient : dict, optional
126 transient : dict, optional
117 A dictionary of transient data to associate with the output.
127 A dictionary of transient data to associate with the output.
118 Data in this dict should not be persisted to files (e.g. notebooks).
128 Data in this dict should not be persisted to files (e.g. notebooks).
119 display_id : str, bool optional
129 display_id : str, bool optional
120 Set an id for the display.
130 Set an id for the display.
121 This id can be used for updating this display area later via update_display.
131 This id can be used for updating this display area later via update_display.
122 If given as `True`, generate a new `display_id`
132 If given as `True`, generate a new `display_id`
123 clear : bool, optional
133 clear : bool, optional
124 Should the output area be cleared before displaying anything? If True,
134 Should the output area be cleared before displaying anything? If True,
125 this will wait for additional output before clearing. [default: False]
135 this will wait for additional output before clearing. [default: False]
126 kwargs: additional keyword-args, optional
136 kwargs: additional keyword-args, optional
127 Additional keyword-arguments are passed through to the display publisher.
137 Additional keyword-arguments are passed through to the display publisher.
128
138
129 Returns
139 Returns
130 -------
140 -------
131
141
132 handle: DisplayHandle
142 handle: DisplayHandle
133 Returns a handle on updatable displays for use with :func:`update_display`,
143 Returns a handle on updatable displays for use with :func:`update_display`,
134 if `display_id` is given. Returns :any:`None` if no `display_id` is given
144 if `display_id` is given. Returns :any:`None` if no `display_id` is given
135 (default).
145 (default).
136
146
137 Examples
147 Examples
138 --------
148 --------
139
149
140 >>> class Json(object):
150 >>> class Json(object):
141 ... def __init__(self, json):
151 ... def __init__(self, json):
142 ... self.json = json
152 ... self.json = json
143 ... def _repr_pretty_(self, pp, cycle):
153 ... def _repr_pretty_(self, pp, cycle):
144 ... import json
154 ... import json
145 ... pp.text(json.dumps(self.json, indent=2))
155 ... pp.text(json.dumps(self.json, indent=2))
146 ... def __repr__(self):
156 ... def __repr__(self):
147 ... return str(self.json)
157 ... return str(self.json)
148 ...
158 ...
149
159
150 >>> d = Json({1:2, 3: {4:5}})
160 >>> d = Json({1:2, 3: {4:5}})
151
161
152 >>> print(d)
162 >>> print(d)
153 {1: 2, 3: {4: 5}}
163 {1: 2, 3: {4: 5}}
154
164
155 >>> display(d)
165 >>> display(d)
156 {
166 {
157 "1": 2,
167 "1": 2,
158 "3": {
168 "3": {
159 "4": 5
169 "4": 5
160 }
170 }
161 }
171 }
162
172
163 >>> def int_formatter(integer, pp, cycle):
173 >>> def int_formatter(integer, pp, cycle):
164 ... pp.text('I'*integer)
174 ... pp.text('I'*integer)
165
175
166 >>> plain = get_ipython().display_formatter.formatters['text/plain']
176 >>> plain = get_ipython().display_formatter.formatters['text/plain']
167 >>> plain.for_type(int, int_formatter)
177 >>> plain.for_type(int, int_formatter)
168 <function _repr_pprint at 0x...>
178 <function _repr_pprint at 0x...>
169 >>> display(7-5)
179 >>> display(7-5)
170 II
180 II
171
181
172 >>> del plain.type_printers[int]
182 >>> del plain.type_printers[int]
173 >>> display(7-5)
183 >>> display(7-5)
174 2
184 2
175
185
176 See Also
186 See Also
177 --------
187 --------
178
188
179 :func:`update_display`
189 :func:`update_display`
180
190
181 Notes
191 Notes
182 -----
192 -----
183
193
184 In Python, objects can declare their textual representation using the
194 In Python, objects can declare their textual representation using the
185 `__repr__` method. IPython expands on this idea and allows objects to declare
195 `__repr__` method. IPython expands on this idea and allows objects to declare
186 other, rich representations including:
196 other, rich representations including:
187
197
188 - HTML
198 - HTML
189 - JSON
199 - JSON
190 - PNG
200 - PNG
191 - JPEG
201 - JPEG
192 - SVG
202 - SVG
193 - LaTeX
203 - LaTeX
194
204
195 A single object can declare some or all of these representations; all are
205 A single object can declare some or all of these representations; all are
196 handled by IPython's display system.
206 handled by IPython's display system.
197
207
198 The main idea of the first approach is that you have to implement special
208 The main idea of the first approach is that you have to implement special
199 display methods when you define your class, one for each representation you
209 display methods when you define your class, one for each representation you
200 want to use. Here is a list of the names of the special methods and the
210 want to use. Here is a list of the names of the special methods and the
201 values they must return:
211 values they must return:
202
212
203 - `_repr_html_`: return raw HTML as a string, or a tuple (see below).
213 - `_repr_html_`: return raw HTML as a string, or a tuple (see below).
204 - `_repr_json_`: return a JSONable dict, or a tuple (see below).
214 - `_repr_json_`: return a JSONable dict, or a tuple (see below).
205 - `_repr_jpeg_`: return raw JPEG data, or a tuple (see below).
215 - `_repr_jpeg_`: return raw JPEG data, or a tuple (see below).
206 - `_repr_png_`: return raw PNG data, or a tuple (see below).
216 - `_repr_png_`: return raw PNG data, or a tuple (see below).
207 - `_repr_svg_`: return raw SVG data as a string, or a tuple (see below).
217 - `_repr_svg_`: return raw SVG data as a string, or a tuple (see below).
208 - `_repr_latex_`: return LaTeX commands in a string surrounded by "$",
218 - `_repr_latex_`: return LaTeX commands in a string surrounded by "$",
209 or a tuple (see below).
219 or a tuple (see below).
210 - `_repr_mimebundle_`: return a full mimebundle containing the mapping
220 - `_repr_mimebundle_`: return a full mimebundle containing the mapping
211 from all mimetypes to data.
221 from all mimetypes to data.
212 Use this for any mime-type not listed above.
222 Use this for any mime-type not listed above.
213
223
214 The above functions may also return the object's metadata alonside the
224 The above functions may also return the object's metadata alonside the
215 data. If the metadata is available, the functions will return a tuple
225 data. If the metadata is available, the functions will return a tuple
216 containing the data and metadata, in that order. If there is no metadata
226 containing the data and metadata, in that order. If there is no metadata
217 available, then the functions will return the data only.
227 available, then the functions will return the data only.
218
228
219 When you are directly writing your own classes, you can adapt them for
229 When you are directly writing your own classes, you can adapt them for
220 display in IPython by following the above approach. But in practice, you
230 display in IPython by following the above approach. But in practice, you
221 often need to work with existing classes that you can't easily modify.
231 often need to work with existing classes that you can't easily modify.
222
232
223 You can refer to the documentation on integrating with the display system in
233 You can refer to the documentation on integrating with the display system in
224 order to register custom formatters for already existing types
234 order to register custom formatters for already existing types
225 (:ref:`integrating_rich_display`).
235 (:ref:`integrating_rich_display`).
226
236
227 .. versionadded:: 5.4 display available without import
237 .. versionadded:: 5.4 display available without import
228 .. versionadded:: 6.1 display available without import
238 .. versionadded:: 6.1 display available without import
229
239
230 Since IPython 5.4 and 6.1 :func:`display` is automatically made available to
240 Since IPython 5.4 and 6.1 :func:`display` is automatically made available to
231 the user without import. If you are using display in a document that might
241 the user without import. If you are using display in a document that might
232 be used in a pure python context or with older version of IPython, use the
242 be used in a pure python context or with older version of IPython, use the
233 following import at the top of your file::
243 following import at the top of your file::
234
244
235 from IPython.display import display
245 from IPython.display import display
236
246
237 """
247 """
238 from IPython.core.interactiveshell import InteractiveShell
248 from IPython.core.interactiveshell import InteractiveShell
239
249
240 if not InteractiveShell.initialized():
250 if not InteractiveShell.initialized():
241 # Directly print objects.
251 # Directly print objects.
242 print(*objs)
252 print(*objs)
243 return
253 return
244
254
245 raw = kwargs.pop("raw", False)
246 clear = kwargs.pop("clear", False)
247 if transient is None:
255 if transient is None:
248 transient = {}
256 transient = {}
249 if metadata is None:
257 if metadata is None:
250 metadata={}
258 metadata={}
251 if display_id:
259 if display_id:
252 if display_id is True:
260 if display_id is True:
253 display_id = _new_id()
261 display_id = _new_id()
254 transient['display_id'] = display_id
262 transient['display_id'] = display_id
255 if kwargs.get('update') and 'display_id' not in transient:
263 if kwargs.get('update') and 'display_id' not in transient:
256 raise TypeError('display_id required for update_display')
264 raise TypeError('display_id required for update_display')
257 if transient:
265 if transient:
258 kwargs['transient'] = transient
266 kwargs['transient'] = transient
259
267
260 if not objs and display_id:
268 if not objs and display_id:
261 # if given no objects, but still a request for a display_id,
269 # if given no objects, but still a request for a display_id,
262 # we assume the user wants to insert an empty output that
270 # we assume the user wants to insert an empty output that
263 # can be updated later
271 # can be updated later
264 objs = [{}]
272 objs = [{}]
265 raw = True
273 raw = True
266
274
267 if not raw:
275 if not raw:
268 format = InteractiveShell.instance().display_formatter.format
276 format = InteractiveShell.instance().display_formatter.format
269
277
270 if clear:
278 if clear:
271 clear_output(wait=True)
279 clear_output(wait=True)
272
280
273 for obj in objs:
281 for obj in objs:
274 if raw:
282 if raw:
275 publish_display_data(data=obj, metadata=metadata, **kwargs)
283 publish_display_data(data=obj, metadata=metadata, **kwargs)
276 else:
284 else:
277 format_dict, md_dict = format(obj, include=include, exclude=exclude)
285 format_dict, md_dict = format(obj, include=include, exclude=exclude)
278 if not format_dict:
286 if not format_dict:
279 # nothing to display (e.g. _ipython_display_ took over)
287 # nothing to display (e.g. _ipython_display_ took over)
280 continue
288 continue
281 if metadata:
289 if metadata:
282 # kwarg-specified metadata gets precedence
290 # kwarg-specified metadata gets precedence
283 _merge(md_dict, metadata)
291 _merge(md_dict, metadata)
284 publish_display_data(data=format_dict, metadata=md_dict, **kwargs)
292 publish_display_data(data=format_dict, metadata=md_dict, **kwargs)
285 if display_id:
293 if display_id:
286 return DisplayHandle(display_id)
294 return DisplayHandle(display_id)
287
295
288
296
289 # use * for keyword-only display_id arg
297 # use * for keyword-only display_id arg
290 def update_display(obj, *, display_id, **kwargs):
298 def update_display(obj, *, display_id, **kwargs):
291 """Update an existing display by id
299 """Update an existing display by id
292
300
293 Parameters
301 Parameters
294 ----------
302 ----------
295
303
296 obj:
304 obj:
297 The object with which to update the display
305 The object with which to update the display
298 display_id: keyword-only
306 display_id: keyword-only
299 The id of the display to update
307 The id of the display to update
300
308
301 See Also
309 See Also
302 --------
310 --------
303
311
304 :func:`display`
312 :func:`display`
305 """
313 """
306 kwargs['update'] = True
314 kwargs['update'] = True
307 display(obj, display_id=display_id, **kwargs)
315 display(obj, display_id=display_id, **kwargs)
308
316
309
317
310 class DisplayHandle(object):
318 class DisplayHandle(object):
311 """A handle on an updatable display
319 """A handle on an updatable display
312
320
313 Call `.update(obj)` to display a new object.
321 Call `.update(obj)` to display a new object.
314
322
315 Call `.display(obj`) to add a new instance of this display,
323 Call `.display(obj`) to add a new instance of this display,
316 and update existing instances.
324 and update existing instances.
317
325
318 See Also
326 See Also
319 --------
327 --------
320
328
321 :func:`display`, :func:`update_display`
329 :func:`display`, :func:`update_display`
322
330
323 """
331 """
324
332
325 def __init__(self, display_id=None):
333 def __init__(self, display_id=None):
326 if display_id is None:
334 if display_id is None:
327 display_id = _new_id()
335 display_id = _new_id()
328 self.display_id = display_id
336 self.display_id = display_id
329
337
330 def __repr__(self):
338 def __repr__(self):
331 return "<%s display_id=%s>" % (self.__class__.__name__, self.display_id)
339 return "<%s display_id=%s>" % (self.__class__.__name__, self.display_id)
332
340
333 def display(self, obj, **kwargs):
341 def display(self, obj, **kwargs):
334 """Make a new display with my id, updating existing instances.
342 """Make a new display with my id, updating existing instances.
335
343
336 Parameters
344 Parameters
337 ----------
345 ----------
338
346
339 obj:
347 obj:
340 object to display
348 object to display
341 **kwargs:
349 **kwargs:
342 additional keyword arguments passed to display
350 additional keyword arguments passed to display
343 """
351 """
344 display(obj, display_id=self.display_id, **kwargs)
352 display(obj, display_id=self.display_id, **kwargs)
345
353
346 def update(self, obj, **kwargs):
354 def update(self, obj, **kwargs):
347 """Update existing displays with my id
355 """Update existing displays with my id
348
356
349 Parameters
357 Parameters
350 ----------
358 ----------
351
359
352 obj:
360 obj:
353 object to display
361 object to display
354 **kwargs:
362 **kwargs:
355 additional keyword arguments passed to update_display
363 additional keyword arguments passed to update_display
356 """
364 """
357 update_display(obj, display_id=self.display_id, **kwargs)
365 update_display(obj, display_id=self.display_id, **kwargs)
358
366
359
367
360 def clear_output(wait=False):
368 def clear_output(wait=False):
361 """Clear the output of the current cell receiving output.
369 """Clear the output of the current cell receiving output.
362
370
363 Parameters
371 Parameters
364 ----------
372 ----------
365 wait : bool [default: false]
373 wait : bool [default: false]
366 Wait to clear the output until new output is available to replace it."""
374 Wait to clear the output until new output is available to replace it."""
367 from IPython.core.interactiveshell import InteractiveShell
375 from IPython.core.interactiveshell import InteractiveShell
368 if InteractiveShell.initialized():
376 if InteractiveShell.initialized():
369 InteractiveShell.instance().display_pub.clear_output(wait)
377 InteractiveShell.instance().display_pub.clear_output(wait)
370 else:
378 else:
371 print('\033[2K\r', end='')
379 print('\033[2K\r', end='')
372 sys.stdout.flush()
380 sys.stdout.flush()
373 print('\033[2K\r', end='')
381 print('\033[2K\r', end='')
374 sys.stderr.flush()
382 sys.stderr.flush()
@@ -1,717 +1,717 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """Magic functions for InteractiveShell.
2 """Magic functions for InteractiveShell.
3 """
3 """
4
4
5 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 # Copyright (C) 2001 Fernando Perez <fperez@colorado.edu>
7 # Copyright (C) 2001 Fernando Perez <fperez@colorado.edu>
8 # Copyright (C) 2008 The IPython Development Team
8 # Copyright (C) 2008 The IPython Development Team
9
9
10 # Distributed under the terms of the BSD License. The full license is in
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13
13
14 import os
14 import os
15 import re
15 import re
16 import sys
16 import sys
17 from getopt import getopt, GetoptError
17 from getopt import getopt, GetoptError
18
18
19 from traitlets.config.configurable import Configurable
19 from traitlets.config.configurable import Configurable
20 from . import oinspect
20 from . import oinspect
21 from .error import UsageError
21 from .error import UsageError
22 from .inputtransformer2 import ESC_MAGIC, ESC_MAGIC2
22 from .inputtransformer2 import ESC_MAGIC, ESC_MAGIC2
23 from decorator import decorator
23 from decorator import decorator
24 from ..utils.ipstruct import Struct
24 from ..utils.ipstruct import Struct
25 from ..utils.process import arg_split
25 from ..utils.process import arg_split
26 from ..utils.text import dedent
26 from ..utils.text import dedent
27 from traitlets import Bool, Dict, Instance, observe
27 from traitlets import Bool, Dict, Instance, observe
28 from logging import error
28 from logging import error
29
29
30 #-----------------------------------------------------------------------------
30 #-----------------------------------------------------------------------------
31 # Globals
31 # Globals
32 #-----------------------------------------------------------------------------
32 #-----------------------------------------------------------------------------
33
33
34 # A dict we'll use for each class that has magics, used as temporary storage to
34 # A dict we'll use for each class that has magics, used as temporary storage to
35 # pass information between the @line/cell_magic method decorators and the
35 # pass information between the @line/cell_magic method decorators and the
36 # @magics_class class decorator, because the method decorators have no
36 # @magics_class class decorator, because the method decorators have no
37 # access to the class when they run. See for more details:
37 # access to the class when they run. See for more details:
38 # http://stackoverflow.com/questions/2366713/can-a-python-decorator-of-an-instance-method-access-the-class
38 # http://stackoverflow.com/questions/2366713/can-a-python-decorator-of-an-instance-method-access-the-class
39
39
40 magics = dict(line={}, cell={})
40 magics = dict(line={}, cell={})
41
41
42 magic_kinds = ('line', 'cell')
42 magic_kinds = ('line', 'cell')
43 magic_spec = ('line', 'cell', 'line_cell')
43 magic_spec = ('line', 'cell', 'line_cell')
44 magic_escapes = dict(line=ESC_MAGIC, cell=ESC_MAGIC2)
44 magic_escapes = dict(line=ESC_MAGIC, cell=ESC_MAGIC2)
45
45
46 #-----------------------------------------------------------------------------
46 #-----------------------------------------------------------------------------
47 # Utility classes and functions
47 # Utility classes and functions
48 #-----------------------------------------------------------------------------
48 #-----------------------------------------------------------------------------
49
49
50 class Bunch: pass
50 class Bunch: pass
51
51
52
52
53 def on_off(tag):
53 def on_off(tag):
54 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
54 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
55 return ['OFF','ON'][tag]
55 return ['OFF','ON'][tag]
56
56
57
57
58 def compress_dhist(dh):
58 def compress_dhist(dh):
59 """Compress a directory history into a new one with at most 20 entries.
59 """Compress a directory history into a new one with at most 20 entries.
60
60
61 Return a new list made from the first and last 10 elements of dhist after
61 Return a new list made from the first and last 10 elements of dhist after
62 removal of duplicates.
62 removal of duplicates.
63 """
63 """
64 head, tail = dh[:-10], dh[-10:]
64 head, tail = dh[:-10], dh[-10:]
65
65
66 newhead = []
66 newhead = []
67 done = set()
67 done = set()
68 for h in head:
68 for h in head:
69 if h in done:
69 if h in done:
70 continue
70 continue
71 newhead.append(h)
71 newhead.append(h)
72 done.add(h)
72 done.add(h)
73
73
74 return newhead + tail
74 return newhead + tail
75
75
76
76
77 def needs_local_scope(func):
77 def needs_local_scope(func):
78 """Decorator to mark magic functions which need to local scope to run."""
78 """Decorator to mark magic functions which need to local scope to run."""
79 func.needs_local_scope = True
79 func.needs_local_scope = True
80 return func
80 return func
81
81
82 #-----------------------------------------------------------------------------
82 #-----------------------------------------------------------------------------
83 # Class and method decorators for registering magics
83 # Class and method decorators for registering magics
84 #-----------------------------------------------------------------------------
84 #-----------------------------------------------------------------------------
85
85
86 def magics_class(cls):
86 def magics_class(cls):
87 """Class decorator for all subclasses of the main Magics class.
87 """Class decorator for all subclasses of the main Magics class.
88
88
89 Any class that subclasses Magics *must* also apply this decorator, to
89 Any class that subclasses Magics *must* also apply this decorator, to
90 ensure that all the methods that have been decorated as line/cell magics
90 ensure that all the methods that have been decorated as line/cell magics
91 get correctly registered in the class instance. This is necessary because
91 get correctly registered in the class instance. This is necessary because
92 when method decorators run, the class does not exist yet, so they
92 when method decorators run, the class does not exist yet, so they
93 temporarily store their information into a module global. Application of
93 temporarily store their information into a module global. Application of
94 this class decorator copies that global data to the class instance and
94 this class decorator copies that global data to the class instance and
95 clears the global.
95 clears the global.
96
96
97 Obviously, this mechanism is not thread-safe, which means that the
97 Obviously, this mechanism is not thread-safe, which means that the
98 *creation* of subclasses of Magic should only be done in a single-thread
98 *creation* of subclasses of Magic should only be done in a single-thread
99 context. Instantiation of the classes has no restrictions. Given that
99 context. Instantiation of the classes has no restrictions. Given that
100 these classes are typically created at IPython startup time and before user
100 these classes are typically created at IPython startup time and before user
101 application code becomes active, in practice this should not pose any
101 application code becomes active, in practice this should not pose any
102 problems.
102 problems.
103 """
103 """
104 cls.registered = True
104 cls.registered = True
105 cls.magics = dict(line = magics['line'],
105 cls.magics = dict(line = magics['line'],
106 cell = magics['cell'])
106 cell = magics['cell'])
107 magics['line'] = {}
107 magics['line'] = {}
108 magics['cell'] = {}
108 magics['cell'] = {}
109 return cls
109 return cls
110
110
111
111
112 def record_magic(dct, magic_kind, magic_name, func):
112 def record_magic(dct, magic_kind, magic_name, func):
113 """Utility function to store a function as a magic of a specific kind.
113 """Utility function to store a function as a magic of a specific kind.
114
114
115 Parameters
115 Parameters
116 ----------
116 ----------
117 dct : dict
117 dct : dict
118 A dictionary with 'line' and 'cell' subdicts.
118 A dictionary with 'line' and 'cell' subdicts.
119
119
120 magic_kind : str
120 magic_kind : str
121 Kind of magic to be stored.
121 Kind of magic to be stored.
122
122
123 magic_name : str
123 magic_name : str
124 Key to store the magic as.
124 Key to store the magic as.
125
125
126 func : function
126 func : function
127 Callable object to store.
127 Callable object to store.
128 """
128 """
129 if magic_kind == 'line_cell':
129 if magic_kind == 'line_cell':
130 dct['line'][magic_name] = dct['cell'][magic_name] = func
130 dct['line'][magic_name] = dct['cell'][magic_name] = func
131 else:
131 else:
132 dct[magic_kind][magic_name] = func
132 dct[magic_kind][magic_name] = func
133
133
134
134
135 def validate_type(magic_kind):
135 def validate_type(magic_kind):
136 """Ensure that the given magic_kind is valid.
136 """Ensure that the given magic_kind is valid.
137
137
138 Check that the given magic_kind is one of the accepted spec types (stored
138 Check that the given magic_kind is one of the accepted spec types (stored
139 in the global `magic_spec`), raise ValueError otherwise.
139 in the global `magic_spec`), raise ValueError otherwise.
140 """
140 """
141 if magic_kind not in magic_spec:
141 if magic_kind not in magic_spec:
142 raise ValueError('magic_kind must be one of %s, %s given' %
142 raise ValueError('magic_kind must be one of %s, %s given' %
143 magic_kinds, magic_kind)
143 magic_kinds, magic_kind)
144
144
145
145
146 # The docstrings for the decorator below will be fairly similar for the two
146 # The docstrings for the decorator below will be fairly similar for the two
147 # types (method and function), so we generate them here once and reuse the
147 # types (method and function), so we generate them here once and reuse the
148 # templates below.
148 # templates below.
149 _docstring_template = \
149 _docstring_template = \
150 """Decorate the given {0} as {1} magic.
150 """Decorate the given {0} as {1} magic.
151
151
152 The decorator can be used with or without arguments, as follows.
152 The decorator can be used with or without arguments, as follows.
153
153
154 i) without arguments: it will create a {1} magic named as the {0} being
154 i) without arguments: it will create a {1} magic named as the {0} being
155 decorated::
155 decorated::
156
156
157 @deco
157 @deco
158 def foo(...)
158 def foo(...)
159
159
160 will create a {1} magic named `foo`.
160 will create a {1} magic named `foo`.
161
161
162 ii) with one string argument: which will be used as the actual name of the
162 ii) with one string argument: which will be used as the actual name of the
163 resulting magic::
163 resulting magic::
164
164
165 @deco('bar')
165 @deco('bar')
166 def foo(...)
166 def foo(...)
167
167
168 will create a {1} magic named `bar`.
168 will create a {1} magic named `bar`.
169
169
170 To register a class magic use ``Interactiveshell.register_magic(class or instance)``.
170 To register a class magic use ``Interactiveshell.register_magic(class or instance)``.
171 """
171 """
172
172
173 # These two are decorator factories. While they are conceptually very similar,
173 # These two are decorator factories. While they are conceptually very similar,
174 # there are enough differences in the details that it's simpler to have them
174 # there are enough differences in the details that it's simpler to have them
175 # written as completely standalone functions rather than trying to share code
175 # written as completely standalone functions rather than trying to share code
176 # and make a single one with convoluted logic.
176 # and make a single one with convoluted logic.
177
177
178 def _method_magic_marker(magic_kind):
178 def _method_magic_marker(magic_kind):
179 """Decorator factory for methods in Magics subclasses.
179 """Decorator factory for methods in Magics subclasses.
180 """
180 """
181
181
182 validate_type(magic_kind)
182 validate_type(magic_kind)
183
183
184 # This is a closure to capture the magic_kind. We could also use a class,
184 # This is a closure to capture the magic_kind. We could also use a class,
185 # but it's overkill for just that one bit of state.
185 # but it's overkill for just that one bit of state.
186 def magic_deco(arg):
186 def magic_deco(arg):
187 call = lambda f, *a, **k: f(*a, **k)
187 call = lambda f, *a, **k: f(*a, **k)
188
188
189 if callable(arg):
189 if callable(arg):
190 # "Naked" decorator call (just @foo, no args)
190 # "Naked" decorator call (just @foo, no args)
191 func = arg
191 func = arg
192 name = func.__name__
192 name = func.__name__
193 retval = decorator(call, func)
193 retval = decorator(call, func)
194 record_magic(magics, magic_kind, name, name)
194 record_magic(magics, magic_kind, name, name)
195 elif isinstance(arg, str):
195 elif isinstance(arg, str):
196 # Decorator called with arguments (@foo('bar'))
196 # Decorator called with arguments (@foo('bar'))
197 name = arg
197 name = arg
198 def mark(func, *a, **kw):
198 def mark(func, *a, **kw):
199 record_magic(magics, magic_kind, name, func.__name__)
199 record_magic(magics, magic_kind, name, func.__name__)
200 return decorator(call, func)
200 return decorator(call, func)
201 retval = mark
201 retval = mark
202 else:
202 else:
203 raise TypeError("Decorator can only be called with "
203 raise TypeError("Decorator can only be called with "
204 "string or function")
204 "string or function")
205 return retval
205 return retval
206
206
207 # Ensure the resulting decorator has a usable docstring
207 # Ensure the resulting decorator has a usable docstring
208 magic_deco.__doc__ = _docstring_template.format('method', magic_kind)
208 magic_deco.__doc__ = _docstring_template.format('method', magic_kind)
209 return magic_deco
209 return magic_deco
210
210
211
211
212 def _function_magic_marker(magic_kind):
212 def _function_magic_marker(magic_kind):
213 """Decorator factory for standalone functions.
213 """Decorator factory for standalone functions.
214 """
214 """
215 validate_type(magic_kind)
215 validate_type(magic_kind)
216
216
217 # This is a closure to capture the magic_kind. We could also use a class,
217 # This is a closure to capture the magic_kind. We could also use a class,
218 # but it's overkill for just that one bit of state.
218 # but it's overkill for just that one bit of state.
219 def magic_deco(arg):
219 def magic_deco(arg):
220 call = lambda f, *a, **k: f(*a, **k)
220 call = lambda f, *a, **k: f(*a, **k)
221
221
222 # Find get_ipython() in the caller's namespace
222 # Find get_ipython() in the caller's namespace
223 caller = sys._getframe(1)
223 caller = sys._getframe(1)
224 for ns in ['f_locals', 'f_globals', 'f_builtins']:
224 for ns in ['f_locals', 'f_globals', 'f_builtins']:
225 get_ipython = getattr(caller, ns).get('get_ipython')
225 get_ipython = getattr(caller, ns).get('get_ipython')
226 if get_ipython is not None:
226 if get_ipython is not None:
227 break
227 break
228 else:
228 else:
229 raise NameError('Decorator can only run in context where '
229 raise NameError('Decorator can only run in context where '
230 '`get_ipython` exists')
230 '`get_ipython` exists')
231
231
232 ip = get_ipython()
232 ip = get_ipython()
233
233
234 if callable(arg):
234 if callable(arg):
235 # "Naked" decorator call (just @foo, no args)
235 # "Naked" decorator call (just @foo, no args)
236 func = arg
236 func = arg
237 name = func.__name__
237 name = func.__name__
238 ip.register_magic_function(func, magic_kind, name)
238 ip.register_magic_function(func, magic_kind, name)
239 retval = decorator(call, func)
239 retval = decorator(call, func)
240 elif isinstance(arg, str):
240 elif isinstance(arg, str):
241 # Decorator called with arguments (@foo('bar'))
241 # Decorator called with arguments (@foo('bar'))
242 name = arg
242 name = arg
243 def mark(func, *a, **kw):
243 def mark(func, *a, **kw):
244 ip.register_magic_function(func, magic_kind, name)
244 ip.register_magic_function(func, magic_kind, name)
245 return decorator(call, func)
245 return decorator(call, func)
246 retval = mark
246 retval = mark
247 else:
247 else:
248 raise TypeError("Decorator can only be called with "
248 raise TypeError("Decorator can only be called with "
249 "string or function")
249 "string or function")
250 return retval
250 return retval
251
251
252 # Ensure the resulting decorator has a usable docstring
252 # Ensure the resulting decorator has a usable docstring
253 ds = _docstring_template.format('function', magic_kind)
253 ds = _docstring_template.format('function', magic_kind)
254
254
255 ds += dedent("""
255 ds += dedent("""
256 Note: this decorator can only be used in a context where IPython is already
256 Note: this decorator can only be used in a context where IPython is already
257 active, so that the `get_ipython()` call succeeds. You can therefore use
257 active, so that the `get_ipython()` call succeeds. You can therefore use
258 it in your startup files loaded after IPython initializes, but *not* in the
258 it in your startup files loaded after IPython initializes, but *not* in the
259 IPython configuration file itself, which is executed before IPython is
259 IPython configuration file itself, which is executed before IPython is
260 fully up and running. Any file located in the `startup` subdirectory of
260 fully up and running. Any file located in the `startup` subdirectory of
261 your configuration profile will be OK in this sense.
261 your configuration profile will be OK in this sense.
262 """)
262 """)
263
263
264 magic_deco.__doc__ = ds
264 magic_deco.__doc__ = ds
265 return magic_deco
265 return magic_deco
266
266
267
267
268 MAGIC_NO_VAR_EXPAND_ATTR = '_ipython_magic_no_var_expand'
268 MAGIC_NO_VAR_EXPAND_ATTR = '_ipython_magic_no_var_expand'
269
269
270
270
271 def no_var_expand(magic_func):
271 def no_var_expand(magic_func):
272 """Mark a magic function as not needing variable expansion
272 """Mark a magic function as not needing variable expansion
273
273
274 By default, IPython interprets `{a}` or `$a` in the line passed to magics
274 By default, IPython interprets `{a}` or `$a` in the line passed to magics
275 as variables that should be interpolated from the interactive namespace
275 as variables that should be interpolated from the interactive namespace
276 before passing the line to the magic function.
276 before passing the line to the magic function.
277 This is not always desirable, e.g. when the magic executes Python code
277 This is not always desirable, e.g. when the magic executes Python code
278 (%timeit, %time, etc.).
278 (%timeit, %time, etc.).
279 Decorate magics with `@no_var_expand` to opt-out of variable expansion.
279 Decorate magics with `@no_var_expand` to opt-out of variable expansion.
280
280
281 .. versionadded:: 7.3
281 .. versionadded:: 7.3
282 """
282 """
283 setattr(magic_func, MAGIC_NO_VAR_EXPAND_ATTR, True)
283 setattr(magic_func, MAGIC_NO_VAR_EXPAND_ATTR, True)
284 return magic_func
284 return magic_func
285
285
286
286
287 # Create the actual decorators for public use
287 # Create the actual decorators for public use
288
288
289 # These three are used to decorate methods in class definitions
289 # These three are used to decorate methods in class definitions
290 line_magic = _method_magic_marker('line')
290 line_magic = _method_magic_marker('line')
291 cell_magic = _method_magic_marker('cell')
291 cell_magic = _method_magic_marker('cell')
292 line_cell_magic = _method_magic_marker('line_cell')
292 line_cell_magic = _method_magic_marker('line_cell')
293
293
294 # These three decorate standalone functions and perform the decoration
294 # These three decorate standalone functions and perform the decoration
295 # immediately. They can only run where get_ipython() works
295 # immediately. They can only run where get_ipython() works
296 register_line_magic = _function_magic_marker('line')
296 register_line_magic = _function_magic_marker('line')
297 register_cell_magic = _function_magic_marker('cell')
297 register_cell_magic = _function_magic_marker('cell')
298 register_line_cell_magic = _function_magic_marker('line_cell')
298 register_line_cell_magic = _function_magic_marker('line_cell')
299
299
300 #-----------------------------------------------------------------------------
300 #-----------------------------------------------------------------------------
301 # Core Magic classes
301 # Core Magic classes
302 #-----------------------------------------------------------------------------
302 #-----------------------------------------------------------------------------
303
303
304 class MagicsManager(Configurable):
304 class MagicsManager(Configurable):
305 """Object that handles all magic-related functionality for IPython.
305 """Object that handles all magic-related functionality for IPython.
306 """
306 """
307 # Non-configurable class attributes
307 # Non-configurable class attributes
308
308
309 # A two-level dict, first keyed by magic type, then by magic function, and
309 # A two-level dict, first keyed by magic type, then by magic function, and
310 # holding the actual callable object as value. This is the dict used for
310 # holding the actual callable object as value. This is the dict used for
311 # magic function dispatch
311 # magic function dispatch
312 magics = Dict()
312 magics = Dict()
313
313
314 # A registry of the original objects that we've been given holding magics.
314 # A registry of the original objects that we've been given holding magics.
315 registry = Dict()
315 registry = Dict()
316
316
317 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
317 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
318
318
319 auto_magic = Bool(True, help=
319 auto_magic = Bool(True, help=
320 "Automatically call line magics without requiring explicit % prefix"
320 "Automatically call line magics without requiring explicit % prefix"
321 ).tag(config=True)
321 ).tag(config=True)
322 @observe('auto_magic')
322 @observe('auto_magic')
323 def _auto_magic_changed(self, change):
323 def _auto_magic_changed(self, change):
324 self.shell.automagic = change['new']
324 self.shell.automagic = change['new']
325
325
326 _auto_status = [
326 _auto_status = [
327 'Automagic is OFF, % prefix IS needed for line magics.',
327 'Automagic is OFF, % prefix IS needed for line magics.',
328 'Automagic is ON, % prefix IS NOT needed for line magics.']
328 'Automagic is ON, % prefix IS NOT needed for line magics.']
329
329
330 user_magics = Instance('IPython.core.magics.UserMagics', allow_none=True)
330 user_magics = Instance('IPython.core.magics.UserMagics', allow_none=True)
331
331
332 def __init__(self, shell=None, config=None, user_magics=None, **traits):
332 def __init__(self, shell=None, config=None, user_magics=None, **traits):
333
333
334 super(MagicsManager, self).__init__(shell=shell, config=config,
334 super(MagicsManager, self).__init__(shell=shell, config=config,
335 user_magics=user_magics, **traits)
335 user_magics=user_magics, **traits)
336 self.magics = dict(line={}, cell={})
336 self.magics = dict(line={}, cell={})
337 # Let's add the user_magics to the registry for uniformity, so *all*
337 # Let's add the user_magics to the registry for uniformity, so *all*
338 # registered magic containers can be found there.
338 # registered magic containers can be found there.
339 self.registry[user_magics.__class__.__name__] = user_magics
339 self.registry[user_magics.__class__.__name__] = user_magics
340
340
341 def auto_status(self):
341 def auto_status(self):
342 """Return descriptive string with automagic status."""
342 """Return descriptive string with automagic status."""
343 return self._auto_status[self.auto_magic]
343 return self._auto_status[self.auto_magic]
344
344
345 def lsmagic(self):
345 def lsmagic(self):
346 """Return a dict of currently available magic functions.
346 """Return a dict of currently available magic functions.
347
347
348 The return dict has the keys 'line' and 'cell', corresponding to the
348 The return dict has the keys 'line' and 'cell', corresponding to the
349 two types of magics we support. Each value is a list of names.
349 two types of magics we support. Each value is a list of names.
350 """
350 """
351 return self.magics
351 return self.magics
352
352
353 def lsmagic_docs(self, brief=False, missing=''):
353 def lsmagic_docs(self, brief=False, missing=''):
354 """Return dict of documentation of magic functions.
354 """Return dict of documentation of magic functions.
355
355
356 The return dict has the keys 'line' and 'cell', corresponding to the
356 The return dict has the keys 'line' and 'cell', corresponding to the
357 two types of magics we support. Each value is a dict keyed by magic
357 two types of magics we support. Each value is a dict keyed by magic
358 name whose value is the function docstring. If a docstring is
358 name whose value is the function docstring. If a docstring is
359 unavailable, the value of `missing` is used instead.
359 unavailable, the value of `missing` is used instead.
360
360
361 If brief is True, only the first line of each docstring will be returned.
361 If brief is True, only the first line of each docstring will be returned.
362 """
362 """
363 docs = {}
363 docs = {}
364 for m_type in self.magics:
364 for m_type in self.magics:
365 m_docs = {}
365 m_docs = {}
366 for m_name, m_func in self.magics[m_type].items():
366 for m_name, m_func in self.magics[m_type].items():
367 if m_func.__doc__:
367 if m_func.__doc__:
368 if brief:
368 if brief:
369 m_docs[m_name] = m_func.__doc__.split('\n', 1)[0]
369 m_docs[m_name] = m_func.__doc__.split('\n', 1)[0]
370 else:
370 else:
371 m_docs[m_name] = m_func.__doc__.rstrip()
371 m_docs[m_name] = m_func.__doc__.rstrip()
372 else:
372 else:
373 m_docs[m_name] = missing
373 m_docs[m_name] = missing
374 docs[m_type] = m_docs
374 docs[m_type] = m_docs
375 return docs
375 return docs
376
376
377 def register(self, *magic_objects):
377 def register(self, *magic_objects):
378 """Register one or more instances of Magics.
378 """Register one or more instances of Magics.
379
379
380 Take one or more classes or instances of classes that subclass the main
380 Take one or more classes or instances of classes that subclass the main
381 `core.Magic` class, and register them with IPython to use the magic
381 `core.Magic` class, and register them with IPython to use the magic
382 functions they provide. The registration process will then ensure that
382 functions they provide. The registration process will then ensure that
383 any methods that have decorated to provide line and/or cell magics will
383 any methods that have decorated to provide line and/or cell magics will
384 be recognized with the `%x`/`%%x` syntax as a line/cell magic
384 be recognized with the `%x`/`%%x` syntax as a line/cell magic
385 respectively.
385 respectively.
386
386
387 If classes are given, they will be instantiated with the default
387 If classes are given, they will be instantiated with the default
388 constructor. If your classes need a custom constructor, you should
388 constructor. If your classes need a custom constructor, you should
389 instanitate them first and pass the instance.
389 instanitate them first and pass the instance.
390
390
391 The provided arguments can be an arbitrary mix of classes and instances.
391 The provided arguments can be an arbitrary mix of classes and instances.
392
392
393 Parameters
393 Parameters
394 ----------
394 ----------
395 magic_objects : one or more classes or instances
395 magic_objects : one or more classes or instances
396 """
396 """
397 # Start by validating them to ensure they have all had their magic
397 # Start by validating them to ensure they have all had their magic
398 # methods registered at the instance level
398 # methods registered at the instance level
399 for m in magic_objects:
399 for m in magic_objects:
400 if not m.registered:
400 if not m.registered:
401 raise ValueError("Class of magics %r was constructed without "
401 raise ValueError("Class of magics %r was constructed without "
402 "the @register_magics class decorator")
402 "the @register_magics class decorator")
403 if isinstance(m, type):
403 if isinstance(m, type):
404 # If we're given an uninstantiated class
404 # If we're given an uninstantiated class
405 m = m(shell=self.shell)
405 m = m(shell=self.shell)
406
406
407 # Now that we have an instance, we can register it and update the
407 # Now that we have an instance, we can register it and update the
408 # table of callables
408 # table of callables
409 self.registry[m.__class__.__name__] = m
409 self.registry[m.__class__.__name__] = m
410 for mtype in magic_kinds:
410 for mtype in magic_kinds:
411 self.magics[mtype].update(m.magics[mtype])
411 self.magics[mtype].update(m.magics[mtype])
412
412
413 def register_function(self, func, magic_kind='line', magic_name=None):
413 def register_function(self, func, magic_kind='line', magic_name=None):
414 """Expose a standalone function as magic function for IPython.
414 """Expose a standalone function as magic function for IPython.
415
415
416 This will create an IPython magic (line, cell or both) from a
416 This will create an IPython magic (line, cell or both) from a
417 standalone function. The functions should have the following
417 standalone function. The functions should have the following
418 signatures:
418 signatures:
419
419
420 * For line magics: `def f(line)`
420 * For line magics: `def f(line)`
421 * For cell magics: `def f(line, cell)`
421 * For cell magics: `def f(line, cell)`
422 * For a function that does both: `def f(line, cell=None)`
422 * For a function that does both: `def f(line, cell=None)`
423
423
424 In the latter case, the function will be called with `cell==None` when
424 In the latter case, the function will be called with `cell==None` when
425 invoked as `%f`, and with cell as a string when invoked as `%%f`.
425 invoked as `%f`, and with cell as a string when invoked as `%%f`.
426
426
427 Parameters
427 Parameters
428 ----------
428 ----------
429 func : callable
429 func : callable
430 Function to be registered as a magic.
430 Function to be registered as a magic.
431
431
432 magic_kind : str
432 magic_kind : str
433 Kind of magic, one of 'line', 'cell' or 'line_cell'
433 Kind of magic, one of 'line', 'cell' or 'line_cell'
434
434
435 magic_name : optional str
435 magic_name : optional str
436 If given, the name the magic will have in the IPython namespace. By
436 If given, the name the magic will have in the IPython namespace. By
437 default, the name of the function itself is used.
437 default, the name of the function itself is used.
438 """
438 """
439
439
440 # Create the new method in the user_magics and register it in the
440 # Create the new method in the user_magics and register it in the
441 # global table
441 # global table
442 validate_type(magic_kind)
442 validate_type(magic_kind)
443 magic_name = func.__name__ if magic_name is None else magic_name
443 magic_name = func.__name__ if magic_name is None else magic_name
444 setattr(self.user_magics, magic_name, func)
444 setattr(self.user_magics, magic_name, func)
445 record_magic(self.magics, magic_kind, magic_name, func)
445 record_magic(self.magics, magic_kind, magic_name, func)
446
446
447 def register_alias(self, alias_name, magic_name, magic_kind='line', magic_params=None):
447 def register_alias(self, alias_name, magic_name, magic_kind='line', magic_params=None):
448 """Register an alias to a magic function.
448 """Register an alias to a magic function.
449
449
450 The alias is an instance of :class:`MagicAlias`, which holds the
450 The alias is an instance of :class:`MagicAlias`, which holds the
451 name and kind of the magic it should call. Binding is done at
451 name and kind of the magic it should call. Binding is done at
452 call time, so if the underlying magic function is changed the alias
452 call time, so if the underlying magic function is changed the alias
453 will call the new function.
453 will call the new function.
454
454
455 Parameters
455 Parameters
456 ----------
456 ----------
457 alias_name : str
457 alias_name : str
458 The name of the magic to be registered.
458 The name of the magic to be registered.
459
459
460 magic_name : str
460 magic_name : str
461 The name of an existing magic.
461 The name of an existing magic.
462
462
463 magic_kind : str
463 magic_kind : str
464 Kind of magic, one of 'line' or 'cell'
464 Kind of magic, one of 'line' or 'cell'
465 """
465 """
466
466
467 # `validate_type` is too permissive, as it allows 'line_cell'
467 # `validate_type` is too permissive, as it allows 'line_cell'
468 # which we do not handle.
468 # which we do not handle.
469 if magic_kind not in magic_kinds:
469 if magic_kind not in magic_kinds:
470 raise ValueError('magic_kind must be one of %s, %s given' %
470 raise ValueError('magic_kind must be one of %s, %s given' %
471 magic_kinds, magic_kind)
471 magic_kinds, magic_kind)
472
472
473 alias = MagicAlias(self.shell, magic_name, magic_kind, magic_params)
473 alias = MagicAlias(self.shell, magic_name, magic_kind, magic_params)
474 setattr(self.user_magics, alias_name, alias)
474 setattr(self.user_magics, alias_name, alias)
475 record_magic(self.magics, magic_kind, alias_name, alias)
475 record_magic(self.magics, magic_kind, alias_name, alias)
476
476
477 # Key base class that provides the central functionality for magics.
477 # Key base class that provides the central functionality for magics.
478
478
479
479
480 class Magics(Configurable):
480 class Magics(Configurable):
481 """Base class for implementing magic functions.
481 """Base class for implementing magic functions.
482
482
483 Shell functions which can be reached as %function_name. All magic
483 Shell functions which can be reached as %function_name. All magic
484 functions should accept a string, which they can parse for their own
484 functions should accept a string, which they can parse for their own
485 needs. This can make some functions easier to type, eg `%cd ../`
485 needs. This can make some functions easier to type, eg `%cd ../`
486 vs. `%cd("../")`
486 vs. `%cd("../")`
487
487
488 Classes providing magic functions need to subclass this class, and they
488 Classes providing magic functions need to subclass this class, and they
489 MUST:
489 MUST:
490
490
491 - Use the method decorators `@line_magic` and `@cell_magic` to decorate
491 - Use the method decorators `@line_magic` and `@cell_magic` to decorate
492 individual methods as magic functions, AND
492 individual methods as magic functions, AND
493
493
494 - Use the class decorator `@magics_class` to ensure that the magic
494 - Use the class decorator `@magics_class` to ensure that the magic
495 methods are properly registered at the instance level upon instance
495 methods are properly registered at the instance level upon instance
496 initialization.
496 initialization.
497
497
498 See :mod:`magic_functions` for examples of actual implementation classes.
498 See :mod:`magic_functions` for examples of actual implementation classes.
499 """
499 """
500 # Dict holding all command-line options for each magic.
500 # Dict holding all command-line options for each magic.
501 options_table = None
501 options_table = None
502 # Dict for the mapping of magic names to methods, set by class decorator
502 # Dict for the mapping of magic names to methods, set by class decorator
503 magics = None
503 magics = None
504 # Flag to check that the class decorator was properly applied
504 # Flag to check that the class decorator was properly applied
505 registered = False
505 registered = False
506 # Instance of IPython shell
506 # Instance of IPython shell
507 shell = None
507 shell = None
508
508
509 def __init__(self, shell=None, **kwargs):
509 def __init__(self, shell=None, **kwargs):
510 if not(self.__class__.registered):
510 if not(self.__class__.registered):
511 raise ValueError('Magics subclass without registration - '
511 raise ValueError('Magics subclass without registration - '
512 'did you forget to apply @magics_class?')
512 'did you forget to apply @magics_class?')
513 if shell is not None:
513 if shell is not None:
514 if hasattr(shell, 'configurables'):
514 if hasattr(shell, 'configurables'):
515 shell.configurables.append(self)
515 shell.configurables.append(self)
516 if hasattr(shell, 'config'):
516 if hasattr(shell, 'config'):
517 kwargs.setdefault('parent', shell)
517 kwargs.setdefault('parent', shell)
518
518
519 self.shell = shell
519 self.shell = shell
520 self.options_table = {}
520 self.options_table = {}
521 # The method decorators are run when the instance doesn't exist yet, so
521 # The method decorators are run when the instance doesn't exist yet, so
522 # they can only record the names of the methods they are supposed to
522 # they can only record the names of the methods they are supposed to
523 # grab. Only now, that the instance exists, can we create the proper
523 # grab. Only now, that the instance exists, can we create the proper
524 # mapping to bound methods. So we read the info off the original names
524 # mapping to bound methods. So we read the info off the original names
525 # table and replace each method name by the actual bound method.
525 # table and replace each method name by the actual bound method.
526 # But we mustn't clobber the *class* mapping, in case of multiple instances.
526 # But we mustn't clobber the *class* mapping, in case of multiple instances.
527 class_magics = self.magics
527 class_magics = self.magics
528 self.magics = {}
528 self.magics = {}
529 for mtype in magic_kinds:
529 for mtype in magic_kinds:
530 tab = self.magics[mtype] = {}
530 tab = self.magics[mtype] = {}
531 cls_tab = class_magics[mtype]
531 cls_tab = class_magics[mtype]
532 for magic_name, meth_name in cls_tab.items():
532 for magic_name, meth_name in cls_tab.items():
533 if isinstance(meth_name, str):
533 if isinstance(meth_name, str):
534 # it's a method name, grab it
534 # it's a method name, grab it
535 tab[magic_name] = getattr(self, meth_name)
535 tab[magic_name] = getattr(self, meth_name)
536 else:
536 else:
537 # it's the real thing
537 # it's the real thing
538 tab[magic_name] = meth_name
538 tab[magic_name] = meth_name
539 # Configurable **needs** to be initiated at the end or the config
539 # Configurable **needs** to be initiated at the end or the config
540 # magics get screwed up.
540 # magics get screwed up.
541 super(Magics, self).__init__(**kwargs)
541 super(Magics, self).__init__(**kwargs)
542
542
543 def arg_err(self,func):
543 def arg_err(self,func):
544 """Print docstring if incorrect arguments were passed"""
544 """Print docstring if incorrect arguments were passed"""
545 print('Error in arguments:')
545 print('Error in arguments:')
546 print(oinspect.getdoc(func))
546 print(oinspect.getdoc(func))
547
547
548 def format_latex(self, strng):
548 def format_latex(self, strng):
549 """Format a string for latex inclusion."""
549 """Format a string for latex inclusion."""
550
550
551 # Characters that need to be escaped for latex:
551 # Characters that need to be escaped for latex:
552 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
552 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
553 # Magic command names as headers:
553 # Magic command names as headers:
554 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
554 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
555 re.MULTILINE)
555 re.MULTILINE)
556 # Magic commands
556 # Magic commands
557 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
557 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
558 re.MULTILINE)
558 re.MULTILINE)
559 # Paragraph continue
559 # Paragraph continue
560 par_re = re.compile(r'\\$',re.MULTILINE)
560 par_re = re.compile(r'\\$',re.MULTILINE)
561
561
562 # The "\n" symbol
562 # The "\n" symbol
563 newline_re = re.compile(r'\\n')
563 newline_re = re.compile(r'\\n')
564
564
565 # Now build the string for output:
565 # Now build the string for output:
566 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
566 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
567 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
567 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
568 strng)
568 strng)
569 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
569 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
570 strng = par_re.sub(r'\\\\',strng)
570 strng = par_re.sub(r'\\\\',strng)
571 strng = escape_re.sub(r'\\\1',strng)
571 strng = escape_re.sub(r'\\\1',strng)
572 strng = newline_re.sub(r'\\textbackslash{}n',strng)
572 strng = newline_re.sub(r'\\textbackslash{}n',strng)
573 return strng
573 return strng
574
574
575 def parse_options(self, arg_str, opt_str, *long_opts, **kw):
575 def parse_options(self, arg_str, opt_str, *long_opts, **kw):
576 """Parse options passed to an argument string.
576 """Parse options passed to an argument string.
577
577
578 The interface is similar to that of :func:`getopt.getopt`, but it
578 The interface is similar to that of :func:`getopt.getopt`, but it
579 returns a :class:`~IPython.utils.struct.Struct` with the options as keys
579 returns a :class:`~IPython.utils.struct.Struct` with the options as keys
580 and the stripped argument string still as a string.
580 and the stripped argument string still as a string.
581
581
582 arg_str is quoted as a true sys.argv vector by using shlex.split.
582 arg_str is quoted as a true sys.argv vector by using shlex.split.
583 This allows us to easily expand variables, glob files, quote
583 This allows us to easily expand variables, glob files, quote
584 arguments, etc.
584 arguments, etc.
585
585
586 Parameters
586 Parameters
587 ----------
587 ----------
588
588
589 arg_str : str
589 arg_str : str
590 The arguments to parse.
590 The arguments to parse.
591
591
592 opt_str : str
592 opt_str : str
593 The options specification.
593 The options specification.
594
594
595 mode : str, default 'string'
595 mode : str, default 'string'
596 If given as 'list', the argument string is returned as a list (split
596 If given as 'list', the argument string is returned as a list (split
597 on whitespace) instead of a string.
597 on whitespace) instead of a string.
598
598
599 list_all : bool, default False
599 list_all : bool, default False
600 Put all option values in lists. Normally only options
600 Put all option values in lists. Normally only options
601 appearing more than once are put in a list.
601 appearing more than once are put in a list.
602
602
603 posix : bool, default True
603 posix : bool, default True
604 Whether to split the input line in POSIX mode or not, as per the
604 Whether to split the input line in POSIX mode or not, as per the
605 conventions outlined in the :mod:`shlex` module from the standard
605 conventions outlined in the :mod:`shlex` module from the standard
606 library.
606 library.
607 """
607 """
608
608
609 # inject default options at the beginning of the input line
609 # inject default options at the beginning of the input line
610 caller = sys._getframe(1).f_code.co_name
610 caller = sys._getframe(1).f_code.co_name
611 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
611 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
612
612
613 mode = kw.get('mode','string')
613 mode = kw.get('mode','string')
614 if mode not in ['string','list']:
614 if mode not in ['string','list']:
615 raise ValueError('incorrect mode given: %s' % mode)
615 raise ValueError('incorrect mode given: %s' % mode)
616 # Get options
616 # Get options
617 list_all = kw.get('list_all',0)
617 list_all = kw.get('list_all',0)
618 posix = kw.get('posix', os.name == 'posix')
618 posix = kw.get('posix', os.name == 'posix')
619 strict = kw.get('strict', True)
619 strict = kw.get('strict', True)
620
620
621 preserve_non_opts = kw.get("preserve_non_opts", False)
621 preserve_non_opts = kw.get("preserve_non_opts", False)
622 remainder_arg_str = arg_str
622 remainder_arg_str = arg_str
623
623
624 # Check if we have more than one argument to warrant extra processing:
624 # Check if we have more than one argument to warrant extra processing:
625 odict = {} # Dictionary with options
625 odict = {} # Dictionary with options
626 args = arg_str.split()
626 args = arg_str.split()
627 if len(args) >= 1:
627 if len(args) >= 1:
628 # If the list of inputs only has 0 or 1 thing in it, there's no
628 # If the list of inputs only has 0 or 1 thing in it, there's no
629 # need to look for options
629 # need to look for options
630 argv = arg_split(arg_str, posix, strict)
630 argv = arg_split(arg_str, posix, strict)
631 # Do regular option processing
631 # Do regular option processing
632 try:
632 try:
633 opts,args = getopt(argv, opt_str, long_opts)
633 opts,args = getopt(argv, opt_str, long_opts)
634 except GetoptError as e:
634 except GetoptError as e:
635 raise UsageError(
635 raise UsageError(
636 '%s ( allowed: "%s" %s)' % (e.msg, opt_str, " ".join(long_opts))
636 '%s ( allowed: "%s" %s)' % (e.msg, opt_str, " ".join(long_opts))
637 ) from e
637 ) from e
638 for o, a in opts:
638 for o, a in opts:
639 if mode is "string" and preserve_non_opts:
639 if mode == "string" and preserve_non_opts:
640 # remove option-parts from the original args-string and preserve remaining-part.
640 # remove option-parts from the original args-string and preserve remaining-part.
641 # This relies on the arg_split(...) and getopt(...)'s impl spec, that the parsed options are
641 # This relies on the arg_split(...) and getopt(...)'s impl spec, that the parsed options are
642 # returned in the original order.
642 # returned in the original order.
643 remainder_arg_str = remainder_arg_str.replace(o, "", 1).replace(
643 remainder_arg_str = remainder_arg_str.replace(o, "", 1).replace(
644 a, "", 1
644 a, "", 1
645 )
645 )
646 if o.startswith("--"):
646 if o.startswith("--"):
647 o = o[2:]
647 o = o[2:]
648 else:
648 else:
649 o = o[1:]
649 o = o[1:]
650 try:
650 try:
651 odict[o].append(a)
651 odict[o].append(a)
652 except AttributeError:
652 except AttributeError:
653 odict[o] = [odict[o],a]
653 odict[o] = [odict[o],a]
654 except KeyError:
654 except KeyError:
655 if list_all:
655 if list_all:
656 odict[o] = [a]
656 odict[o] = [a]
657 else:
657 else:
658 odict[o] = a
658 odict[o] = a
659
659
660 # Prepare opts,args for return
660 # Prepare opts,args for return
661 opts = Struct(odict)
661 opts = Struct(odict)
662 if mode == 'string':
662 if mode == 'string':
663 if preserve_non_opts:
663 if preserve_non_opts:
664 args = remainder_arg_str.lstrip()
664 args = remainder_arg_str.lstrip()
665 else:
665 else:
666 args = " ".join(args)
666 args = " ".join(args)
667
667
668 return opts,args
668 return opts,args
669
669
670 def default_option(self, fn, optstr):
670 def default_option(self, fn, optstr):
671 """Make an entry in the options_table for fn, with value optstr"""
671 """Make an entry in the options_table for fn, with value optstr"""
672
672
673 if fn not in self.lsmagic():
673 if fn not in self.lsmagic():
674 error("%s is not a magic function" % fn)
674 error("%s is not a magic function" % fn)
675 self.options_table[fn] = optstr
675 self.options_table[fn] = optstr
676
676
677
677
678 class MagicAlias(object):
678 class MagicAlias(object):
679 """An alias to another magic function.
679 """An alias to another magic function.
680
680
681 An alias is determined by its magic name and magic kind. Lookup
681 An alias is determined by its magic name and magic kind. Lookup
682 is done at call time, so if the underlying magic changes the alias
682 is done at call time, so if the underlying magic changes the alias
683 will call the new function.
683 will call the new function.
684
684
685 Use the :meth:`MagicsManager.register_alias` method or the
685 Use the :meth:`MagicsManager.register_alias` method or the
686 `%alias_magic` magic function to create and register a new alias.
686 `%alias_magic` magic function to create and register a new alias.
687 """
687 """
688 def __init__(self, shell, magic_name, magic_kind, magic_params=None):
688 def __init__(self, shell, magic_name, magic_kind, magic_params=None):
689 self.shell = shell
689 self.shell = shell
690 self.magic_name = magic_name
690 self.magic_name = magic_name
691 self.magic_params = magic_params
691 self.magic_params = magic_params
692 self.magic_kind = magic_kind
692 self.magic_kind = magic_kind
693
693
694 self.pretty_target = '%s%s' % (magic_escapes[self.magic_kind], self.magic_name)
694 self.pretty_target = '%s%s' % (magic_escapes[self.magic_kind], self.magic_name)
695 self.__doc__ = "Alias for `%s`." % self.pretty_target
695 self.__doc__ = "Alias for `%s`." % self.pretty_target
696
696
697 self._in_call = False
697 self._in_call = False
698
698
699 def __call__(self, *args, **kwargs):
699 def __call__(self, *args, **kwargs):
700 """Call the magic alias."""
700 """Call the magic alias."""
701 fn = self.shell.find_magic(self.magic_name, self.magic_kind)
701 fn = self.shell.find_magic(self.magic_name, self.magic_kind)
702 if fn is None:
702 if fn is None:
703 raise UsageError("Magic `%s` not found." % self.pretty_target)
703 raise UsageError("Magic `%s` not found." % self.pretty_target)
704
704
705 # Protect against infinite recursion.
705 # Protect against infinite recursion.
706 if self._in_call:
706 if self._in_call:
707 raise UsageError("Infinite recursion detected; "
707 raise UsageError("Infinite recursion detected; "
708 "magic aliases cannot call themselves.")
708 "magic aliases cannot call themselves.")
709 self._in_call = True
709 self._in_call = True
710 try:
710 try:
711 if self.magic_params:
711 if self.magic_params:
712 args_list = list(args)
712 args_list = list(args)
713 args_list[0] = self.magic_params + " " + args[0]
713 args_list[0] = self.magic_params + " " + args[0]
714 args = tuple(args_list)
714 args = tuple(args_list)
715 return fn(*args, **kwargs)
715 return fn(*args, **kwargs)
716 finally:
716 finally:
717 self._in_call = False
717 self._in_call = False
@@ -1,399 +1,397 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """
2 """
3 An embedded IPython shell.
3 An embedded IPython shell.
4 """
4 """
5 # Copyright (c) IPython Development Team.
5 # Copyright (c) IPython Development Team.
6 # Distributed under the terms of the Modified BSD License.
6 # Distributed under the terms of the Modified BSD License.
7
7
8
8
9 import sys
9 import sys
10 import warnings
10 import warnings
11
11
12 from IPython.core import ultratb, compilerop
12 from IPython.core import ultratb, compilerop
13 from IPython.core import magic_arguments
13 from IPython.core import magic_arguments
14 from IPython.core.magic import Magics, magics_class, line_magic
14 from IPython.core.magic import Magics, magics_class, line_magic
15 from IPython.core.interactiveshell import DummyMod, InteractiveShell
15 from IPython.core.interactiveshell import DummyMod, InteractiveShell
16 from IPython.terminal.interactiveshell import TerminalInteractiveShell
16 from IPython.terminal.interactiveshell import TerminalInteractiveShell
17 from IPython.terminal.ipapp import load_default_config
17 from IPython.terminal.ipapp import load_default_config
18
18
19 from traitlets import Bool, CBool, Unicode
19 from traitlets import Bool, CBool, Unicode
20 from IPython.utils.io import ask_yes_no
20 from IPython.utils.io import ask_yes_no
21
21
22 class KillEmbedded(Exception):pass
22 class KillEmbedded(Exception):pass
23
23
24 # kept for backward compatibility as IPython 6 was released with
24 # kept for backward compatibility as IPython 6 was released with
25 # the typo. See https://github.com/ipython/ipython/pull/10706
25 # the typo. See https://github.com/ipython/ipython/pull/10706
26 KillEmbeded = KillEmbedded
26 KillEmbeded = KillEmbedded
27
27
28 # This is an additional magic that is exposed in embedded shells.
28 # This is an additional magic that is exposed in embedded shells.
29 @magics_class
29 @magics_class
30 class EmbeddedMagics(Magics):
30 class EmbeddedMagics(Magics):
31
31
32 @line_magic
32 @line_magic
33 @magic_arguments.magic_arguments()
33 @magic_arguments.magic_arguments()
34 @magic_arguments.argument('-i', '--instance', action='store_true',
34 @magic_arguments.argument('-i', '--instance', action='store_true',
35 help='Kill instance instead of call location')
35 help='Kill instance instead of call location')
36 @magic_arguments.argument('-x', '--exit', action='store_true',
36 @magic_arguments.argument('-x', '--exit', action='store_true',
37 help='Also exit the current session')
37 help='Also exit the current session')
38 @magic_arguments.argument('-y', '--yes', action='store_true',
38 @magic_arguments.argument('-y', '--yes', action='store_true',
39 help='Do not ask confirmation')
39 help='Do not ask confirmation')
40 def kill_embedded(self, parameter_s=''):
40 def kill_embedded(self, parameter_s=''):
41 """%kill_embedded : deactivate for good the current embedded IPython
41 """%kill_embedded : deactivate for good the current embedded IPython
42
42
43 This function (after asking for confirmation) sets an internal flag so
43 This function (after asking for confirmation) sets an internal flag so
44 that an embedded IPython will never activate again for the given call
44 that an embedded IPython will never activate again for the given call
45 location. This is useful to permanently disable a shell that is being
45 location. This is useful to permanently disable a shell that is being
46 called inside a loop: once you've figured out what you needed from it,
46 called inside a loop: once you've figured out what you needed from it,
47 you may then kill it and the program will then continue to run without
47 you may then kill it and the program will then continue to run without
48 the interactive shell interfering again.
48 the interactive shell interfering again.
49
49
50
50
51 Kill Instance Option:
51 Kill Instance Option:
52
52
53 If for some reasons you need to kill the location where the instance
53 If for some reasons you need to kill the location where the instance
54 is created and not called, for example if you create a single
54 is created and not called, for example if you create a single
55 instance in one place and debug in many locations, you can use the
55 instance in one place and debug in many locations, you can use the
56 ``--instance`` option to kill this specific instance. Like for the
56 ``--instance`` option to kill this specific instance. Like for the
57 ``call location`` killing an "instance" should work even if it is
57 ``call location`` killing an "instance" should work even if it is
58 recreated within a loop.
58 recreated within a loop.
59
59
60 .. note::
60 .. note::
61
61
62 This was the default behavior before IPython 5.2
62 This was the default behavior before IPython 5.2
63
63
64 """
64 """
65
65
66 args = magic_arguments.parse_argstring(self.kill_embedded, parameter_s)
66 args = magic_arguments.parse_argstring(self.kill_embedded, parameter_s)
67 print(args)
67 print(args)
68 if args.instance:
68 if args.instance:
69 # let no ask
69 # let no ask
70 if not args.yes:
70 if not args.yes:
71 kill = ask_yes_no(
71 kill = ask_yes_no(
72 "Are you sure you want to kill this embedded instance? [y/N] ", 'n')
72 "Are you sure you want to kill this embedded instance? [y/N] ", 'n')
73 else:
73 else:
74 kill = True
74 kill = True
75 if kill:
75 if kill:
76 self.shell._disable_init_location()
76 self.shell._disable_init_location()
77 print("This embedded IPython instance will not reactivate anymore "
77 print("This embedded IPython instance will not reactivate anymore "
78 "once you exit.")
78 "once you exit.")
79 else:
79 else:
80 if not args.yes:
80 if not args.yes:
81 kill = ask_yes_no(
81 kill = ask_yes_no(
82 "Are you sure you want to kill this embedded call_location? [y/N] ", 'n')
82 "Are you sure you want to kill this embedded call_location? [y/N] ", 'n')
83 else:
83 else:
84 kill = True
84 kill = True
85 if kill:
85 if kill:
86 self.shell.embedded_active = False
86 self.shell.embedded_active = False
87 print("This embedded IPython call location will not reactivate anymore "
87 print("This embedded IPython call location will not reactivate anymore "
88 "once you exit.")
88 "once you exit.")
89
89
90 if args.exit:
90 if args.exit:
91 # Ask-exit does not really ask, it just set internals flags to exit
91 # Ask-exit does not really ask, it just set internals flags to exit
92 # on next loop.
92 # on next loop.
93 self.shell.ask_exit()
93 self.shell.ask_exit()
94
94
95
95
96 @line_magic
96 @line_magic
97 def exit_raise(self, parameter_s=''):
97 def exit_raise(self, parameter_s=''):
98 """%exit_raise Make the current embedded kernel exit and raise and exception.
98 """%exit_raise Make the current embedded kernel exit and raise and exception.
99
99
100 This function sets an internal flag so that an embedded IPython will
100 This function sets an internal flag so that an embedded IPython will
101 raise a `IPython.terminal.embed.KillEmbedded` Exception on exit, and then exit the current I. This is
101 raise a `IPython.terminal.embed.KillEmbedded` Exception on exit, and then exit the current I. This is
102 useful to permanently exit a loop that create IPython embed instance.
102 useful to permanently exit a loop that create IPython embed instance.
103 """
103 """
104
104
105 self.shell.should_raise = True
105 self.shell.should_raise = True
106 self.shell.ask_exit()
106 self.shell.ask_exit()
107
107
108
108
109
109
110 class InteractiveShellEmbed(TerminalInteractiveShell):
110 class InteractiveShellEmbed(TerminalInteractiveShell):
111
111
112 dummy_mode = Bool(False)
112 dummy_mode = Bool(False)
113 exit_msg = Unicode('')
113 exit_msg = Unicode('')
114 embedded = CBool(True)
114 embedded = CBool(True)
115 should_raise = CBool(False)
115 should_raise = CBool(False)
116 # Like the base class display_banner is not configurable, but here it
116 # Like the base class display_banner is not configurable, but here it
117 # is True by default.
117 # is True by default.
118 display_banner = CBool(True)
118 display_banner = CBool(True)
119 exit_msg = Unicode()
119 exit_msg = Unicode()
120
120
121 # When embedding, by default we don't change the terminal title
121 # When embedding, by default we don't change the terminal title
122 term_title = Bool(False,
122 term_title = Bool(False,
123 help="Automatically set the terminal title"
123 help="Automatically set the terminal title"
124 ).tag(config=True)
124 ).tag(config=True)
125
125
126 _inactive_locations = set()
126 _inactive_locations = set()
127
127
128 @property
128 @property
129 def embedded_active(self):
129 def embedded_active(self):
130 return (self._call_location_id not in InteractiveShellEmbed._inactive_locations)\
130 return (self._call_location_id not in InteractiveShellEmbed._inactive_locations)\
131 and (self._init_location_id not in InteractiveShellEmbed._inactive_locations)
131 and (self._init_location_id not in InteractiveShellEmbed._inactive_locations)
132
132
133 def _disable_init_location(self):
133 def _disable_init_location(self):
134 """Disable the current Instance creation location"""
134 """Disable the current Instance creation location"""
135 InteractiveShellEmbed._inactive_locations.add(self._init_location_id)
135 InteractiveShellEmbed._inactive_locations.add(self._init_location_id)
136
136
137 @embedded_active.setter
137 @embedded_active.setter
138 def embedded_active(self, value):
138 def embedded_active(self, value):
139 if value:
139 if value:
140 InteractiveShellEmbed._inactive_locations.discard(
140 InteractiveShellEmbed._inactive_locations.discard(
141 self._call_location_id)
141 self._call_location_id)
142 InteractiveShellEmbed._inactive_locations.discard(
142 InteractiveShellEmbed._inactive_locations.discard(
143 self._init_location_id)
143 self._init_location_id)
144 else:
144 else:
145 InteractiveShellEmbed._inactive_locations.add(
145 InteractiveShellEmbed._inactive_locations.add(
146 self._call_location_id)
146 self._call_location_id)
147
147
148 def __init__(self, **kw):
148 def __init__(self, **kw):
149 if kw.get('user_global_ns', None) is not None:
149 if kw.get('user_global_ns', None) is not None:
150 raise DeprecationWarning(
150 raise DeprecationWarning(
151 "Key word argument `user_global_ns` has been replaced by `user_module` since IPython 4.0.")
151 "Key word argument `user_global_ns` has been replaced by `user_module` since IPython 4.0.")
152
152
153 clid = kw.pop('_init_location_id', None)
153 clid = kw.pop('_init_location_id', None)
154 if not clid:
154 if not clid:
155 frame = sys._getframe(1)
155 frame = sys._getframe(1)
156 clid = '%s:%s' % (frame.f_code.co_filename, frame.f_lineno)
156 clid = '%s:%s' % (frame.f_code.co_filename, frame.f_lineno)
157 self._init_location_id = clid
157 self._init_location_id = clid
158
158
159 super(InteractiveShellEmbed,self).__init__(**kw)
159 super(InteractiveShellEmbed,self).__init__(**kw)
160
160
161 # don't use the ipython crash handler so that user exceptions aren't
161 # don't use the ipython crash handler so that user exceptions aren't
162 # trapped
162 # trapped
163 sys.excepthook = ultratb.FormattedTB(color_scheme=self.colors,
163 sys.excepthook = ultratb.FormattedTB(color_scheme=self.colors,
164 mode=self.xmode,
164 mode=self.xmode,
165 call_pdb=self.pdb)
165 call_pdb=self.pdb)
166
166
167 def init_sys_modules(self):
167 def init_sys_modules(self):
168 """
168 """
169 Explicitly overwrite :mod:`IPython.core.interactiveshell` to do nothing.
169 Explicitly overwrite :mod:`IPython.core.interactiveshell` to do nothing.
170 """
170 """
171 pass
171 pass
172
172
173 def init_magics(self):
173 def init_magics(self):
174 super(InteractiveShellEmbed, self).init_magics()
174 super(InteractiveShellEmbed, self).init_magics()
175 self.register_magics(EmbeddedMagics)
175 self.register_magics(EmbeddedMagics)
176
176
177 def __call__(self, header='', local_ns=None, module=None, dummy=None,
177 def __call__(self, header='', local_ns=None, module=None, dummy=None,
178 stack_depth=1, global_ns=None, compile_flags=None, **kw):
178 stack_depth=1, global_ns=None, compile_flags=None, **kw):
179 """Activate the interactive interpreter.
179 """Activate the interactive interpreter.
180
180
181 __call__(self,header='',local_ns=None,module=None,dummy=None) -> Start
181 __call__(self,header='',local_ns=None,module=None,dummy=None) -> Start
182 the interpreter shell with the given local and global namespaces, and
182 the interpreter shell with the given local and global namespaces, and
183 optionally print a header string at startup.
183 optionally print a header string at startup.
184
184
185 The shell can be globally activated/deactivated using the
185 The shell can be globally activated/deactivated using the
186 dummy_mode attribute. This allows you to turn off a shell used
186 dummy_mode attribute. This allows you to turn off a shell used
187 for debugging globally.
187 for debugging globally.
188
188
189 However, *each* time you call the shell you can override the current
189 However, *each* time you call the shell you can override the current
190 state of dummy_mode with the optional keyword parameter 'dummy'. For
190 state of dummy_mode with the optional keyword parameter 'dummy'. For
191 example, if you set dummy mode on with IPShell.dummy_mode = True, you
191 example, if you set dummy mode on with IPShell.dummy_mode = True, you
192 can still have a specific call work by making it as IPShell(dummy=False).
192 can still have a specific call work by making it as IPShell(dummy=False).
193 """
193 """
194
194
195 # we are called, set the underlying interactiveshell not to exit.
195 # we are called, set the underlying interactiveshell not to exit.
196 self.keep_running = True
196 self.keep_running = True
197
197
198 # If the user has turned it off, go away
198 # If the user has turned it off, go away
199 clid = kw.pop('_call_location_id', None)
199 clid = kw.pop('_call_location_id', None)
200 if not clid:
200 if not clid:
201 frame = sys._getframe(1)
201 frame = sys._getframe(1)
202 clid = '%s:%s' % (frame.f_code.co_filename, frame.f_lineno)
202 clid = '%s:%s' % (frame.f_code.co_filename, frame.f_lineno)
203 self._call_location_id = clid
203 self._call_location_id = clid
204
204
205 if not self.embedded_active:
205 if not self.embedded_active:
206 return
206 return
207
207
208 # Normal exits from interactive mode set this flag, so the shell can't
208 # Normal exits from interactive mode set this flag, so the shell can't
209 # re-enter (it checks this variable at the start of interactive mode).
209 # re-enter (it checks this variable at the start of interactive mode).
210 self.exit_now = False
210 self.exit_now = False
211
211
212 # Allow the dummy parameter to override the global __dummy_mode
212 # Allow the dummy parameter to override the global __dummy_mode
213 if dummy or (dummy != 0 and self.dummy_mode):
213 if dummy or (dummy != 0 and self.dummy_mode):
214 return
214 return
215
215
216 # self.banner is auto computed
216 # self.banner is auto computed
217 if header:
217 if header:
218 self.old_banner2 = self.banner2
218 self.old_banner2 = self.banner2
219 self.banner2 = self.banner2 + '\n' + header + '\n'
219 self.banner2 = self.banner2 + '\n' + header + '\n'
220 else:
220 else:
221 self.old_banner2 = ''
221 self.old_banner2 = ''
222
222
223 if self.display_banner:
223 if self.display_banner:
224 self.show_banner()
224 self.show_banner()
225
225
226 # Call the embedding code with a stack depth of 1 so it can skip over
226 # Call the embedding code with a stack depth of 1 so it can skip over
227 # our call and get the original caller's namespaces.
227 # our call and get the original caller's namespaces.
228 self.mainloop(local_ns, module, stack_depth=stack_depth,
228 self.mainloop(local_ns, module, stack_depth=stack_depth,
229 global_ns=global_ns, compile_flags=compile_flags)
229 global_ns=global_ns, compile_flags=compile_flags)
230
230
231 self.banner2 = self.old_banner2
231 self.banner2 = self.old_banner2
232
232
233 if self.exit_msg is not None:
233 if self.exit_msg is not None:
234 print(self.exit_msg)
234 print(self.exit_msg)
235
235
236 if self.should_raise:
236 if self.should_raise:
237 raise KillEmbedded('Embedded IPython raising error, as user requested.')
237 raise KillEmbedded('Embedded IPython raising error, as user requested.')
238
238
239
239
240 def mainloop(self, local_ns=None, module=None, stack_depth=0,
240 def mainloop(self, local_ns=None, module=None, stack_depth=0,
241 display_banner=None, global_ns=None, compile_flags=None):
241 display_banner=None, global_ns=None, compile_flags=None):
242 """Embeds IPython into a running python program.
242 """Embeds IPython into a running python program.
243
243
244 Parameters
244 Parameters
245 ----------
245 ----------
246
246
247 local_ns, module
247 local_ns, module
248 Working local namespace (a dict) and module (a module or similar
248 Working local namespace (a dict) and module (a module or similar
249 object). If given as None, they are automatically taken from the scope
249 object). If given as None, they are automatically taken from the scope
250 where the shell was called, so that program variables become visible.
250 where the shell was called, so that program variables become visible.
251
251
252 stack_depth : int
252 stack_depth : int
253 How many levels in the stack to go to looking for namespaces (when
253 How many levels in the stack to go to looking for namespaces (when
254 local_ns or module is None). This allows an intermediate caller to
254 local_ns or module is None). This allows an intermediate caller to
255 make sure that this function gets the namespace from the intended
255 make sure that this function gets the namespace from the intended
256 level in the stack. By default (0) it will get its locals and globals
256 level in the stack. By default (0) it will get its locals and globals
257 from the immediate caller.
257 from the immediate caller.
258
258
259 compile_flags
259 compile_flags
260 A bit field identifying the __future__ features
260 A bit field identifying the __future__ features
261 that are enabled, as passed to the builtin :func:`compile` function.
261 that are enabled, as passed to the builtin :func:`compile` function.
262 If given as None, they are automatically taken from the scope where
262 If given as None, they are automatically taken from the scope where
263 the shell was called.
263 the shell was called.
264
264
265 """
265 """
266
266
267 if (global_ns is not None) and (module is None):
267 if (global_ns is not None) and (module is None):
268 raise DeprecationWarning("'global_ns' keyword argument is deprecated, and has been removed in IPython 5.0 use `module` keyword argument instead.")
268 raise DeprecationWarning("'global_ns' keyword argument is deprecated, and has been removed in IPython 5.0 use `module` keyword argument instead.")
269
269
270 if (display_banner is not None):
270 if (display_banner is not None):
271 warnings.warn("The display_banner parameter is deprecated since IPython 4.0", DeprecationWarning)
271 warnings.warn("The display_banner parameter is deprecated since IPython 4.0", DeprecationWarning)
272
272
273 # Get locals and globals from caller
273 # Get locals and globals from caller
274 if ((local_ns is None or module is None or compile_flags is None)
274 if ((local_ns is None or module is None or compile_flags is None)
275 and self.default_user_namespaces):
275 and self.default_user_namespaces):
276 call_frame = sys._getframe(stack_depth).f_back
276 call_frame = sys._getframe(stack_depth).f_back
277
277
278 if local_ns is None:
278 if local_ns is None:
279 local_ns = call_frame.f_locals
279 local_ns = call_frame.f_locals
280 if module is None:
280 if module is None:
281 global_ns = call_frame.f_globals
281 global_ns = call_frame.f_globals
282 try:
282 try:
283 module = sys.modules[global_ns['__name__']]
283 module = sys.modules[global_ns['__name__']]
284 except KeyError:
284 except KeyError:
285 warnings.warn("Failed to get module %s" % \
285 warnings.warn("Failed to get module %s" % \
286 global_ns.get('__name__', 'unknown module')
286 global_ns.get('__name__', 'unknown module')
287 )
287 )
288 module = DummyMod()
288 module = DummyMod()
289 module.__dict__ = global_ns
289 module.__dict__ = global_ns
290 if compile_flags is None:
290 if compile_flags is None:
291 compile_flags = (call_frame.f_code.co_flags &
291 compile_flags = (call_frame.f_code.co_flags &
292 compilerop.PyCF_MASK)
292 compilerop.PyCF_MASK)
293
293
294 # Save original namespace and module so we can restore them after
294 # Save original namespace and module so we can restore them after
295 # embedding; otherwise the shell doesn't shut down correctly.
295 # embedding; otherwise the shell doesn't shut down correctly.
296 orig_user_module = self.user_module
296 orig_user_module = self.user_module
297 orig_user_ns = self.user_ns
297 orig_user_ns = self.user_ns
298 orig_compile_flags = self.compile.flags
298 orig_compile_flags = self.compile.flags
299
299
300 # Update namespaces and fire up interpreter
300 # Update namespaces and fire up interpreter
301
301
302 # The global one is easy, we can just throw it in
302 # The global one is easy, we can just throw it in
303 if module is not None:
303 if module is not None:
304 self.user_module = module
304 self.user_module = module
305
305
306 # But the user/local one is tricky: ipython needs it to store internal
306 # But the user/local one is tricky: ipython needs it to store internal
307 # data, but we also need the locals. We'll throw our hidden variables
307 # data, but we also need the locals. We'll throw our hidden variables
308 # like _ih and get_ipython() into the local namespace, but delete them
308 # like _ih and get_ipython() into the local namespace, but delete them
309 # later.
309 # later.
310 if local_ns is not None:
310 if local_ns is not None:
311 reentrant_local_ns = {k: v for (k, v) in local_ns.items() if k not in self.user_ns_hidden.keys()}
311 reentrant_local_ns = {k: v for (k, v) in local_ns.items() if k not in self.user_ns_hidden.keys()}
312 self.user_ns = reentrant_local_ns
312 self.user_ns = reentrant_local_ns
313 self.init_user_ns()
313 self.init_user_ns()
314
314
315 # Compiler flags
315 # Compiler flags
316 if compile_flags is not None:
316 if compile_flags is not None:
317 self.compile.flags = compile_flags
317 self.compile.flags = compile_flags
318
318
319 # make sure the tab-completer has the correct frame information, so it
319 # make sure the tab-completer has the correct frame information, so it
320 # actually completes using the frame's locals/globals
320 # actually completes using the frame's locals/globals
321 self.set_completer_frame()
321 self.set_completer_frame()
322
322
323 with self.builtin_trap, self.display_trap:
323 with self.builtin_trap, self.display_trap:
324 self.interact()
324 self.interact()
325
325
326 # now, purge out the local namespace of IPython's hidden variables.
326 # now, purge out the local namespace of IPython's hidden variables.
327 if local_ns is not None:
327 if local_ns is not None:
328 local_ns.update({k: v for (k, v) in self.user_ns.items() if k not in self.user_ns_hidden.keys()})
328 local_ns.update({k: v for (k, v) in self.user_ns.items() if k not in self.user_ns_hidden.keys()})
329
329
330
330
331 # Restore original namespace so shell can shut down when we exit.
331 # Restore original namespace so shell can shut down when we exit.
332 self.user_module = orig_user_module
332 self.user_module = orig_user_module
333 self.user_ns = orig_user_ns
333 self.user_ns = orig_user_ns
334 self.compile.flags = orig_compile_flags
334 self.compile.flags = orig_compile_flags
335
335
336
336
337 def embed(**kwargs):
337 def embed(*, header="", compile_flags=None, **kwargs):
338 """Call this to embed IPython at the current point in your program.
338 """Call this to embed IPython at the current point in your program.
339
339
340 The first invocation of this will create an :class:`InteractiveShellEmbed`
340 The first invocation of this will create an :class:`InteractiveShellEmbed`
341 instance and then call it. Consecutive calls just call the already
341 instance and then call it. Consecutive calls just call the already
342 created instance.
342 created instance.
343
343
344 If you don't want the kernel to initialize the namespace
344 If you don't want the kernel to initialize the namespace
345 from the scope of the surrounding function,
345 from the scope of the surrounding function,
346 and/or you want to load full IPython configuration,
346 and/or you want to load full IPython configuration,
347 you probably want `IPython.start_ipython()` instead.
347 you probably want `IPython.start_ipython()` instead.
348
348
349 Here is a simple example::
349 Here is a simple example::
350
350
351 from IPython import embed
351 from IPython import embed
352 a = 10
352 a = 10
353 b = 20
353 b = 20
354 embed(header='First time')
354 embed(header='First time')
355 c = 30
355 c = 30
356 d = 40
356 d = 40
357 embed()
357 embed()
358
358
359 Full customization can be done by passing a :class:`Config` in as the
359 Full customization can be done by passing a :class:`Config` in as the
360 config argument.
360 config argument.
361 """
361 """
362 config = kwargs.get('config')
362 config = kwargs.get('config')
363 header = kwargs.pop('header', u'')
364 compile_flags = kwargs.pop('compile_flags', None)
365 if config is None:
363 if config is None:
366 config = load_default_config()
364 config = load_default_config()
367 config.InteractiveShellEmbed = config.TerminalInteractiveShell
365 config.InteractiveShellEmbed = config.TerminalInteractiveShell
368 kwargs['config'] = config
366 kwargs['config'] = config
369 using = kwargs.get('using', 'sync')
367 using = kwargs.get('using', 'sync')
370 if using :
368 if using :
371 kwargs['config'].update({'TerminalInteractiveShell':{'loop_runner':using, 'colors':'NoColor', 'autoawait': using!='sync'}})
369 kwargs['config'].update({'TerminalInteractiveShell':{'loop_runner':using, 'colors':'NoColor', 'autoawait': using!='sync'}})
372 #save ps1/ps2 if defined
370 #save ps1/ps2 if defined
373 ps1 = None
371 ps1 = None
374 ps2 = None
372 ps2 = None
375 try:
373 try:
376 ps1 = sys.ps1
374 ps1 = sys.ps1
377 ps2 = sys.ps2
375 ps2 = sys.ps2
378 except AttributeError:
376 except AttributeError:
379 pass
377 pass
380 #save previous instance
378 #save previous instance
381 saved_shell_instance = InteractiveShell._instance
379 saved_shell_instance = InteractiveShell._instance
382 if saved_shell_instance is not None:
380 if saved_shell_instance is not None:
383 cls = type(saved_shell_instance)
381 cls = type(saved_shell_instance)
384 cls.clear_instance()
382 cls.clear_instance()
385 frame = sys._getframe(1)
383 frame = sys._getframe(1)
386 shell = InteractiveShellEmbed.instance(_init_location_id='%s:%s' % (
384 shell = InteractiveShellEmbed.instance(_init_location_id='%s:%s' % (
387 frame.f_code.co_filename, frame.f_lineno), **kwargs)
385 frame.f_code.co_filename, frame.f_lineno), **kwargs)
388 shell(header=header, stack_depth=2, compile_flags=compile_flags,
386 shell(header=header, stack_depth=2, compile_flags=compile_flags,
389 _call_location_id='%s:%s' % (frame.f_code.co_filename, frame.f_lineno))
387 _call_location_id='%s:%s' % (frame.f_code.co_filename, frame.f_lineno))
390 InteractiveShellEmbed.clear_instance()
388 InteractiveShellEmbed.clear_instance()
391 #restore previous instance
389 #restore previous instance
392 if saved_shell_instance is not None:
390 if saved_shell_instance is not None:
393 cls = type(saved_shell_instance)
391 cls = type(saved_shell_instance)
394 cls.clear_instance()
392 cls.clear_instance()
395 for subclass in cls._walk_mro():
393 for subclass in cls._walk_mro():
396 subclass._instance = saved_shell_instance
394 subclass._instance = saved_shell_instance
397 if ps1 is not None:
395 if ps1 is not None:
398 sys.ps1 = ps1
396 sys.ps1 = ps1
399 sys.ps2 = ps2
397 sys.ps2 = ps2
General Comments 0
You need to be logged in to leave comments. Login now