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