Show More
@@ -1,2117 +1,2117 b'' | |||
|
1 | 1 | """Completion for IPython. |
|
2 | 2 | |
|
3 | 3 | This module started as fork of the rlcompleter module in the Python standard |
|
4 | 4 | library. The original enhancements made to rlcompleter have been sent |
|
5 | 5 | upstream and were accepted as of Python 2.3, |
|
6 | 6 | |
|
7 | 7 | This module now support a wide variety of completion mechanism both available |
|
8 | 8 | for normal classic Python code, as well as completer for IPython specific |
|
9 | 9 | Syntax like magics. |
|
10 | 10 | |
|
11 | 11 | Latex and Unicode completion |
|
12 | 12 | ============================ |
|
13 | 13 | |
|
14 | 14 | IPython and compatible frontends not only can complete your code, but can help |
|
15 | 15 | you to input a wide range of characters. In particular we allow you to insert |
|
16 | 16 | a unicode character using the tab completion mechanism. |
|
17 | 17 | |
|
18 | 18 | Forward latex/unicode completion |
|
19 | 19 | -------------------------------- |
|
20 | 20 | |
|
21 | 21 | Forward completion allows you to easily type a unicode character using its latex |
|
22 | 22 | name, or unicode long description. To do so type a backslash follow by the |
|
23 | 23 | relevant name and press tab: |
|
24 | 24 | |
|
25 | 25 | |
|
26 | 26 | Using latex completion: |
|
27 | 27 | |
|
28 | 28 | .. code:: |
|
29 | 29 | |
|
30 | 30 | \\alpha<tab> |
|
31 | 31 | Ξ± |
|
32 | 32 | |
|
33 | 33 | or using unicode completion: |
|
34 | 34 | |
|
35 | 35 | |
|
36 | 36 | .. code:: |
|
37 | 37 | |
|
38 | 38 | \\greek small letter alpha<tab> |
|
39 | 39 | Ξ± |
|
40 | 40 | |
|
41 | 41 | |
|
42 | 42 | Only valid Python identifiers will complete. Combining characters (like arrow or |
|
43 | 43 | dots) are also available, unlike latex they need to be put after the their |
|
44 | counterpart that is to say, `F\\\\vec<tab>` is correct, not `\\\\vec<tab>F`. | |
|
44 | counterpart that is to say, ``F\\\\vec<tab>`` is correct, not ``\\\\vec<tab>F``. | |
|
45 | 45 | |
|
46 | 46 | Some browsers are known to display combining characters incorrectly. |
|
47 | 47 | |
|
48 | 48 | Backward latex completion |
|
49 | 49 | ------------------------- |
|
50 | 50 | |
|
51 | 51 | It is sometime challenging to know how to type a character, if you are using |
|
52 | 52 | IPython, or any compatible frontend you can prepend backslash to the character |
|
53 | 53 | and press `<tab>` to expand it to its latex form. |
|
54 | 54 | |
|
55 | 55 | .. code:: |
|
56 | 56 | |
|
57 | 57 | \\Ξ±<tab> |
|
58 | 58 | \\alpha |
|
59 | 59 | |
|
60 | 60 | |
|
61 | 61 | Both forward and backward completions can be deactivated by setting the |
|
62 | 62 | ``Completer.backslash_combining_completions`` option to ``False``. |
|
63 | 63 | |
|
64 | 64 | |
|
65 | 65 | Experimental |
|
66 | 66 | ============ |
|
67 | 67 | |
|
68 | 68 | Starting with IPython 6.0, this module can make use of the Jedi library to |
|
69 | 69 | generate completions both using static analysis of the code, and dynamically |
|
70 | 70 | inspecting multiple namespaces. Jedi is an autocompletion and static analysis |
|
71 | 71 | for Python. The APIs attached to this new mechanism is unstable and will |
|
72 | 72 | raise unless use in an :any:`provisionalcompleter` context manager. |
|
73 | 73 | |
|
74 | 74 | You will find that the following are experimental: |
|
75 | 75 | |
|
76 | 76 | - :any:`provisionalcompleter` |
|
77 | 77 | - :any:`IPCompleter.completions` |
|
78 | 78 | - :any:`Completion` |
|
79 | 79 | - :any:`rectify_completions` |
|
80 | 80 | |
|
81 | 81 | .. note:: |
|
82 | 82 | |
|
83 | 83 | better name for :any:`rectify_completions` ? |
|
84 | 84 | |
|
85 | 85 | We welcome any feedback on these new API, and we also encourage you to try this |
|
86 | 86 | module in debug mode (start IPython with ``--Completer.debug=True``) in order |
|
87 | 87 | to have extra logging information if :any:`jedi` is crashing, or if current |
|
88 | 88 | IPython completer pending deprecations are returning results not yet handled |
|
89 | 89 | by :any:`jedi` |
|
90 | 90 | |
|
91 | 91 | Using Jedi for tab completion allow snippets like the following to work without |
|
92 | 92 | having to execute any code: |
|
93 | 93 | |
|
94 | 94 | >>> myvar = ['hello', 42] |
|
95 | 95 | ... myvar[1].bi<tab> |
|
96 | 96 | |
|
97 | 97 | Tab completion will be able to infer that ``myvar[1]`` is a real number without |
|
98 | 98 | executing any code unlike the previously available ``IPCompleter.greedy`` |
|
99 | 99 | option. |
|
100 | 100 | |
|
101 | 101 | Be sure to update :any:`jedi` to the latest stable version or to try the |
|
102 | 102 | current development version to get better completions. |
|
103 | 103 | """ |
|
104 | 104 | |
|
105 | 105 | |
|
106 | 106 | # Copyright (c) IPython Development Team. |
|
107 | 107 | # Distributed under the terms of the Modified BSD License. |
|
108 | 108 | # |
|
109 | 109 | # Some of this code originated from rlcompleter in the Python standard library |
|
110 | 110 | # Copyright (C) 2001 Python Software Foundation, www.python.org |
|
111 | 111 | |
|
112 | 112 | |
|
113 | 113 | import builtins as builtin_mod |
|
114 | 114 | import glob |
|
115 | 115 | import inspect |
|
116 | 116 | import itertools |
|
117 | 117 | import keyword |
|
118 | 118 | import os |
|
119 | 119 | import re |
|
120 | 120 | import string |
|
121 | 121 | import sys |
|
122 | 122 | import time |
|
123 | 123 | import unicodedata |
|
124 | 124 | import warnings |
|
125 | 125 | from contextlib import contextmanager |
|
126 | 126 | from importlib import import_module |
|
127 | 127 | from types import SimpleNamespace |
|
128 | 128 | from typing import Iterable, Iterator, List, Tuple |
|
129 | 129 | |
|
130 | 130 | from IPython.core.error import TryNext |
|
131 | 131 | from IPython.core.inputtransformer2 import ESC_MAGIC |
|
132 | 132 | from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol |
|
133 | 133 | from IPython.core.oinspect import InspectColors |
|
134 | 134 | from IPython.utils import generics |
|
135 | 135 | from IPython.utils.dir2 import dir2, get_real_method |
|
136 | 136 | from IPython.utils.process import arg_split |
|
137 | 137 | from traitlets import Bool, Enum, Int, observe |
|
138 | 138 | from traitlets.config.configurable import Configurable |
|
139 | 139 | |
|
140 | 140 | import __main__ |
|
141 | 141 | |
|
142 | 142 | # skip module docstests |
|
143 | 143 | skip_doctest = True |
|
144 | 144 | |
|
145 | 145 | try: |
|
146 | 146 | import jedi |
|
147 | 147 | jedi.settings.case_insensitive_completion = False |
|
148 | 148 | import jedi.api.helpers |
|
149 | 149 | import jedi.api.classes |
|
150 | 150 | JEDI_INSTALLED = True |
|
151 | 151 | except ImportError: |
|
152 | 152 | JEDI_INSTALLED = False |
|
153 | 153 | #----------------------------------------------------------------------------- |
|
154 | 154 | # Globals |
|
155 | 155 | #----------------------------------------------------------------------------- |
|
156 | 156 | |
|
157 | 157 | # Public API |
|
158 | 158 | __all__ = ['Completer','IPCompleter'] |
|
159 | 159 | |
|
160 | 160 | if sys.platform == 'win32': |
|
161 | 161 | PROTECTABLES = ' ' |
|
162 | 162 | else: |
|
163 | 163 | PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&' |
|
164 | 164 | |
|
165 | 165 | # Protect against returning an enormous number of completions which the frontend |
|
166 | 166 | # may have trouble processing. |
|
167 | 167 | MATCHES_LIMIT = 500 |
|
168 | 168 | |
|
169 | 169 | |
|
170 | 170 | class Sentinel: |
|
171 | 171 | def __repr__(self): |
|
172 | 172 | return "<deprecated sentinel>" |
|
173 | 173 | |
|
174 | 174 | |
|
175 | 175 | _deprecation_readline_sentinel = Sentinel() |
|
176 | 176 | |
|
177 | 177 | |
|
178 | 178 | class ProvisionalCompleterWarning(FutureWarning): |
|
179 | 179 | """ |
|
180 | 180 | Exception raise by an experimental feature in this module. |
|
181 | 181 | |
|
182 | 182 | Wrap code in :any:`provisionalcompleter` context manager if you |
|
183 | 183 | are certain you want to use an unstable feature. |
|
184 | 184 | """ |
|
185 | 185 | pass |
|
186 | 186 | |
|
187 | 187 | warnings.filterwarnings('error', category=ProvisionalCompleterWarning) |
|
188 | 188 | |
|
189 | 189 | @contextmanager |
|
190 | 190 | def provisionalcompleter(action='ignore'): |
|
191 | 191 | """ |
|
192 | 192 | |
|
193 | 193 | |
|
194 | 194 | This context manager has to be used in any place where unstable completer |
|
195 | 195 | behavior and API may be called. |
|
196 | 196 | |
|
197 | 197 | >>> with provisionalcompleter(): |
|
198 | 198 | ... completer.do_experimental_things() # works |
|
199 | 199 | |
|
200 | 200 | >>> completer.do_experimental_things() # raises. |
|
201 | 201 | |
|
202 | 202 | .. note:: |
|
203 | 203 | |
|
204 | 204 | Unstable |
|
205 | 205 | |
|
206 | 206 | By using this context manager you agree that the API in use may change |
|
207 | 207 | without warning, and that you won't complain if they do so. |
|
208 | 208 | |
|
209 | 209 | You also understand that, if the API is not to your liking, you should report |
|
210 | 210 | a bug to explain your use case upstream. |
|
211 | 211 | |
|
212 | 212 | We'll be happy to get your feedback, feature requests, and improvements on |
|
213 | 213 | any of the unstable APIs! |
|
214 | 214 | """ |
|
215 | 215 | with warnings.catch_warnings(): |
|
216 | 216 | warnings.filterwarnings(action, category=ProvisionalCompleterWarning) |
|
217 | 217 | yield |
|
218 | 218 | |
|
219 | 219 | |
|
220 | 220 | def has_open_quotes(s): |
|
221 | 221 | """Return whether a string has open quotes. |
|
222 | 222 | |
|
223 | 223 | This simply counts whether the number of quote characters of either type in |
|
224 | 224 | the string is odd. |
|
225 | 225 | |
|
226 | 226 | Returns |
|
227 | 227 | ------- |
|
228 | 228 | If there is an open quote, the quote character is returned. Else, return |
|
229 | 229 | False. |
|
230 | 230 | """ |
|
231 | 231 | # We check " first, then ', so complex cases with nested quotes will get |
|
232 | 232 | # the " to take precedence. |
|
233 | 233 | if s.count('"') % 2: |
|
234 | 234 | return '"' |
|
235 | 235 | elif s.count("'") % 2: |
|
236 | 236 | return "'" |
|
237 | 237 | else: |
|
238 | 238 | return False |
|
239 | 239 | |
|
240 | 240 | |
|
241 | 241 | def protect_filename(s, protectables=PROTECTABLES): |
|
242 | 242 | """Escape a string to protect certain characters.""" |
|
243 | 243 | if set(s) & set(protectables): |
|
244 | 244 | if sys.platform == "win32": |
|
245 | 245 | return '"' + s + '"' |
|
246 | 246 | else: |
|
247 | 247 | return "".join(("\\" + c if c in protectables else c) for c in s) |
|
248 | 248 | else: |
|
249 | 249 | return s |
|
250 | 250 | |
|
251 | 251 | |
|
252 | 252 | def expand_user(path:str) -> Tuple[str, bool, str]: |
|
253 | 253 | """Expand ``~``-style usernames in strings. |
|
254 | 254 | |
|
255 | 255 | This is similar to :func:`os.path.expanduser`, but it computes and returns |
|
256 | 256 | extra information that will be useful if the input was being used in |
|
257 | 257 | computing completions, and you wish to return the completions with the |
|
258 | 258 | original '~' instead of its expanded value. |
|
259 | 259 | |
|
260 | 260 | Parameters |
|
261 | 261 | ---------- |
|
262 | 262 | path : str |
|
263 | 263 | String to be expanded. If no ~ is present, the output is the same as the |
|
264 | 264 | input. |
|
265 | 265 | |
|
266 | 266 | Returns |
|
267 | 267 | ------- |
|
268 | 268 | newpath : str |
|
269 | 269 | Result of ~ expansion in the input path. |
|
270 | 270 | tilde_expand : bool |
|
271 | 271 | Whether any expansion was performed or not. |
|
272 | 272 | tilde_val : str |
|
273 | 273 | The value that ~ was replaced with. |
|
274 | 274 | """ |
|
275 | 275 | # Default values |
|
276 | 276 | tilde_expand = False |
|
277 | 277 | tilde_val = '' |
|
278 | 278 | newpath = path |
|
279 | 279 | |
|
280 | 280 | if path.startswith('~'): |
|
281 | 281 | tilde_expand = True |
|
282 | 282 | rest = len(path)-1 |
|
283 | 283 | newpath = os.path.expanduser(path) |
|
284 | 284 | if rest: |
|
285 | 285 | tilde_val = newpath[:-rest] |
|
286 | 286 | else: |
|
287 | 287 | tilde_val = newpath |
|
288 | 288 | |
|
289 | 289 | return newpath, tilde_expand, tilde_val |
|
290 | 290 | |
|
291 | 291 | |
|
292 | 292 | def compress_user(path:str, tilde_expand:bool, tilde_val:str) -> str: |
|
293 | 293 | """Does the opposite of expand_user, with its outputs. |
|
294 | 294 | """ |
|
295 | 295 | if tilde_expand: |
|
296 | 296 | return path.replace(tilde_val, '~') |
|
297 | 297 | else: |
|
298 | 298 | return path |
|
299 | 299 | |
|
300 | 300 | |
|
301 | 301 | def completions_sorting_key(word): |
|
302 | 302 | """key for sorting completions |
|
303 | 303 | |
|
304 | 304 | This does several things: |
|
305 | 305 | |
|
306 | 306 | - Demote any completions starting with underscores to the end |
|
307 | 307 | - Insert any %magic and %%cellmagic completions in the alphabetical order |
|
308 | 308 | by their name |
|
309 | 309 | """ |
|
310 | 310 | prio1, prio2 = 0, 0 |
|
311 | 311 | |
|
312 | 312 | if word.startswith('__'): |
|
313 | 313 | prio1 = 2 |
|
314 | 314 | elif word.startswith('_'): |
|
315 | 315 | prio1 = 1 |
|
316 | 316 | |
|
317 | 317 | if word.endswith('='): |
|
318 | 318 | prio1 = -1 |
|
319 | 319 | |
|
320 | 320 | if word.startswith('%%'): |
|
321 | 321 | # If there's another % in there, this is something else, so leave it alone |
|
322 | 322 | if not "%" in word[2:]: |
|
323 | 323 | word = word[2:] |
|
324 | 324 | prio2 = 2 |
|
325 | 325 | elif word.startswith('%'): |
|
326 | 326 | if not "%" in word[1:]: |
|
327 | 327 | word = word[1:] |
|
328 | 328 | prio2 = 1 |
|
329 | 329 | |
|
330 | 330 | return prio1, word, prio2 |
|
331 | 331 | |
|
332 | 332 | |
|
333 | 333 | class _FakeJediCompletion: |
|
334 | 334 | """ |
|
335 | 335 | This is a workaround to communicate to the UI that Jedi has crashed and to |
|
336 | 336 | report a bug. Will be used only id :any:`IPCompleter.debug` is set to true. |
|
337 | 337 | |
|
338 | 338 | Added in IPython 6.0 so should likely be removed for 7.0 |
|
339 | 339 | |
|
340 | 340 | """ |
|
341 | 341 | |
|
342 | 342 | def __init__(self, name): |
|
343 | 343 | |
|
344 | 344 | self.name = name |
|
345 | 345 | self.complete = name |
|
346 | 346 | self.type = 'crashed' |
|
347 | 347 | self.name_with_symbols = name |
|
348 | 348 | self.signature = '' |
|
349 | 349 | self._origin = 'fake' |
|
350 | 350 | |
|
351 | 351 | def __repr__(self): |
|
352 | 352 | return '<Fake completion object jedi has crashed>' |
|
353 | 353 | |
|
354 | 354 | |
|
355 | 355 | class Completion: |
|
356 | 356 | """ |
|
357 | 357 | Completion object used and return by IPython completers. |
|
358 | 358 | |
|
359 | 359 | .. warning:: |
|
360 | 360 | |
|
361 | 361 | Unstable |
|
362 | 362 | |
|
363 | 363 | This function is unstable, API may change without warning. |
|
364 | 364 | It will also raise unless use in proper context manager. |
|
365 | 365 | |
|
366 | 366 | This act as a middle ground :any:`Completion` object between the |
|
367 | 367 | :any:`jedi.api.classes.Completion` object and the Prompt Toolkit completion |
|
368 | 368 | object. While Jedi need a lot of information about evaluator and how the |
|
369 | 369 | code should be ran/inspected, PromptToolkit (and other frontend) mostly |
|
370 | 370 | need user facing information. |
|
371 | 371 | |
|
372 | 372 | - Which range should be replaced replaced by what. |
|
373 | 373 | - Some metadata (like completion type), or meta information to displayed to |
|
374 | 374 | the use user. |
|
375 | 375 | |
|
376 | 376 | For debugging purpose we can also store the origin of the completion (``jedi``, |
|
377 | 377 | ``IPython.python_matches``, ``IPython.magics_matches``...). |
|
378 | 378 | """ |
|
379 | 379 | |
|
380 | 380 | __slots__ = ['start', 'end', 'text', 'type', 'signature', '_origin'] |
|
381 | 381 | |
|
382 | 382 | def __init__(self, start: int, end: int, text: str, *, type: str=None, _origin='', signature='') -> None: |
|
383 | 383 | warnings.warn("``Completion`` is a provisional API (as of IPython 6.0). " |
|
384 | 384 | "It may change without warnings. " |
|
385 | 385 | "Use in corresponding context manager.", |
|
386 | 386 | category=ProvisionalCompleterWarning, stacklevel=2) |
|
387 | 387 | |
|
388 | 388 | self.start = start |
|
389 | 389 | self.end = end |
|
390 | 390 | self.text = text |
|
391 | 391 | self.type = type |
|
392 | 392 | self.signature = signature |
|
393 | 393 | self._origin = _origin |
|
394 | 394 | |
|
395 | 395 | def __repr__(self): |
|
396 | 396 | return '<Completion start=%s end=%s text=%r type=%r, signature=%r,>' % \ |
|
397 | 397 | (self.start, self.end, self.text, self.type or '?', self.signature or '?') |
|
398 | 398 | |
|
399 | 399 | def __eq__(self, other)->Bool: |
|
400 | 400 | """ |
|
401 | 401 | Equality and hash do not hash the type (as some completer may not be |
|
402 | 402 | able to infer the type), but are use to (partially) de-duplicate |
|
403 | 403 | completion. |
|
404 | 404 | |
|
405 | 405 | Completely de-duplicating completion is a bit tricker that just |
|
406 | 406 | comparing as it depends on surrounding text, which Completions are not |
|
407 | 407 | aware of. |
|
408 | 408 | """ |
|
409 | 409 | return self.start == other.start and \ |
|
410 | 410 | self.end == other.end and \ |
|
411 | 411 | self.text == other.text |
|
412 | 412 | |
|
413 | 413 | def __hash__(self): |
|
414 | 414 | return hash((self.start, self.end, self.text)) |
|
415 | 415 | |
|
416 | 416 | |
|
417 | 417 | _IC = Iterable[Completion] |
|
418 | 418 | |
|
419 | 419 | |
|
420 | 420 | def _deduplicate_completions(text: str, completions: _IC)-> _IC: |
|
421 | 421 | """ |
|
422 | 422 | Deduplicate a set of completions. |
|
423 | 423 | |
|
424 | 424 | .. warning:: |
|
425 | 425 | |
|
426 | 426 | Unstable |
|
427 | 427 | |
|
428 | 428 | This function is unstable, API may change without warning. |
|
429 | 429 | |
|
430 | 430 | Parameters |
|
431 | 431 | ---------- |
|
432 | 432 | text: str |
|
433 | 433 | text that should be completed. |
|
434 | 434 | completions: Iterator[Completion] |
|
435 | 435 | iterator over the completions to deduplicate |
|
436 | 436 | |
|
437 | 437 | Yields |
|
438 | 438 | ------ |
|
439 | 439 | `Completions` objects |
|
440 | 440 | |
|
441 | 441 | |
|
442 | 442 | Completions coming from multiple sources, may be different but end up having |
|
443 | 443 | the same effect when applied to ``text``. If this is the case, this will |
|
444 | 444 | consider completions as equal and only emit the first encountered. |
|
445 | 445 | |
|
446 | 446 | Not folded in `completions()` yet for debugging purpose, and to detect when |
|
447 | 447 | the IPython completer does return things that Jedi does not, but should be |
|
448 | 448 | at some point. |
|
449 | 449 | """ |
|
450 | 450 | completions = list(completions) |
|
451 | 451 | if not completions: |
|
452 | 452 | return |
|
453 | 453 | |
|
454 | 454 | new_start = min(c.start for c in completions) |
|
455 | 455 | new_end = max(c.end for c in completions) |
|
456 | 456 | |
|
457 | 457 | seen = set() |
|
458 | 458 | for c in completions: |
|
459 | 459 | new_text = text[new_start:c.start] + c.text + text[c.end:new_end] |
|
460 | 460 | if new_text not in seen: |
|
461 | 461 | yield c |
|
462 | 462 | seen.add(new_text) |
|
463 | 463 | |
|
464 | 464 | |
|
465 | 465 | def rectify_completions(text: str, completions: _IC, *, _debug=False)->_IC: |
|
466 | 466 | """ |
|
467 | 467 | Rectify a set of completions to all have the same ``start`` and ``end`` |
|
468 | 468 | |
|
469 | 469 | .. warning:: |
|
470 | 470 | |
|
471 | 471 | Unstable |
|
472 | 472 | |
|
473 | 473 | This function is unstable, API may change without warning. |
|
474 | 474 | It will also raise unless use in proper context manager. |
|
475 | 475 | |
|
476 | 476 | Parameters |
|
477 | 477 | ---------- |
|
478 | 478 | text: str |
|
479 | 479 | text that should be completed. |
|
480 | 480 | completions: Iterator[Completion] |
|
481 | 481 | iterator over the completions to rectify |
|
482 | 482 | |
|
483 | 483 | |
|
484 | 484 | :any:`jedi.api.classes.Completion` s returned by Jedi may not have the same start and end, though |
|
485 | 485 | the Jupyter Protocol requires them to behave like so. This will readjust |
|
486 | 486 | the completion to have the same ``start`` and ``end`` by padding both |
|
487 | 487 | extremities with surrounding text. |
|
488 | 488 | |
|
489 | 489 | During stabilisation should support a ``_debug`` option to log which |
|
490 | 490 | completion are return by the IPython completer and not found in Jedi in |
|
491 | 491 | order to make upstream bug report. |
|
492 | 492 | """ |
|
493 | 493 | warnings.warn("`rectify_completions` is a provisional API (as of IPython 6.0). " |
|
494 | 494 | "It may change without warnings. " |
|
495 | 495 | "Use in corresponding context manager.", |
|
496 | 496 | category=ProvisionalCompleterWarning, stacklevel=2) |
|
497 | 497 | |
|
498 | 498 | completions = list(completions) |
|
499 | 499 | if not completions: |
|
500 | 500 | return |
|
501 | 501 | starts = (c.start for c in completions) |
|
502 | 502 | ends = (c.end for c in completions) |
|
503 | 503 | |
|
504 | 504 | new_start = min(starts) |
|
505 | 505 | new_end = max(ends) |
|
506 | 506 | |
|
507 | 507 | seen_jedi = set() |
|
508 | 508 | seen_python_matches = set() |
|
509 | 509 | for c in completions: |
|
510 | 510 | new_text = text[new_start:c.start] + c.text + text[c.end:new_end] |
|
511 | 511 | if c._origin == 'jedi': |
|
512 | 512 | seen_jedi.add(new_text) |
|
513 | 513 | elif c._origin == 'IPCompleter.python_matches': |
|
514 | 514 | seen_python_matches.add(new_text) |
|
515 | 515 | yield Completion(new_start, new_end, new_text, type=c.type, _origin=c._origin, signature=c.signature) |
|
516 | 516 | diff = seen_python_matches.difference(seen_jedi) |
|
517 | 517 | if diff and _debug: |
|
518 | 518 | print('IPython.python matches have extras:', diff) |
|
519 | 519 | |
|
520 | 520 | |
|
521 | 521 | if sys.platform == 'win32': |
|
522 | 522 | DELIMS = ' \t\n`!@#$^&*()=+[{]}|;\'",<>?' |
|
523 | 523 | else: |
|
524 | 524 | DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?' |
|
525 | 525 | |
|
526 | 526 | GREEDY_DELIMS = ' =\r\n' |
|
527 | 527 | |
|
528 | 528 | |
|
529 | 529 | class CompletionSplitter(object): |
|
530 | 530 | """An object to split an input line in a manner similar to readline. |
|
531 | 531 | |
|
532 | 532 | By having our own implementation, we can expose readline-like completion in |
|
533 | 533 | a uniform manner to all frontends. This object only needs to be given the |
|
534 | 534 | line of text to be split and the cursor position on said line, and it |
|
535 | 535 | returns the 'word' to be completed on at the cursor after splitting the |
|
536 | 536 | entire line. |
|
537 | 537 | |
|
538 | 538 | What characters are used as splitting delimiters can be controlled by |
|
539 | 539 | setting the ``delims`` attribute (this is a property that internally |
|
540 | 540 | automatically builds the necessary regular expression)""" |
|
541 | 541 | |
|
542 | 542 | # Private interface |
|
543 | 543 | |
|
544 | 544 | # A string of delimiter characters. The default value makes sense for |
|
545 | 545 | # IPython's most typical usage patterns. |
|
546 | 546 | _delims = DELIMS |
|
547 | 547 | |
|
548 | 548 | # The expression (a normal string) to be compiled into a regular expression |
|
549 | 549 | # for actual splitting. We store it as an attribute mostly for ease of |
|
550 | 550 | # debugging, since this type of code can be so tricky to debug. |
|
551 | 551 | _delim_expr = None |
|
552 | 552 | |
|
553 | 553 | # The regular expression that does the actual splitting |
|
554 | 554 | _delim_re = None |
|
555 | 555 | |
|
556 | 556 | def __init__(self, delims=None): |
|
557 | 557 | delims = CompletionSplitter._delims if delims is None else delims |
|
558 | 558 | self.delims = delims |
|
559 | 559 | |
|
560 | 560 | @property |
|
561 | 561 | def delims(self): |
|
562 | 562 | """Return the string of delimiter characters.""" |
|
563 | 563 | return self._delims |
|
564 | 564 | |
|
565 | 565 | @delims.setter |
|
566 | 566 | def delims(self, delims): |
|
567 | 567 | """Set the delimiters for line splitting.""" |
|
568 | 568 | expr = '[' + ''.join('\\'+ c for c in delims) + ']' |
|
569 | 569 | self._delim_re = re.compile(expr) |
|
570 | 570 | self._delims = delims |
|
571 | 571 | self._delim_expr = expr |
|
572 | 572 | |
|
573 | 573 | def split_line(self, line, cursor_pos=None): |
|
574 | 574 | """Split a line of text with a cursor at the given position. |
|
575 | 575 | """ |
|
576 | 576 | l = line if cursor_pos is None else line[:cursor_pos] |
|
577 | 577 | return self._delim_re.split(l)[-1] |
|
578 | 578 | |
|
579 | 579 | |
|
580 | 580 | |
|
581 | 581 | class Completer(Configurable): |
|
582 | 582 | |
|
583 | 583 | greedy = Bool(False, |
|
584 | 584 | help="""Activate greedy completion |
|
585 | 585 | PENDING DEPRECTION. this is now mostly taken care of with Jedi. |
|
586 | 586 | |
|
587 | 587 | This will enable completion on elements of lists, results of function calls, etc., |
|
588 | 588 | but can be unsafe because the code is actually evaluated on TAB. |
|
589 | 589 | """ |
|
590 | 590 | ).tag(config=True) |
|
591 | 591 | |
|
592 | 592 | use_jedi = Bool(default_value=JEDI_INSTALLED, |
|
593 | 593 | help="Experimental: Use Jedi to generate autocompletions. " |
|
594 | 594 | "Default to True if jedi is installed.").tag(config=True) |
|
595 | 595 | |
|
596 | 596 | jedi_compute_type_timeout = Int(default_value=400, |
|
597 | 597 | help="""Experimental: restrict time (in milliseconds) during which Jedi can compute types. |
|
598 | 598 | Set to 0 to stop computing types. Non-zero value lower than 100ms may hurt |
|
599 | 599 | performance by preventing jedi to build its cache. |
|
600 | 600 | """).tag(config=True) |
|
601 | 601 | |
|
602 | 602 | debug = Bool(default_value=False, |
|
603 | 603 | help='Enable debug for the Completer. Mostly print extra ' |
|
604 | 604 | 'information for experimental jedi integration.')\ |
|
605 | 605 | .tag(config=True) |
|
606 | 606 | |
|
607 | 607 | backslash_combining_completions = Bool(True, |
|
608 | 608 | help="Enable unicode completions, e.g. \\alpha<tab> . " |
|
609 | 609 | "Includes completion of latex commands, unicode names, and expanding " |
|
610 | 610 | "unicode characters back to latex commands.").tag(config=True) |
|
611 | 611 | |
|
612 | 612 | |
|
613 | 613 | |
|
614 | 614 | def __init__(self, namespace=None, global_namespace=None, **kwargs): |
|
615 | 615 | """Create a new completer for the command line. |
|
616 | 616 | |
|
617 | 617 | Completer(namespace=ns, global_namespace=ns2) -> completer instance. |
|
618 | 618 | |
|
619 | 619 | If unspecified, the default namespace where completions are performed |
|
620 | 620 | is __main__ (technically, __main__.__dict__). Namespaces should be |
|
621 | 621 | given as dictionaries. |
|
622 | 622 | |
|
623 | 623 | An optional second namespace can be given. This allows the completer |
|
624 | 624 | to handle cases where both the local and global scopes need to be |
|
625 | 625 | distinguished. |
|
626 | 626 | """ |
|
627 | 627 | |
|
628 | 628 | # Don't bind to namespace quite yet, but flag whether the user wants a |
|
629 | 629 | # specific namespace or to use __main__.__dict__. This will allow us |
|
630 | 630 | # to bind to __main__.__dict__ at completion time, not now. |
|
631 | 631 | if namespace is None: |
|
632 | 632 | self.use_main_ns = True |
|
633 | 633 | else: |
|
634 | 634 | self.use_main_ns = False |
|
635 | 635 | self.namespace = namespace |
|
636 | 636 | |
|
637 | 637 | # The global namespace, if given, can be bound directly |
|
638 | 638 | if global_namespace is None: |
|
639 | 639 | self.global_namespace = {} |
|
640 | 640 | else: |
|
641 | 641 | self.global_namespace = global_namespace |
|
642 | 642 | |
|
643 | 643 | self.custom_matchers = [] |
|
644 | 644 | |
|
645 | 645 | super(Completer, self).__init__(**kwargs) |
|
646 | 646 | |
|
647 | 647 | def complete(self, text, state): |
|
648 | 648 | """Return the next possible completion for 'text'. |
|
649 | 649 | |
|
650 | 650 | This is called successively with state == 0, 1, 2, ... until it |
|
651 | 651 | returns None. The completion should begin with 'text'. |
|
652 | 652 | |
|
653 | 653 | """ |
|
654 | 654 | if self.use_main_ns: |
|
655 | 655 | self.namespace = __main__.__dict__ |
|
656 | 656 | |
|
657 | 657 | if state == 0: |
|
658 | 658 | if "." in text: |
|
659 | 659 | self.matches = self.attr_matches(text) |
|
660 | 660 | else: |
|
661 | 661 | self.matches = self.global_matches(text) |
|
662 | 662 | try: |
|
663 | 663 | return self.matches[state] |
|
664 | 664 | except IndexError: |
|
665 | 665 | return None |
|
666 | 666 | |
|
667 | 667 | def global_matches(self, text): |
|
668 | 668 | """Compute matches when text is a simple name. |
|
669 | 669 | |
|
670 | 670 | Return a list of all keywords, built-in functions and names currently |
|
671 | 671 | defined in self.namespace or self.global_namespace that match. |
|
672 | 672 | |
|
673 | 673 | """ |
|
674 | 674 | matches = [] |
|
675 | 675 | match_append = matches.append |
|
676 | 676 | n = len(text) |
|
677 | 677 | for lst in [keyword.kwlist, |
|
678 | 678 | builtin_mod.__dict__.keys(), |
|
679 | 679 | self.namespace.keys(), |
|
680 | 680 | self.global_namespace.keys()]: |
|
681 | 681 | for word in lst: |
|
682 | 682 | if word[:n] == text and word != "__builtins__": |
|
683 | 683 | match_append(word) |
|
684 | 684 | |
|
685 | 685 | snake_case_re = re.compile(r"[^_]+(_[^_]+)+?\Z") |
|
686 | 686 | for lst in [self.namespace.keys(), |
|
687 | 687 | self.global_namespace.keys()]: |
|
688 | 688 | shortened = {"_".join([sub[0] for sub in word.split('_')]) : word |
|
689 | 689 | for word in lst if snake_case_re.match(word)} |
|
690 | 690 | for word in shortened.keys(): |
|
691 | 691 | if word[:n] == text and word != "__builtins__": |
|
692 | 692 | match_append(shortened[word]) |
|
693 | 693 | return matches |
|
694 | 694 | |
|
695 | 695 | def attr_matches(self, text): |
|
696 | 696 | """Compute matches when text contains a dot. |
|
697 | 697 | |
|
698 | 698 | Assuming the text is of the form NAME.NAME....[NAME], and is |
|
699 | 699 | evaluatable in self.namespace or self.global_namespace, it will be |
|
700 | 700 | evaluated and its attributes (as revealed by dir()) are used as |
|
701 | 701 | possible completions. (For class instances, class members are |
|
702 | 702 | also considered.) |
|
703 | 703 | |
|
704 | 704 | WARNING: this can still invoke arbitrary C code, if an object |
|
705 | 705 | with a __getattr__ hook is evaluated. |
|
706 | 706 | |
|
707 | 707 | """ |
|
708 | 708 | |
|
709 | 709 | # Another option, seems to work great. Catches things like ''.<tab> |
|
710 | 710 | m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text) |
|
711 | 711 | |
|
712 | 712 | if m: |
|
713 | 713 | expr, attr = m.group(1, 3) |
|
714 | 714 | elif self.greedy: |
|
715 | 715 | m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer) |
|
716 | 716 | if not m2: |
|
717 | 717 | return [] |
|
718 | 718 | expr, attr = m2.group(1,2) |
|
719 | 719 | else: |
|
720 | 720 | return [] |
|
721 | 721 | |
|
722 | 722 | try: |
|
723 | 723 | obj = eval(expr, self.namespace) |
|
724 | 724 | except: |
|
725 | 725 | try: |
|
726 | 726 | obj = eval(expr, self.global_namespace) |
|
727 | 727 | except: |
|
728 | 728 | return [] |
|
729 | 729 | |
|
730 | 730 | if self.limit_to__all__ and hasattr(obj, '__all__'): |
|
731 | 731 | words = get__all__entries(obj) |
|
732 | 732 | else: |
|
733 | 733 | words = dir2(obj) |
|
734 | 734 | |
|
735 | 735 | try: |
|
736 | 736 | words = generics.complete_object(obj, words) |
|
737 | 737 | except TryNext: |
|
738 | 738 | pass |
|
739 | 739 | except AssertionError: |
|
740 | 740 | raise |
|
741 | 741 | except Exception: |
|
742 | 742 | # Silence errors from completion function |
|
743 | 743 | #raise # dbg |
|
744 | 744 | pass |
|
745 | 745 | # Build match list to return |
|
746 | 746 | n = len(attr) |
|
747 | 747 | return [u"%s.%s" % (expr, w) for w in words if w[:n] == attr ] |
|
748 | 748 | |
|
749 | 749 | |
|
750 | 750 | def get__all__entries(obj): |
|
751 | 751 | """returns the strings in the __all__ attribute""" |
|
752 | 752 | try: |
|
753 | 753 | words = getattr(obj, '__all__') |
|
754 | 754 | except: |
|
755 | 755 | return [] |
|
756 | 756 | |
|
757 | 757 | return [w for w in words if isinstance(w, str)] |
|
758 | 758 | |
|
759 | 759 | |
|
760 | 760 | def match_dict_keys(keys: List[str], prefix: str, delims: str): |
|
761 | 761 | """Used by dict_key_matches, matching the prefix to a list of keys |
|
762 | 762 | |
|
763 | 763 | Parameters |
|
764 | 764 | ========== |
|
765 | 765 | keys: |
|
766 | 766 | list of keys in dictionary currently being completed. |
|
767 | 767 | prefix: |
|
768 | 768 | Part of the text already typed by the user. e.g. `mydict[b'fo` |
|
769 | 769 | delims: |
|
770 | 770 | String of delimiters to consider when finding the current key. |
|
771 | 771 | |
|
772 | 772 | Returns |
|
773 | 773 | ======= |
|
774 | 774 | |
|
775 | 775 | A tuple of three elements: ``quote``, ``token_start``, ``matched``, with |
|
776 | 776 | ``quote`` being the quote that need to be used to close current string. |
|
777 | 777 | ``token_start`` the position where the replacement should start occurring, |
|
778 | 778 | ``matches`` a list of replacement/completion |
|
779 | 779 | |
|
780 | 780 | """ |
|
781 | 781 | if not prefix: |
|
782 | 782 | return None, 0, [repr(k) for k in keys |
|
783 | 783 | if isinstance(k, (str, bytes))] |
|
784 | 784 | quote_match = re.search('["\']', prefix) |
|
785 | 785 | quote = quote_match.group() |
|
786 | 786 | try: |
|
787 | 787 | prefix_str = eval(prefix + quote, {}) |
|
788 | 788 | except Exception: |
|
789 | 789 | return None, 0, [] |
|
790 | 790 | |
|
791 | 791 | pattern = '[^' + ''.join('\\' + c for c in delims) + ']*$' |
|
792 | 792 | token_match = re.search(pattern, prefix, re.UNICODE) |
|
793 | 793 | token_start = token_match.start() |
|
794 | 794 | token_prefix = token_match.group() |
|
795 | 795 | |
|
796 | 796 | matched = [] |
|
797 | 797 | for key in keys: |
|
798 | 798 | try: |
|
799 | 799 | if not key.startswith(prefix_str): |
|
800 | 800 | continue |
|
801 | 801 | except (AttributeError, TypeError, UnicodeError): |
|
802 | 802 | # Python 3+ TypeError on b'a'.startswith('a') or vice-versa |
|
803 | 803 | continue |
|
804 | 804 | |
|
805 | 805 | # reformat remainder of key to begin with prefix |
|
806 | 806 | rem = key[len(prefix_str):] |
|
807 | 807 | # force repr wrapped in ' |
|
808 | 808 | rem_repr = repr(rem + '"') if isinstance(rem, str) else repr(rem + b'"') |
|
809 | 809 | if rem_repr.startswith('u') and prefix[0] not in 'uU': |
|
810 | 810 | # Found key is unicode, but prefix is Py2 string. |
|
811 | 811 | # Therefore attempt to interpret key as string. |
|
812 | 812 | try: |
|
813 | 813 | rem_repr = repr(rem.encode('ascii') + '"') |
|
814 | 814 | except UnicodeEncodeError: |
|
815 | 815 | continue |
|
816 | 816 | |
|
817 | 817 | rem_repr = rem_repr[1 + rem_repr.index("'"):-2] |
|
818 | 818 | if quote == '"': |
|
819 | 819 | # The entered prefix is quoted with ", |
|
820 | 820 | # but the match is quoted with '. |
|
821 | 821 | # A contained " hence needs escaping for comparison: |
|
822 | 822 | rem_repr = rem_repr.replace('"', '\\"') |
|
823 | 823 | |
|
824 | 824 | # then reinsert prefix from start of token |
|
825 | 825 | matched.append('%s%s' % (token_prefix, rem_repr)) |
|
826 | 826 | return quote, token_start, matched |
|
827 | 827 | |
|
828 | 828 | |
|
829 | 829 | def cursor_to_position(text:str, line:int, column:int)->int: |
|
830 | 830 | """ |
|
831 | 831 | |
|
832 | 832 | Convert the (line,column) position of the cursor in text to an offset in a |
|
833 | 833 | string. |
|
834 | 834 | |
|
835 | 835 | Parameters |
|
836 | 836 | ---------- |
|
837 | 837 | |
|
838 | 838 | text : str |
|
839 | 839 | The text in which to calculate the cursor offset |
|
840 | 840 | line : int |
|
841 | 841 | Line of the cursor; 0-indexed |
|
842 | 842 | column : int |
|
843 | 843 | Column of the cursor 0-indexed |
|
844 | 844 | |
|
845 | 845 | Return |
|
846 | 846 | ------ |
|
847 | 847 | Position of the cursor in ``text``, 0-indexed. |
|
848 | 848 | |
|
849 | 849 | See Also |
|
850 | 850 | -------- |
|
851 | 851 | position_to_cursor: reciprocal of this function |
|
852 | 852 | |
|
853 | 853 | """ |
|
854 | 854 | lines = text.split('\n') |
|
855 | 855 | assert line <= len(lines), '{} <= {}'.format(str(line), str(len(lines))) |
|
856 | 856 | |
|
857 | 857 | return sum(len(l) + 1 for l in lines[:line]) + column |
|
858 | 858 | |
|
859 | 859 | def position_to_cursor(text:str, offset:int)->Tuple[int, int]: |
|
860 | 860 | """ |
|
861 | 861 | Convert the position of the cursor in text (0 indexed) to a line |
|
862 | 862 | number(0-indexed) and a column number (0-indexed) pair |
|
863 | 863 | |
|
864 | 864 | Position should be a valid position in ``text``. |
|
865 | 865 | |
|
866 | 866 | Parameters |
|
867 | 867 | ---------- |
|
868 | 868 | |
|
869 | 869 | text : str |
|
870 | 870 | The text in which to calculate the cursor offset |
|
871 | 871 | offset : int |
|
872 | 872 | Position of the cursor in ``text``, 0-indexed. |
|
873 | 873 | |
|
874 | 874 | Return |
|
875 | 875 | ------ |
|
876 | 876 | (line, column) : (int, int) |
|
877 | 877 | Line of the cursor; 0-indexed, column of the cursor 0-indexed |
|
878 | 878 | |
|
879 | 879 | |
|
880 | 880 | See Also |
|
881 | 881 | -------- |
|
882 | 882 | cursor_to_position : reciprocal of this function |
|
883 | 883 | |
|
884 | 884 | |
|
885 | 885 | """ |
|
886 | 886 | |
|
887 | 887 | assert 0 <= offset <= len(text) , "0 <= %s <= %s" % (offset , len(text)) |
|
888 | 888 | |
|
889 | 889 | before = text[:offset] |
|
890 | 890 | blines = before.split('\n') # ! splitnes trim trailing \n |
|
891 | 891 | line = before.count('\n') |
|
892 | 892 | col = len(blines[-1]) |
|
893 | 893 | return line, col |
|
894 | 894 | |
|
895 | 895 | |
|
896 | 896 | def _safe_isinstance(obj, module, class_name): |
|
897 | 897 | """Checks if obj is an instance of module.class_name if loaded |
|
898 | 898 | """ |
|
899 | 899 | return (module in sys.modules and |
|
900 | 900 | isinstance(obj, getattr(import_module(module), class_name))) |
|
901 | 901 | |
|
902 | 902 | |
|
903 | 903 | def back_unicode_name_matches(text): |
|
904 | 904 | u"""Match unicode characters back to unicode name |
|
905 | 905 | |
|
906 | 906 | This does ``β`` -> ``\\snowman`` |
|
907 | 907 | |
|
908 | 908 | Note that snowman is not a valid python3 combining character but will be expanded. |
|
909 | 909 | Though it will not recombine back to the snowman character by the completion machinery. |
|
910 | 910 | |
|
911 | 911 | This will not either back-complete standard sequences like \\n, \\b ... |
|
912 | 912 | |
|
913 | 913 | Used on Python 3 only. |
|
914 | 914 | """ |
|
915 | 915 | if len(text)<2: |
|
916 | 916 | return u'', () |
|
917 | 917 | maybe_slash = text[-2] |
|
918 | 918 | if maybe_slash != '\\': |
|
919 | 919 | return u'', () |
|
920 | 920 | |
|
921 | 921 | char = text[-1] |
|
922 | 922 | # no expand on quote for completion in strings. |
|
923 | 923 | # nor backcomplete standard ascii keys |
|
924 | 924 | if char in string.ascii_letters or char in ['"',"'"]: |
|
925 | 925 | return u'', () |
|
926 | 926 | try : |
|
927 | 927 | unic = unicodedata.name(char) |
|
928 | 928 | return '\\'+char,['\\'+unic] |
|
929 | 929 | except KeyError: |
|
930 | 930 | pass |
|
931 | 931 | return u'', () |
|
932 | 932 | |
|
933 | 933 | def back_latex_name_matches(text:str): |
|
934 | 934 | """Match latex characters back to unicode name |
|
935 | 935 | |
|
936 | 936 | This does ``\\β΅`` -> ``\\aleph`` |
|
937 | 937 | |
|
938 | 938 | Used on Python 3 only. |
|
939 | 939 | """ |
|
940 | 940 | if len(text)<2: |
|
941 | 941 | return u'', () |
|
942 | 942 | maybe_slash = text[-2] |
|
943 | 943 | if maybe_slash != '\\': |
|
944 | 944 | return u'', () |
|
945 | 945 | |
|
946 | 946 | |
|
947 | 947 | char = text[-1] |
|
948 | 948 | # no expand on quote for completion in strings. |
|
949 | 949 | # nor backcomplete standard ascii keys |
|
950 | 950 | if char in string.ascii_letters or char in ['"',"'"]: |
|
951 | 951 | return u'', () |
|
952 | 952 | try : |
|
953 | 953 | latex = reverse_latex_symbol[char] |
|
954 | 954 | # '\\' replace the \ as well |
|
955 | 955 | return '\\'+char,[latex] |
|
956 | 956 | except KeyError: |
|
957 | 957 | pass |
|
958 | 958 | return u'', () |
|
959 | 959 | |
|
960 | 960 | |
|
961 | 961 | def _formatparamchildren(parameter) -> str: |
|
962 | 962 | """ |
|
963 | 963 | Get parameter name and value from Jedi Private API |
|
964 | 964 | |
|
965 | 965 | Jedi does not expose a simple way to get `param=value` from its API. |
|
966 | 966 | |
|
967 | 967 | Parameter |
|
968 | 968 | ========= |
|
969 | 969 | |
|
970 | 970 | parameter: |
|
971 | 971 | Jedi's function `Param` |
|
972 | 972 | |
|
973 | 973 | Returns |
|
974 | 974 | ======= |
|
975 | 975 | |
|
976 | 976 | A string like 'a', 'b=1', '*args', '**kwargs' |
|
977 | 977 | |
|
978 | 978 | |
|
979 | 979 | """ |
|
980 | 980 | description = parameter.description |
|
981 | 981 | if not description.startswith('param '): |
|
982 | 982 | raise ValueError('Jedi function parameter description have change format.' |
|
983 | 983 | 'Expected "param ...", found %r".' % description) |
|
984 | 984 | return description[6:] |
|
985 | 985 | |
|
986 | 986 | def _make_signature(completion)-> str: |
|
987 | 987 | """ |
|
988 | 988 | Make the signature from a jedi completion |
|
989 | 989 | |
|
990 | 990 | Parameter |
|
991 | 991 | ========= |
|
992 | 992 | |
|
993 | 993 | completion: jedi.Completion |
|
994 | 994 | object does not complete a function type |
|
995 | 995 | |
|
996 | 996 | Returns |
|
997 | 997 | ======= |
|
998 | 998 | |
|
999 | 999 | a string consisting of the function signature, with the parenthesis but |
|
1000 | 1000 | without the function name. example: |
|
1001 | 1001 | `(a, *args, b=1, **kwargs)` |
|
1002 | 1002 | |
|
1003 | 1003 | """ |
|
1004 | 1004 | |
|
1005 | 1005 | # it looks like this might work on jedi 0.17 |
|
1006 | 1006 | if hasattr(completion, 'get_signatures'): |
|
1007 | 1007 | signatures = completion.get_signatures() |
|
1008 | 1008 | if not signatures: |
|
1009 | 1009 | return '(?)' |
|
1010 | 1010 | |
|
1011 | 1011 | c0 = completion.get_signatures()[0] |
|
1012 | 1012 | return '('+c0.to_string().split('(', maxsplit=1)[1] |
|
1013 | 1013 | |
|
1014 | 1014 | return '(%s)'% ', '.join([f for f in (_formatparamchildren(p) for signature in completion.get_signatures() |
|
1015 | 1015 | for p in signature.defined_names()) if f]) |
|
1016 | 1016 | |
|
1017 | 1017 | class IPCompleter(Completer): |
|
1018 | 1018 | """Extension of the completer class with IPython-specific features""" |
|
1019 | 1019 | |
|
1020 | 1020 | _names = None |
|
1021 | 1021 | |
|
1022 | 1022 | @observe('greedy') |
|
1023 | 1023 | def _greedy_changed(self, change): |
|
1024 | 1024 | """update the splitter and readline delims when greedy is changed""" |
|
1025 | 1025 | if change['new']: |
|
1026 | 1026 | self.splitter.delims = GREEDY_DELIMS |
|
1027 | 1027 | else: |
|
1028 | 1028 | self.splitter.delims = DELIMS |
|
1029 | 1029 | |
|
1030 | 1030 | dict_keys_only = Bool(False, |
|
1031 | 1031 | help="""Whether to show dict key matches only""") |
|
1032 | 1032 | |
|
1033 | 1033 | merge_completions = Bool(True, |
|
1034 | 1034 | help="""Whether to merge completion results into a single list |
|
1035 | 1035 | |
|
1036 | 1036 | If False, only the completion results from the first non-empty |
|
1037 | 1037 | completer will be returned. |
|
1038 | 1038 | """ |
|
1039 | 1039 | ).tag(config=True) |
|
1040 | 1040 | omit__names = Enum((0,1,2), default_value=2, |
|
1041 | 1041 | help="""Instruct the completer to omit private method names |
|
1042 | 1042 | |
|
1043 | 1043 | Specifically, when completing on ``object.<tab>``. |
|
1044 | 1044 | |
|
1045 | 1045 | When 2 [default]: all names that start with '_' will be excluded. |
|
1046 | 1046 | |
|
1047 | 1047 | When 1: all 'magic' names (``__foo__``) will be excluded. |
|
1048 | 1048 | |
|
1049 | 1049 | When 0: nothing will be excluded. |
|
1050 | 1050 | """ |
|
1051 | 1051 | ).tag(config=True) |
|
1052 | 1052 | limit_to__all__ = Bool(False, |
|
1053 | 1053 | help=""" |
|
1054 | 1054 | DEPRECATED as of version 5.0. |
|
1055 | 1055 | |
|
1056 | 1056 | Instruct the completer to use __all__ for the completion |
|
1057 | 1057 | |
|
1058 | 1058 | Specifically, when completing on ``object.<tab>``. |
|
1059 | 1059 | |
|
1060 | 1060 | When True: only those names in obj.__all__ will be included. |
|
1061 | 1061 | |
|
1062 | 1062 | When False [default]: the __all__ attribute is ignored |
|
1063 | 1063 | """, |
|
1064 | 1064 | ).tag(config=True) |
|
1065 | 1065 | |
|
1066 | 1066 | @observe('limit_to__all__') |
|
1067 | 1067 | def _limit_to_all_changed(self, change): |
|
1068 | 1068 | warnings.warn('`IPython.core.IPCompleter.limit_to__all__` configuration ' |
|
1069 | 1069 | 'value has been deprecated since IPython 5.0, will be made to have ' |
|
1070 | 1070 | 'no effects and then removed in future version of IPython.', |
|
1071 | 1071 | UserWarning) |
|
1072 | 1072 | |
|
1073 | 1073 | def __init__(self, shell=None, namespace=None, global_namespace=None, |
|
1074 | 1074 | use_readline=_deprecation_readline_sentinel, config=None, **kwargs): |
|
1075 | 1075 | """IPCompleter() -> completer |
|
1076 | 1076 | |
|
1077 | 1077 | Return a completer object. |
|
1078 | 1078 | |
|
1079 | 1079 | Parameters |
|
1080 | 1080 | ---------- |
|
1081 | 1081 | |
|
1082 | 1082 | shell |
|
1083 | 1083 | a pointer to the ipython shell itself. This is needed |
|
1084 | 1084 | because this completer knows about magic functions, and those can |
|
1085 | 1085 | only be accessed via the ipython instance. |
|
1086 | 1086 | |
|
1087 | 1087 | namespace : dict, optional |
|
1088 | 1088 | an optional dict where completions are performed. |
|
1089 | 1089 | |
|
1090 | 1090 | global_namespace : dict, optional |
|
1091 | 1091 | secondary optional dict for completions, to |
|
1092 | 1092 | handle cases (such as IPython embedded inside functions) where |
|
1093 | 1093 | both Python scopes are visible. |
|
1094 | 1094 | |
|
1095 | 1095 | use_readline : bool, optional |
|
1096 | 1096 | DEPRECATED, ignored since IPython 6.0, will have no effects |
|
1097 | 1097 | """ |
|
1098 | 1098 | |
|
1099 | 1099 | self.magic_escape = ESC_MAGIC |
|
1100 | 1100 | self.splitter = CompletionSplitter() |
|
1101 | 1101 | |
|
1102 | 1102 | if use_readline is not _deprecation_readline_sentinel: |
|
1103 | 1103 | warnings.warn('The `use_readline` parameter is deprecated and ignored since IPython 6.0.', |
|
1104 | 1104 | DeprecationWarning, stacklevel=2) |
|
1105 | 1105 | |
|
1106 | 1106 | # _greedy_changed() depends on splitter and readline being defined: |
|
1107 | 1107 | Completer.__init__(self, namespace=namespace, global_namespace=global_namespace, |
|
1108 | 1108 | config=config, **kwargs) |
|
1109 | 1109 | |
|
1110 | 1110 | # List where completion matches will be stored |
|
1111 | 1111 | self.matches = [] |
|
1112 | 1112 | self.shell = shell |
|
1113 | 1113 | # Regexp to split filenames with spaces in them |
|
1114 | 1114 | self.space_name_re = re.compile(r'([^\\] )') |
|
1115 | 1115 | # Hold a local ref. to glob.glob for speed |
|
1116 | 1116 | self.glob = glob.glob |
|
1117 | 1117 | |
|
1118 | 1118 | # Determine if we are running on 'dumb' terminals, like (X)Emacs |
|
1119 | 1119 | # buffers, to avoid completion problems. |
|
1120 | 1120 | term = os.environ.get('TERM','xterm') |
|
1121 | 1121 | self.dumb_terminal = term in ['dumb','emacs'] |
|
1122 | 1122 | |
|
1123 | 1123 | # Special handling of backslashes needed in win32 platforms |
|
1124 | 1124 | if sys.platform == "win32": |
|
1125 | 1125 | self.clean_glob = self._clean_glob_win32 |
|
1126 | 1126 | else: |
|
1127 | 1127 | self.clean_glob = self._clean_glob |
|
1128 | 1128 | |
|
1129 | 1129 | #regexp to parse docstring for function signature |
|
1130 | 1130 | self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*') |
|
1131 | 1131 | self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)') |
|
1132 | 1132 | #use this if positional argument name is also needed |
|
1133 | 1133 | #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)') |
|
1134 | 1134 | |
|
1135 | 1135 | self.magic_arg_matchers = [ |
|
1136 | 1136 | self.magic_config_matches, |
|
1137 | 1137 | self.magic_color_matches, |
|
1138 | 1138 | ] |
|
1139 | 1139 | |
|
1140 | 1140 | # This is set externally by InteractiveShell |
|
1141 | 1141 | self.custom_completers = None |
|
1142 | 1142 | |
|
1143 | 1143 | @property |
|
1144 | 1144 | def matchers(self): |
|
1145 | 1145 | """All active matcher routines for completion""" |
|
1146 | 1146 | if self.dict_keys_only: |
|
1147 | 1147 | return [self.dict_key_matches] |
|
1148 | 1148 | |
|
1149 | 1149 | if self.use_jedi: |
|
1150 | 1150 | return [ |
|
1151 | 1151 | *self.custom_matchers, |
|
1152 | 1152 | self.dict_key_matches, |
|
1153 | 1153 | self.file_matches, |
|
1154 | 1154 | self.magic_matches, |
|
1155 | 1155 | ] |
|
1156 | 1156 | else: |
|
1157 | 1157 | return [ |
|
1158 | 1158 | *self.custom_matchers, |
|
1159 | 1159 | self.dict_key_matches, |
|
1160 | 1160 | self.python_matches, |
|
1161 | 1161 | self.file_matches, |
|
1162 | 1162 | self.magic_matches, |
|
1163 | 1163 | self.python_func_kw_matches, |
|
1164 | 1164 | ] |
|
1165 | 1165 | |
|
1166 | 1166 | def all_completions(self, text) -> List[str]: |
|
1167 | 1167 | """ |
|
1168 | 1168 | Wrapper around the completion methods for the benefit of emacs. |
|
1169 | 1169 | """ |
|
1170 | 1170 | prefix = text.rpartition('.')[0] |
|
1171 | 1171 | with provisionalcompleter(): |
|
1172 | 1172 | return ['.'.join([prefix, c.text]) if prefix and self.use_jedi else c.text |
|
1173 | 1173 | for c in self.completions(text, len(text))] |
|
1174 | 1174 | |
|
1175 | 1175 | return self.complete(text)[1] |
|
1176 | 1176 | |
|
1177 | 1177 | def _clean_glob(self, text): |
|
1178 | 1178 | return self.glob("%s*" % text) |
|
1179 | 1179 | |
|
1180 | 1180 | def _clean_glob_win32(self,text): |
|
1181 | 1181 | return [f.replace("\\","/") |
|
1182 | 1182 | for f in self.glob("%s*" % text)] |
|
1183 | 1183 | |
|
1184 | 1184 | def file_matches(self, text): |
|
1185 | 1185 | """Match filenames, expanding ~USER type strings. |
|
1186 | 1186 | |
|
1187 | 1187 | Most of the seemingly convoluted logic in this completer is an |
|
1188 | 1188 | attempt to handle filenames with spaces in them. And yet it's not |
|
1189 | 1189 | quite perfect, because Python's readline doesn't expose all of the |
|
1190 | 1190 | GNU readline details needed for this to be done correctly. |
|
1191 | 1191 | |
|
1192 | 1192 | For a filename with a space in it, the printed completions will be |
|
1193 | 1193 | only the parts after what's already been typed (instead of the |
|
1194 | 1194 | full completions, as is normally done). I don't think with the |
|
1195 | 1195 | current (as of Python 2.3) Python readline it's possible to do |
|
1196 | 1196 | better.""" |
|
1197 | 1197 | |
|
1198 | 1198 | # chars that require escaping with backslash - i.e. chars |
|
1199 | 1199 | # that readline treats incorrectly as delimiters, but we |
|
1200 | 1200 | # don't want to treat as delimiters in filename matching |
|
1201 | 1201 | # when escaped with backslash |
|
1202 | 1202 | if text.startswith('!'): |
|
1203 | 1203 | text = text[1:] |
|
1204 | 1204 | text_prefix = u'!' |
|
1205 | 1205 | else: |
|
1206 | 1206 | text_prefix = u'' |
|
1207 | 1207 | |
|
1208 | 1208 | text_until_cursor = self.text_until_cursor |
|
1209 | 1209 | # track strings with open quotes |
|
1210 | 1210 | open_quotes = has_open_quotes(text_until_cursor) |
|
1211 | 1211 | |
|
1212 | 1212 | if '(' in text_until_cursor or '[' in text_until_cursor: |
|
1213 | 1213 | lsplit = text |
|
1214 | 1214 | else: |
|
1215 | 1215 | try: |
|
1216 | 1216 | # arg_split ~ shlex.split, but with unicode bugs fixed by us |
|
1217 | 1217 | lsplit = arg_split(text_until_cursor)[-1] |
|
1218 | 1218 | except ValueError: |
|
1219 | 1219 | # typically an unmatched ", or backslash without escaped char. |
|
1220 | 1220 | if open_quotes: |
|
1221 | 1221 | lsplit = text_until_cursor.split(open_quotes)[-1] |
|
1222 | 1222 | else: |
|
1223 | 1223 | return [] |
|
1224 | 1224 | except IndexError: |
|
1225 | 1225 | # tab pressed on empty line |
|
1226 | 1226 | lsplit = "" |
|
1227 | 1227 | |
|
1228 | 1228 | if not open_quotes and lsplit != protect_filename(lsplit): |
|
1229 | 1229 | # if protectables are found, do matching on the whole escaped name |
|
1230 | 1230 | has_protectables = True |
|
1231 | 1231 | text0,text = text,lsplit |
|
1232 | 1232 | else: |
|
1233 | 1233 | has_protectables = False |
|
1234 | 1234 | text = os.path.expanduser(text) |
|
1235 | 1235 | |
|
1236 | 1236 | if text == "": |
|
1237 | 1237 | return [text_prefix + protect_filename(f) for f in self.glob("*")] |
|
1238 | 1238 | |
|
1239 | 1239 | # Compute the matches from the filesystem |
|
1240 | 1240 | if sys.platform == 'win32': |
|
1241 | 1241 | m0 = self.clean_glob(text) |
|
1242 | 1242 | else: |
|
1243 | 1243 | m0 = self.clean_glob(text.replace('\\', '')) |
|
1244 | 1244 | |
|
1245 | 1245 | if has_protectables: |
|
1246 | 1246 | # If we had protectables, we need to revert our changes to the |
|
1247 | 1247 | # beginning of filename so that we don't double-write the part |
|
1248 | 1248 | # of the filename we have so far |
|
1249 | 1249 | len_lsplit = len(lsplit) |
|
1250 | 1250 | matches = [text_prefix + text0 + |
|
1251 | 1251 | protect_filename(f[len_lsplit:]) for f in m0] |
|
1252 | 1252 | else: |
|
1253 | 1253 | if open_quotes: |
|
1254 | 1254 | # if we have a string with an open quote, we don't need to |
|
1255 | 1255 | # protect the names beyond the quote (and we _shouldn't_, as |
|
1256 | 1256 | # it would cause bugs when the filesystem call is made). |
|
1257 | 1257 | matches = m0 if sys.platform == "win32" else\ |
|
1258 | 1258 | [protect_filename(f, open_quotes) for f in m0] |
|
1259 | 1259 | else: |
|
1260 | 1260 | matches = [text_prefix + |
|
1261 | 1261 | protect_filename(f) for f in m0] |
|
1262 | 1262 | |
|
1263 | 1263 | # Mark directories in input list by appending '/' to their names. |
|
1264 | 1264 | return [x+'/' if os.path.isdir(x) else x for x in matches] |
|
1265 | 1265 | |
|
1266 | 1266 | def magic_matches(self, text): |
|
1267 | 1267 | """Match magics""" |
|
1268 | 1268 | # Get all shell magics now rather than statically, so magics loaded at |
|
1269 | 1269 | # runtime show up too. |
|
1270 | 1270 | lsm = self.shell.magics_manager.lsmagic() |
|
1271 | 1271 | line_magics = lsm['line'] |
|
1272 | 1272 | cell_magics = lsm['cell'] |
|
1273 | 1273 | pre = self.magic_escape |
|
1274 | 1274 | pre2 = pre+pre |
|
1275 | 1275 | |
|
1276 | 1276 | explicit_magic = text.startswith(pre) |
|
1277 | 1277 | |
|
1278 | 1278 | # Completion logic: |
|
1279 | 1279 | # - user gives %%: only do cell magics |
|
1280 | 1280 | # - user gives %: do both line and cell magics |
|
1281 | 1281 | # - no prefix: do both |
|
1282 | 1282 | # In other words, line magics are skipped if the user gives %% explicitly |
|
1283 | 1283 | # |
|
1284 | 1284 | # We also exclude magics that match any currently visible names: |
|
1285 | 1285 | # https://github.com/ipython/ipython/issues/4877, unless the user has |
|
1286 | 1286 | # typed a %: |
|
1287 | 1287 | # https://github.com/ipython/ipython/issues/10754 |
|
1288 | 1288 | bare_text = text.lstrip(pre) |
|
1289 | 1289 | global_matches = self.global_matches(bare_text) |
|
1290 | 1290 | if not explicit_magic: |
|
1291 | 1291 | def matches(magic): |
|
1292 | 1292 | """ |
|
1293 | 1293 | Filter magics, in particular remove magics that match |
|
1294 | 1294 | a name present in global namespace. |
|
1295 | 1295 | """ |
|
1296 | 1296 | return ( magic.startswith(bare_text) and |
|
1297 | 1297 | magic not in global_matches ) |
|
1298 | 1298 | else: |
|
1299 | 1299 | def matches(magic): |
|
1300 | 1300 | return magic.startswith(bare_text) |
|
1301 | 1301 | |
|
1302 | 1302 | comp = [ pre2+m for m in cell_magics if matches(m)] |
|
1303 | 1303 | if not text.startswith(pre2): |
|
1304 | 1304 | comp += [ pre+m for m in line_magics if matches(m)] |
|
1305 | 1305 | |
|
1306 | 1306 | return comp |
|
1307 | 1307 | |
|
1308 | 1308 | def magic_config_matches(self, text:str) -> List[str]: |
|
1309 | 1309 | """ Match class names and attributes for %config magic """ |
|
1310 | 1310 | texts = text.strip().split() |
|
1311 | 1311 | |
|
1312 | 1312 | if len(texts) > 0 and (texts[0] == 'config' or texts[0] == '%config'): |
|
1313 | 1313 | # get all configuration classes |
|
1314 | 1314 | classes = sorted(set([ c for c in self.shell.configurables |
|
1315 | 1315 | if c.__class__.class_traits(config=True) |
|
1316 | 1316 | ]), key=lambda x: x.__class__.__name__) |
|
1317 | 1317 | classnames = [ c.__class__.__name__ for c in classes ] |
|
1318 | 1318 | |
|
1319 | 1319 | # return all classnames if config or %config is given |
|
1320 | 1320 | if len(texts) == 1: |
|
1321 | 1321 | return classnames |
|
1322 | 1322 | |
|
1323 | 1323 | # match classname |
|
1324 | 1324 | classname_texts = texts[1].split('.') |
|
1325 | 1325 | classname = classname_texts[0] |
|
1326 | 1326 | classname_matches = [ c for c in classnames |
|
1327 | 1327 | if c.startswith(classname) ] |
|
1328 | 1328 | |
|
1329 | 1329 | # return matched classes or the matched class with attributes |
|
1330 | 1330 | if texts[1].find('.') < 0: |
|
1331 | 1331 | return classname_matches |
|
1332 | 1332 | elif len(classname_matches) == 1 and \ |
|
1333 | 1333 | classname_matches[0] == classname: |
|
1334 | 1334 | cls = classes[classnames.index(classname)].__class__ |
|
1335 | 1335 | help = cls.class_get_help() |
|
1336 | 1336 | # strip leading '--' from cl-args: |
|
1337 | 1337 | help = re.sub(re.compile(r'^--', re.MULTILINE), '', help) |
|
1338 | 1338 | return [ attr.split('=')[0] |
|
1339 | 1339 | for attr in help.strip().splitlines() |
|
1340 | 1340 | if attr.startswith(texts[1]) ] |
|
1341 | 1341 | return [] |
|
1342 | 1342 | |
|
1343 | 1343 | def magic_color_matches(self, text:str) -> List[str] : |
|
1344 | 1344 | """ Match color schemes for %colors magic""" |
|
1345 | 1345 | texts = text.split() |
|
1346 | 1346 | if text.endswith(' '): |
|
1347 | 1347 | # .split() strips off the trailing whitespace. Add '' back |
|
1348 | 1348 | # so that: '%colors ' -> ['%colors', ''] |
|
1349 | 1349 | texts.append('') |
|
1350 | 1350 | |
|
1351 | 1351 | if len(texts) == 2 and (texts[0] == 'colors' or texts[0] == '%colors'): |
|
1352 | 1352 | prefix = texts[1] |
|
1353 | 1353 | return [ color for color in InspectColors.keys() |
|
1354 | 1354 | if color.startswith(prefix) ] |
|
1355 | 1355 | return [] |
|
1356 | 1356 | |
|
1357 | 1357 | def _jedi_matches(self, cursor_column:int, cursor_line:int, text:str): |
|
1358 | 1358 | """ |
|
1359 | 1359 | |
|
1360 | 1360 | Return a list of :any:`jedi.api.Completions` object from a ``text`` and |
|
1361 | 1361 | cursor position. |
|
1362 | 1362 | |
|
1363 | 1363 | Parameters |
|
1364 | 1364 | ---------- |
|
1365 | 1365 | cursor_column : int |
|
1366 | 1366 | column position of the cursor in ``text``, 0-indexed. |
|
1367 | 1367 | cursor_line : int |
|
1368 | 1368 | line position of the cursor in ``text``, 0-indexed |
|
1369 | 1369 | text : str |
|
1370 | 1370 | text to complete |
|
1371 | 1371 | |
|
1372 | 1372 | Debugging |
|
1373 | 1373 | --------- |
|
1374 | 1374 | |
|
1375 | 1375 | If ``IPCompleter.debug`` is ``True`` may return a :any:`_FakeJediCompletion` |
|
1376 | 1376 | object containing a string with the Jedi debug information attached. |
|
1377 | 1377 | """ |
|
1378 | 1378 | namespaces = [self.namespace] |
|
1379 | 1379 | if self.global_namespace is not None: |
|
1380 | 1380 | namespaces.append(self.global_namespace) |
|
1381 | 1381 | |
|
1382 | 1382 | completion_filter = lambda x:x |
|
1383 | 1383 | offset = cursor_to_position(text, cursor_line, cursor_column) |
|
1384 | 1384 | # filter output if we are completing for object members |
|
1385 | 1385 | if offset: |
|
1386 | 1386 | pre = text[offset-1] |
|
1387 | 1387 | if pre == '.': |
|
1388 | 1388 | if self.omit__names == 2: |
|
1389 | 1389 | completion_filter = lambda c:not c.name.startswith('_') |
|
1390 | 1390 | elif self.omit__names == 1: |
|
1391 | 1391 | completion_filter = lambda c:not (c.name.startswith('__') and c.name.endswith('__')) |
|
1392 | 1392 | elif self.omit__names == 0: |
|
1393 | 1393 | completion_filter = lambda x:x |
|
1394 | 1394 | else: |
|
1395 | 1395 | raise ValueError("Don't understand self.omit__names == {}".format(self.omit__names)) |
|
1396 | 1396 | |
|
1397 | 1397 | interpreter = jedi.Interpreter(text[:offset], namespaces) |
|
1398 | 1398 | try_jedi = True |
|
1399 | 1399 | |
|
1400 | 1400 | try: |
|
1401 | 1401 | # find the first token in the current tree -- if it is a ' or " then we are in a string |
|
1402 | 1402 | completing_string = False |
|
1403 | 1403 | try: |
|
1404 | 1404 | first_child = next(c for c in interpreter._get_module().tree_node.children if hasattr(c, 'value')) |
|
1405 | 1405 | except StopIteration: |
|
1406 | 1406 | pass |
|
1407 | 1407 | else: |
|
1408 | 1408 | # note the value may be ', ", or it may also be ''' or """, or |
|
1409 | 1409 | # in some cases, """what/you/typed..., but all of these are |
|
1410 | 1410 | # strings. |
|
1411 | 1411 | completing_string = len(first_child.value) > 0 and first_child.value[0] in {"'", '"'} |
|
1412 | 1412 | |
|
1413 | 1413 | # if we are in a string jedi is likely not the right candidate for |
|
1414 | 1414 | # now. Skip it. |
|
1415 | 1415 | try_jedi = not completing_string |
|
1416 | 1416 | except Exception as e: |
|
1417 | 1417 | # many of things can go wrong, we are using private API just don't crash. |
|
1418 | 1418 | if self.debug: |
|
1419 | 1419 | print("Error detecting if completing a non-finished string :", e, '|') |
|
1420 | 1420 | |
|
1421 | 1421 | if not try_jedi: |
|
1422 | 1422 | return [] |
|
1423 | 1423 | try: |
|
1424 | 1424 | return filter(completion_filter, interpreter.complete(column=cursor_column, line=cursor_line + 1)) |
|
1425 | 1425 | except Exception as e: |
|
1426 | 1426 | if self.debug: |
|
1427 | 1427 | return [_FakeJediCompletion('Oops Jedi has crashed, please report a bug with the following:\n"""\n%s\ns"""' % (e))] |
|
1428 | 1428 | else: |
|
1429 | 1429 | return [] |
|
1430 | 1430 | |
|
1431 | 1431 | def python_matches(self, text): |
|
1432 | 1432 | """Match attributes or global python names""" |
|
1433 | 1433 | if "." in text: |
|
1434 | 1434 | try: |
|
1435 | 1435 | matches = self.attr_matches(text) |
|
1436 | 1436 | if text.endswith('.') and self.omit__names: |
|
1437 | 1437 | if self.omit__names == 1: |
|
1438 | 1438 | # true if txt is _not_ a __ name, false otherwise: |
|
1439 | 1439 | no__name = (lambda txt: |
|
1440 | 1440 | re.match(r'.*\.__.*?__',txt) is None) |
|
1441 | 1441 | else: |
|
1442 | 1442 | # true if txt is _not_ a _ name, false otherwise: |
|
1443 | 1443 | no__name = (lambda txt: |
|
1444 | 1444 | re.match(r'\._.*?',txt[txt.rindex('.'):]) is None) |
|
1445 | 1445 | matches = filter(no__name, matches) |
|
1446 | 1446 | except NameError: |
|
1447 | 1447 | # catches <undefined attributes>.<tab> |
|
1448 | 1448 | matches = [] |
|
1449 | 1449 | else: |
|
1450 | 1450 | matches = self.global_matches(text) |
|
1451 | 1451 | return matches |
|
1452 | 1452 | |
|
1453 | 1453 | def _default_arguments_from_docstring(self, doc): |
|
1454 | 1454 | """Parse the first line of docstring for call signature. |
|
1455 | 1455 | |
|
1456 | 1456 | Docstring should be of the form 'min(iterable[, key=func])\n'. |
|
1457 | 1457 | It can also parse cython docstring of the form |
|
1458 | 1458 | 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'. |
|
1459 | 1459 | """ |
|
1460 | 1460 | if doc is None: |
|
1461 | 1461 | return [] |
|
1462 | 1462 | |
|
1463 | 1463 | #care only the firstline |
|
1464 | 1464 | line = doc.lstrip().splitlines()[0] |
|
1465 | 1465 | |
|
1466 | 1466 | #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*') |
|
1467 | 1467 | #'min(iterable[, key=func])\n' -> 'iterable[, key=func]' |
|
1468 | 1468 | sig = self.docstring_sig_re.search(line) |
|
1469 | 1469 | if sig is None: |
|
1470 | 1470 | return [] |
|
1471 | 1471 | # iterable[, key=func]' -> ['iterable[' ,' key=func]'] |
|
1472 | 1472 | sig = sig.groups()[0].split(',') |
|
1473 | 1473 | ret = [] |
|
1474 | 1474 | for s in sig: |
|
1475 | 1475 | #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)') |
|
1476 | 1476 | ret += self.docstring_kwd_re.findall(s) |
|
1477 | 1477 | return ret |
|
1478 | 1478 | |
|
1479 | 1479 | def _default_arguments(self, obj): |
|
1480 | 1480 | """Return the list of default arguments of obj if it is callable, |
|
1481 | 1481 | or empty list otherwise.""" |
|
1482 | 1482 | call_obj = obj |
|
1483 | 1483 | ret = [] |
|
1484 | 1484 | if inspect.isbuiltin(obj): |
|
1485 | 1485 | pass |
|
1486 | 1486 | elif not (inspect.isfunction(obj) or inspect.ismethod(obj)): |
|
1487 | 1487 | if inspect.isclass(obj): |
|
1488 | 1488 | #for cython embedsignature=True the constructor docstring |
|
1489 | 1489 | #belongs to the object itself not __init__ |
|
1490 | 1490 | ret += self._default_arguments_from_docstring( |
|
1491 | 1491 | getattr(obj, '__doc__', '')) |
|
1492 | 1492 | # for classes, check for __init__,__new__ |
|
1493 | 1493 | call_obj = (getattr(obj, '__init__', None) or |
|
1494 | 1494 | getattr(obj, '__new__', None)) |
|
1495 | 1495 | # for all others, check if they are __call__able |
|
1496 | 1496 | elif hasattr(obj, '__call__'): |
|
1497 | 1497 | call_obj = obj.__call__ |
|
1498 | 1498 | ret += self._default_arguments_from_docstring( |
|
1499 | 1499 | getattr(call_obj, '__doc__', '')) |
|
1500 | 1500 | |
|
1501 | 1501 | _keeps = (inspect.Parameter.KEYWORD_ONLY, |
|
1502 | 1502 | inspect.Parameter.POSITIONAL_OR_KEYWORD) |
|
1503 | 1503 | |
|
1504 | 1504 | try: |
|
1505 | 1505 | sig = inspect.signature(obj) |
|
1506 | 1506 | ret.extend(k for k, v in sig.parameters.items() if |
|
1507 | 1507 | v.kind in _keeps) |
|
1508 | 1508 | except ValueError: |
|
1509 | 1509 | pass |
|
1510 | 1510 | |
|
1511 | 1511 | return list(set(ret)) |
|
1512 | 1512 | |
|
1513 | 1513 | def python_func_kw_matches(self,text): |
|
1514 | 1514 | """Match named parameters (kwargs) of the last open function""" |
|
1515 | 1515 | |
|
1516 | 1516 | if "." in text: # a parameter cannot be dotted |
|
1517 | 1517 | return [] |
|
1518 | 1518 | try: regexp = self.__funcParamsRegex |
|
1519 | 1519 | except AttributeError: |
|
1520 | 1520 | regexp = self.__funcParamsRegex = re.compile(r''' |
|
1521 | 1521 | '.*?(?<!\\)' | # single quoted strings or |
|
1522 | 1522 | ".*?(?<!\\)" | # double quoted strings or |
|
1523 | 1523 | \w+ | # identifier |
|
1524 | 1524 | \S # other characters |
|
1525 | 1525 | ''', re.VERBOSE | re.DOTALL) |
|
1526 | 1526 | # 1. find the nearest identifier that comes before an unclosed |
|
1527 | 1527 | # parenthesis before the cursor |
|
1528 | 1528 | # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo" |
|
1529 | 1529 | tokens = regexp.findall(self.text_until_cursor) |
|
1530 | 1530 | iterTokens = reversed(tokens); openPar = 0 |
|
1531 | 1531 | |
|
1532 | 1532 | for token in iterTokens: |
|
1533 | 1533 | if token == ')': |
|
1534 | 1534 | openPar -= 1 |
|
1535 | 1535 | elif token == '(': |
|
1536 | 1536 | openPar += 1 |
|
1537 | 1537 | if openPar > 0: |
|
1538 | 1538 | # found the last unclosed parenthesis |
|
1539 | 1539 | break |
|
1540 | 1540 | else: |
|
1541 | 1541 | return [] |
|
1542 | 1542 | # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" ) |
|
1543 | 1543 | ids = [] |
|
1544 | 1544 | isId = re.compile(r'\w+$').match |
|
1545 | 1545 | |
|
1546 | 1546 | while True: |
|
1547 | 1547 | try: |
|
1548 | 1548 | ids.append(next(iterTokens)) |
|
1549 | 1549 | if not isId(ids[-1]): |
|
1550 | 1550 | ids.pop(); break |
|
1551 | 1551 | if not next(iterTokens) == '.': |
|
1552 | 1552 | break |
|
1553 | 1553 | except StopIteration: |
|
1554 | 1554 | break |
|
1555 | 1555 | |
|
1556 | 1556 | # Find all named arguments already assigned to, as to avoid suggesting |
|
1557 | 1557 | # them again |
|
1558 | 1558 | usedNamedArgs = set() |
|
1559 | 1559 | par_level = -1 |
|
1560 | 1560 | for token, next_token in zip(tokens, tokens[1:]): |
|
1561 | 1561 | if token == '(': |
|
1562 | 1562 | par_level += 1 |
|
1563 | 1563 | elif token == ')': |
|
1564 | 1564 | par_level -= 1 |
|
1565 | 1565 | |
|
1566 | 1566 | if par_level != 0: |
|
1567 | 1567 | continue |
|
1568 | 1568 | |
|
1569 | 1569 | if next_token != '=': |
|
1570 | 1570 | continue |
|
1571 | 1571 | |
|
1572 | 1572 | usedNamedArgs.add(token) |
|
1573 | 1573 | |
|
1574 | 1574 | argMatches = [] |
|
1575 | 1575 | try: |
|
1576 | 1576 | callableObj = '.'.join(ids[::-1]) |
|
1577 | 1577 | namedArgs = self._default_arguments(eval(callableObj, |
|
1578 | 1578 | self.namespace)) |
|
1579 | 1579 | |
|
1580 | 1580 | # Remove used named arguments from the list, no need to show twice |
|
1581 | 1581 | for namedArg in set(namedArgs) - usedNamedArgs: |
|
1582 | 1582 | if namedArg.startswith(text): |
|
1583 | 1583 | argMatches.append(u"%s=" %namedArg) |
|
1584 | 1584 | except: |
|
1585 | 1585 | pass |
|
1586 | 1586 | |
|
1587 | 1587 | return argMatches |
|
1588 | 1588 | |
|
1589 | 1589 | def dict_key_matches(self, text): |
|
1590 | 1590 | "Match string keys in a dictionary, after e.g. 'foo[' " |
|
1591 | 1591 | def get_keys(obj): |
|
1592 | 1592 | # Objects can define their own completions by defining an |
|
1593 | 1593 | # _ipy_key_completions_() method. |
|
1594 | 1594 | method = get_real_method(obj, '_ipython_key_completions_') |
|
1595 | 1595 | if method is not None: |
|
1596 | 1596 | return method() |
|
1597 | 1597 | |
|
1598 | 1598 | # Special case some common in-memory dict-like types |
|
1599 | 1599 | if isinstance(obj, dict) or\ |
|
1600 | 1600 | _safe_isinstance(obj, 'pandas', 'DataFrame'): |
|
1601 | 1601 | try: |
|
1602 | 1602 | return list(obj.keys()) |
|
1603 | 1603 | except Exception: |
|
1604 | 1604 | return [] |
|
1605 | 1605 | elif _safe_isinstance(obj, 'numpy', 'ndarray') or\ |
|
1606 | 1606 | _safe_isinstance(obj, 'numpy', 'void'): |
|
1607 | 1607 | return obj.dtype.names or [] |
|
1608 | 1608 | return [] |
|
1609 | 1609 | |
|
1610 | 1610 | try: |
|
1611 | 1611 | regexps = self.__dict_key_regexps |
|
1612 | 1612 | except AttributeError: |
|
1613 | 1613 | dict_key_re_fmt = r'''(?x) |
|
1614 | 1614 | ( # match dict-referring expression wrt greedy setting |
|
1615 | 1615 | %s |
|
1616 | 1616 | ) |
|
1617 | 1617 | \[ # open bracket |
|
1618 | 1618 | \s* # and optional whitespace |
|
1619 | 1619 | ([uUbB]? # string prefix (r not handled) |
|
1620 | 1620 | (?: # unclosed string |
|
1621 | 1621 | '(?:[^']|(?<!\\)\\')* |
|
1622 | 1622 | | |
|
1623 | 1623 | "(?:[^"]|(?<!\\)\\")* |
|
1624 | 1624 | ) |
|
1625 | 1625 | )? |
|
1626 | 1626 | $ |
|
1627 | 1627 | ''' |
|
1628 | 1628 | regexps = self.__dict_key_regexps = { |
|
1629 | 1629 | False: re.compile(dict_key_re_fmt % r''' |
|
1630 | 1630 | # identifiers separated by . |
|
1631 | 1631 | (?!\d)\w+ |
|
1632 | 1632 | (?:\.(?!\d)\w+)* |
|
1633 | 1633 | '''), |
|
1634 | 1634 | True: re.compile(dict_key_re_fmt % ''' |
|
1635 | 1635 | .+ |
|
1636 | 1636 | ''') |
|
1637 | 1637 | } |
|
1638 | 1638 | |
|
1639 | 1639 | match = regexps[self.greedy].search(self.text_until_cursor) |
|
1640 | 1640 | if match is None: |
|
1641 | 1641 | return [] |
|
1642 | 1642 | |
|
1643 | 1643 | expr, prefix = match.groups() |
|
1644 | 1644 | try: |
|
1645 | 1645 | obj = eval(expr, self.namespace) |
|
1646 | 1646 | except Exception: |
|
1647 | 1647 | try: |
|
1648 | 1648 | obj = eval(expr, self.global_namespace) |
|
1649 | 1649 | except Exception: |
|
1650 | 1650 | return [] |
|
1651 | 1651 | |
|
1652 | 1652 | keys = get_keys(obj) |
|
1653 | 1653 | if not keys: |
|
1654 | 1654 | return keys |
|
1655 | 1655 | closing_quote, token_offset, matches = match_dict_keys(keys, prefix, self.splitter.delims) |
|
1656 | 1656 | if not matches: |
|
1657 | 1657 | return matches |
|
1658 | 1658 | |
|
1659 | 1659 | # get the cursor position of |
|
1660 | 1660 | # - the text being completed |
|
1661 | 1661 | # - the start of the key text |
|
1662 | 1662 | # - the start of the completion |
|
1663 | 1663 | text_start = len(self.text_until_cursor) - len(text) |
|
1664 | 1664 | if prefix: |
|
1665 | 1665 | key_start = match.start(2) |
|
1666 | 1666 | completion_start = key_start + token_offset |
|
1667 | 1667 | else: |
|
1668 | 1668 | key_start = completion_start = match.end() |
|
1669 | 1669 | |
|
1670 | 1670 | # grab the leading prefix, to make sure all completions start with `text` |
|
1671 | 1671 | if text_start > key_start: |
|
1672 | 1672 | leading = '' |
|
1673 | 1673 | else: |
|
1674 | 1674 | leading = text[text_start:completion_start] |
|
1675 | 1675 | |
|
1676 | 1676 | # the index of the `[` character |
|
1677 | 1677 | bracket_idx = match.end(1) |
|
1678 | 1678 | |
|
1679 | 1679 | # append closing quote and bracket as appropriate |
|
1680 | 1680 | # this is *not* appropriate if the opening quote or bracket is outside |
|
1681 | 1681 | # the text given to this method |
|
1682 | 1682 | suf = '' |
|
1683 | 1683 | continuation = self.line_buffer[len(self.text_until_cursor):] |
|
1684 | 1684 | if key_start > text_start and closing_quote: |
|
1685 | 1685 | # quotes were opened inside text, maybe close them |
|
1686 | 1686 | if continuation.startswith(closing_quote): |
|
1687 | 1687 | continuation = continuation[len(closing_quote):] |
|
1688 | 1688 | else: |
|
1689 | 1689 | suf += closing_quote |
|
1690 | 1690 | if bracket_idx > text_start: |
|
1691 | 1691 | # brackets were opened inside text, maybe close them |
|
1692 | 1692 | if not continuation.startswith(']'): |
|
1693 | 1693 | suf += ']' |
|
1694 | 1694 | |
|
1695 | 1695 | return [leading + k + suf for k in matches] |
|
1696 | 1696 | |
|
1697 | 1697 | def unicode_name_matches(self, text): |
|
1698 | 1698 | u"""Match Latex-like syntax for unicode characters base |
|
1699 | 1699 | on the name of the character. |
|
1700 | 1700 | |
|
1701 | 1701 | This does ``\\GREEK SMALL LETTER ETA`` -> ``Ξ·`` |
|
1702 | 1702 | |
|
1703 | 1703 | Works only on valid python 3 identifier, or on combining characters that |
|
1704 | 1704 | will combine to form a valid identifier. |
|
1705 | 1705 | |
|
1706 | 1706 | Used on Python 3 only. |
|
1707 | 1707 | """ |
|
1708 | 1708 | slashpos = text.rfind('\\') |
|
1709 | 1709 | if slashpos > -1: |
|
1710 | 1710 | s = text[slashpos+1:] |
|
1711 | 1711 | try : |
|
1712 | 1712 | unic = unicodedata.lookup(s) |
|
1713 | 1713 | # allow combining chars |
|
1714 | 1714 | if ('a'+unic).isidentifier(): |
|
1715 | 1715 | return '\\'+s,[unic] |
|
1716 | 1716 | except KeyError: |
|
1717 | 1717 | pass |
|
1718 | 1718 | return u'', [] |
|
1719 | 1719 | |
|
1720 | 1720 | |
|
1721 | 1721 | def latex_matches(self, text): |
|
1722 | 1722 | u"""Match Latex syntax for unicode characters. |
|
1723 | 1723 | |
|
1724 | 1724 | This does both ``\\alp`` -> ``\\alpha`` and ``\\alpha`` -> ``Ξ±`` |
|
1725 | 1725 | """ |
|
1726 | 1726 | slashpos = text.rfind('\\') |
|
1727 | 1727 | if slashpos > -1: |
|
1728 | 1728 | s = text[slashpos:] |
|
1729 | 1729 | if s in latex_symbols: |
|
1730 | 1730 | # Try to complete a full latex symbol to unicode |
|
1731 | 1731 | # \\alpha -> Ξ± |
|
1732 | 1732 | return s, [latex_symbols[s]] |
|
1733 | 1733 | else: |
|
1734 | 1734 | # If a user has partially typed a latex symbol, give them |
|
1735 | 1735 | # a full list of options \al -> [\aleph, \alpha] |
|
1736 | 1736 | matches = [k for k in latex_symbols if k.startswith(s)] |
|
1737 | 1737 | if matches: |
|
1738 | 1738 | return s, matches |
|
1739 | 1739 | return u'', [] |
|
1740 | 1740 | |
|
1741 | 1741 | def dispatch_custom_completer(self, text): |
|
1742 | 1742 | if not self.custom_completers: |
|
1743 | 1743 | return |
|
1744 | 1744 | |
|
1745 | 1745 | line = self.line_buffer |
|
1746 | 1746 | if not line.strip(): |
|
1747 | 1747 | return None |
|
1748 | 1748 | |
|
1749 | 1749 | # Create a little structure to pass all the relevant information about |
|
1750 | 1750 | # the current completion to any custom completer. |
|
1751 | 1751 | event = SimpleNamespace() |
|
1752 | 1752 | event.line = line |
|
1753 | 1753 | event.symbol = text |
|
1754 | 1754 | cmd = line.split(None,1)[0] |
|
1755 | 1755 | event.command = cmd |
|
1756 | 1756 | event.text_until_cursor = self.text_until_cursor |
|
1757 | 1757 | |
|
1758 | 1758 | # for foo etc, try also to find completer for %foo |
|
1759 | 1759 | if not cmd.startswith(self.magic_escape): |
|
1760 | 1760 | try_magic = self.custom_completers.s_matches( |
|
1761 | 1761 | self.magic_escape + cmd) |
|
1762 | 1762 | else: |
|
1763 | 1763 | try_magic = [] |
|
1764 | 1764 | |
|
1765 | 1765 | for c in itertools.chain(self.custom_completers.s_matches(cmd), |
|
1766 | 1766 | try_magic, |
|
1767 | 1767 | self.custom_completers.flat_matches(self.text_until_cursor)): |
|
1768 | 1768 | try: |
|
1769 | 1769 | res = c(event) |
|
1770 | 1770 | if res: |
|
1771 | 1771 | # first, try case sensitive match |
|
1772 | 1772 | withcase = [r for r in res if r.startswith(text)] |
|
1773 | 1773 | if withcase: |
|
1774 | 1774 | return withcase |
|
1775 | 1775 | # if none, then case insensitive ones are ok too |
|
1776 | 1776 | text_low = text.lower() |
|
1777 | 1777 | return [r for r in res if r.lower().startswith(text_low)] |
|
1778 | 1778 | except TryNext: |
|
1779 | 1779 | pass |
|
1780 | 1780 | except KeyboardInterrupt: |
|
1781 | 1781 | """ |
|
1782 | 1782 | If custom completer take too long, |
|
1783 | 1783 | let keyboard interrupt abort and return nothing. |
|
1784 | 1784 | """ |
|
1785 | 1785 | break |
|
1786 | 1786 | |
|
1787 | 1787 | return None |
|
1788 | 1788 | |
|
1789 | 1789 | def completions(self, text: str, offset: int)->Iterator[Completion]: |
|
1790 | 1790 | """ |
|
1791 | 1791 | Returns an iterator over the possible completions |
|
1792 | 1792 | |
|
1793 | 1793 | .. warning:: |
|
1794 | 1794 | |
|
1795 | 1795 | Unstable |
|
1796 | 1796 | |
|
1797 | 1797 | This function is unstable, API may change without warning. |
|
1798 | 1798 | It will also raise unless use in proper context manager. |
|
1799 | 1799 | |
|
1800 | 1800 | Parameters |
|
1801 | 1801 | ---------- |
|
1802 | 1802 | |
|
1803 | 1803 | text:str |
|
1804 | 1804 | Full text of the current input, multi line string. |
|
1805 | 1805 | offset:int |
|
1806 | 1806 | Integer representing the position of the cursor in ``text``. Offset |
|
1807 | 1807 | is 0-based indexed. |
|
1808 | 1808 | |
|
1809 | 1809 | Yields |
|
1810 | 1810 | ------ |
|
1811 | 1811 | :any:`Completion` object |
|
1812 | 1812 | |
|
1813 | 1813 | |
|
1814 | 1814 | The cursor on a text can either be seen as being "in between" |
|
1815 | 1815 | characters or "On" a character depending on the interface visible to |
|
1816 | 1816 | the user. For consistency the cursor being on "in between" characters X |
|
1817 | 1817 | and Y is equivalent to the cursor being "on" character Y, that is to say |
|
1818 | 1818 | the character the cursor is on is considered as being after the cursor. |
|
1819 | 1819 | |
|
1820 | 1820 | Combining characters may span more that one position in the |
|
1821 | 1821 | text. |
|
1822 | 1822 | |
|
1823 | 1823 | |
|
1824 | 1824 | .. note:: |
|
1825 | 1825 | |
|
1826 | 1826 | If ``IPCompleter.debug`` is :any:`True` will yield a ``--jedi/ipython--`` |
|
1827 | 1827 | fake Completion token to distinguish completion returned by Jedi |
|
1828 | 1828 | and usual IPython completion. |
|
1829 | 1829 | |
|
1830 | 1830 | .. note:: |
|
1831 | 1831 | |
|
1832 | 1832 | Completions are not completely deduplicated yet. If identical |
|
1833 | 1833 | completions are coming from different sources this function does not |
|
1834 | 1834 | ensure that each completion object will only be present once. |
|
1835 | 1835 | """ |
|
1836 | 1836 | warnings.warn("_complete is a provisional API (as of IPython 6.0). " |
|
1837 | 1837 | "It may change without warnings. " |
|
1838 | 1838 | "Use in corresponding context manager.", |
|
1839 | 1839 | category=ProvisionalCompleterWarning, stacklevel=2) |
|
1840 | 1840 | |
|
1841 | 1841 | seen = set() |
|
1842 | 1842 | try: |
|
1843 | 1843 | for c in self._completions(text, offset, _timeout=self.jedi_compute_type_timeout/1000): |
|
1844 | 1844 | if c and (c in seen): |
|
1845 | 1845 | continue |
|
1846 | 1846 | yield c |
|
1847 | 1847 | seen.add(c) |
|
1848 | 1848 | except KeyboardInterrupt: |
|
1849 | 1849 | """if completions take too long and users send keyboard interrupt, |
|
1850 | 1850 | do not crash and return ASAP. """ |
|
1851 | 1851 | pass |
|
1852 | 1852 | |
|
1853 | 1853 | def _completions(self, full_text: str, offset: int, *, _timeout)->Iterator[Completion]: |
|
1854 | 1854 | """ |
|
1855 | 1855 | Core completion module.Same signature as :any:`completions`, with the |
|
1856 | 1856 | extra `timeout` parameter (in seconds). |
|
1857 | 1857 | |
|
1858 | 1858 | |
|
1859 | 1859 | Computing jedi's completion ``.type`` can be quite expensive (it is a |
|
1860 | 1860 | lazy property) and can require some warm-up, more warm up than just |
|
1861 | 1861 | computing the ``name`` of a completion. The warm-up can be : |
|
1862 | 1862 | |
|
1863 | 1863 | - Long warm-up the first time a module is encountered after |
|
1864 | 1864 | install/update: actually build parse/inference tree. |
|
1865 | 1865 | |
|
1866 | 1866 | - first time the module is encountered in a session: load tree from |
|
1867 | 1867 | disk. |
|
1868 | 1868 | |
|
1869 | 1869 | We don't want to block completions for tens of seconds so we give the |
|
1870 | 1870 | completer a "budget" of ``_timeout`` seconds per invocation to compute |
|
1871 | 1871 | completions types, the completions that have not yet been computed will |
|
1872 | 1872 | be marked as "unknown" an will have a chance to be computed next round |
|
1873 | 1873 | are things get cached. |
|
1874 | 1874 | |
|
1875 | 1875 | Keep in mind that Jedi is not the only thing treating the completion so |
|
1876 | 1876 | keep the timeout short-ish as if we take more than 0.3 second we still |
|
1877 | 1877 | have lots of processing to do. |
|
1878 | 1878 | |
|
1879 | 1879 | """ |
|
1880 | 1880 | deadline = time.monotonic() + _timeout |
|
1881 | 1881 | |
|
1882 | 1882 | |
|
1883 | 1883 | before = full_text[:offset] |
|
1884 | 1884 | cursor_line, cursor_column = position_to_cursor(full_text, offset) |
|
1885 | 1885 | |
|
1886 | 1886 | matched_text, matches, matches_origin, jedi_matches = self._complete( |
|
1887 | 1887 | full_text=full_text, cursor_line=cursor_line, cursor_pos=cursor_column) |
|
1888 | 1888 | |
|
1889 | 1889 | iter_jm = iter(jedi_matches) |
|
1890 | 1890 | if _timeout: |
|
1891 | 1891 | for jm in iter_jm: |
|
1892 | 1892 | try: |
|
1893 | 1893 | type_ = jm.type |
|
1894 | 1894 | except Exception: |
|
1895 | 1895 | if self.debug: |
|
1896 | 1896 | print("Error in Jedi getting type of ", jm) |
|
1897 | 1897 | type_ = None |
|
1898 | 1898 | delta = len(jm.name_with_symbols) - len(jm.complete) |
|
1899 | 1899 | if type_ == 'function': |
|
1900 | 1900 | signature = _make_signature(jm) |
|
1901 | 1901 | else: |
|
1902 | 1902 | signature = '' |
|
1903 | 1903 | yield Completion(start=offset - delta, |
|
1904 | 1904 | end=offset, |
|
1905 | 1905 | text=jm.name_with_symbols, |
|
1906 | 1906 | type=type_, |
|
1907 | 1907 | signature=signature, |
|
1908 | 1908 | _origin='jedi') |
|
1909 | 1909 | |
|
1910 | 1910 | if time.monotonic() > deadline: |
|
1911 | 1911 | break |
|
1912 | 1912 | |
|
1913 | 1913 | for jm in iter_jm: |
|
1914 | 1914 | delta = len(jm.name_with_symbols) - len(jm.complete) |
|
1915 | 1915 | yield Completion(start=offset - delta, |
|
1916 | 1916 | end=offset, |
|
1917 | 1917 | text=jm.name_with_symbols, |
|
1918 | 1918 | type='<unknown>', # don't compute type for speed |
|
1919 | 1919 | _origin='jedi', |
|
1920 | 1920 | signature='') |
|
1921 | 1921 | |
|
1922 | 1922 | |
|
1923 | 1923 | start_offset = before.rfind(matched_text) |
|
1924 | 1924 | |
|
1925 | 1925 | # TODO: |
|
1926 | 1926 | # Suppress this, right now just for debug. |
|
1927 | 1927 | if jedi_matches and matches and self.debug: |
|
1928 | 1928 | yield Completion(start=start_offset, end=offset, text='--jedi/ipython--', |
|
1929 | 1929 | _origin='debug', type='none', signature='') |
|
1930 | 1930 | |
|
1931 | 1931 | # I'm unsure if this is always true, so let's assert and see if it |
|
1932 | 1932 | # crash |
|
1933 | 1933 | assert before.endswith(matched_text) |
|
1934 | 1934 | for m, t in zip(matches, matches_origin): |
|
1935 | 1935 | yield Completion(start=start_offset, end=offset, text=m, _origin=t, signature='', type='<unknown>') |
|
1936 | 1936 | |
|
1937 | 1937 | |
|
1938 | 1938 | def complete(self, text=None, line_buffer=None, cursor_pos=None): |
|
1939 | 1939 | """Find completions for the given text and line context. |
|
1940 | 1940 | |
|
1941 | 1941 | Note that both the text and the line_buffer are optional, but at least |
|
1942 | 1942 | one of them must be given. |
|
1943 | 1943 | |
|
1944 | 1944 | Parameters |
|
1945 | 1945 | ---------- |
|
1946 | 1946 | text : string, optional |
|
1947 | 1947 | Text to perform the completion on. If not given, the line buffer |
|
1948 | 1948 | is split using the instance's CompletionSplitter object. |
|
1949 | 1949 | |
|
1950 | 1950 | line_buffer : string, optional |
|
1951 | 1951 | If not given, the completer attempts to obtain the current line |
|
1952 | 1952 | buffer via readline. This keyword allows clients which are |
|
1953 | 1953 | requesting for text completions in non-readline contexts to inform |
|
1954 | 1954 | the completer of the entire text. |
|
1955 | 1955 | |
|
1956 | 1956 | cursor_pos : int, optional |
|
1957 | 1957 | Index of the cursor in the full line buffer. Should be provided by |
|
1958 | 1958 | remote frontends where kernel has no access to frontend state. |
|
1959 | 1959 | |
|
1960 | 1960 | Returns |
|
1961 | 1961 | ------- |
|
1962 | 1962 | text : str |
|
1963 | 1963 | Text that was actually used in the completion. |
|
1964 | 1964 | |
|
1965 | 1965 | matches : list |
|
1966 | 1966 | A list of completion matches. |
|
1967 | 1967 | |
|
1968 | 1968 | |
|
1969 | 1969 | .. note:: |
|
1970 | 1970 | |
|
1971 | 1971 | This API is likely to be deprecated and replaced by |
|
1972 | 1972 | :any:`IPCompleter.completions` in the future. |
|
1973 | 1973 | |
|
1974 | 1974 | |
|
1975 | 1975 | """ |
|
1976 | 1976 | warnings.warn('`Completer.complete` is pending deprecation since ' |
|
1977 | 1977 | 'IPython 6.0 and will be replaced by `Completer.completions`.', |
|
1978 | 1978 | PendingDeprecationWarning) |
|
1979 | 1979 | # potential todo, FOLD the 3rd throw away argument of _complete |
|
1980 | 1980 | # into the first 2 one. |
|
1981 | 1981 | return self._complete(line_buffer=line_buffer, cursor_pos=cursor_pos, text=text, cursor_line=0)[:2] |
|
1982 | 1982 | |
|
1983 | 1983 | def _complete(self, *, cursor_line, cursor_pos, line_buffer=None, text=None, |
|
1984 | 1984 | full_text=None) -> Tuple[str, List[str], List[str], Iterable[_FakeJediCompletion]]: |
|
1985 | 1985 | """ |
|
1986 | 1986 | |
|
1987 | 1987 | Like complete but can also returns raw jedi completions as well as the |
|
1988 | 1988 | origin of the completion text. This could (and should) be made much |
|
1989 | 1989 | cleaner but that will be simpler once we drop the old (and stateful) |
|
1990 | 1990 | :any:`complete` API. |
|
1991 | 1991 | |
|
1992 | 1992 | |
|
1993 | 1993 | With current provisional API, cursor_pos act both (depending on the |
|
1994 | 1994 | caller) as the offset in the ``text`` or ``line_buffer``, or as the |
|
1995 | 1995 | ``column`` when passing multiline strings this could/should be renamed |
|
1996 | 1996 | but would add extra noise. |
|
1997 | 1997 | """ |
|
1998 | 1998 | |
|
1999 | 1999 | # if the cursor position isn't given, the only sane assumption we can |
|
2000 | 2000 | # make is that it's at the end of the line (the common case) |
|
2001 | 2001 | if cursor_pos is None: |
|
2002 | 2002 | cursor_pos = len(line_buffer) if text is None else len(text) |
|
2003 | 2003 | |
|
2004 | 2004 | if self.use_main_ns: |
|
2005 | 2005 | self.namespace = __main__.__dict__ |
|
2006 | 2006 | |
|
2007 | 2007 | # if text is either None or an empty string, rely on the line buffer |
|
2008 | 2008 | if (not line_buffer) and full_text: |
|
2009 | 2009 | line_buffer = full_text.split('\n')[cursor_line] |
|
2010 | 2010 | if not text: # issue #11508: check line_buffer before calling split_line |
|
2011 | 2011 | text = self.splitter.split_line(line_buffer, cursor_pos) if line_buffer else '' |
|
2012 | 2012 | |
|
2013 | 2013 | if self.backslash_combining_completions: |
|
2014 | 2014 | # allow deactivation of these on windows. |
|
2015 | 2015 | base_text = text if not line_buffer else line_buffer[:cursor_pos] |
|
2016 | 2016 | latex_text, latex_matches = self.latex_matches(base_text) |
|
2017 | 2017 | if latex_matches: |
|
2018 | 2018 | return latex_text, latex_matches, ['latex_matches']*len(latex_matches), () |
|
2019 | 2019 | name_text = '' |
|
2020 | 2020 | name_matches = [] |
|
2021 | 2021 | # need to add self.fwd_unicode_match() function here when done |
|
2022 | 2022 | for meth in (self.unicode_name_matches, back_latex_name_matches, back_unicode_name_matches, self.fwd_unicode_match): |
|
2023 | 2023 | name_text, name_matches = meth(base_text) |
|
2024 | 2024 | if name_text: |
|
2025 | 2025 | return name_text, name_matches[:MATCHES_LIMIT], \ |
|
2026 | 2026 | [meth.__qualname__]*min(len(name_matches), MATCHES_LIMIT), () |
|
2027 | 2027 | |
|
2028 | 2028 | |
|
2029 | 2029 | # If no line buffer is given, assume the input text is all there was |
|
2030 | 2030 | if line_buffer is None: |
|
2031 | 2031 | line_buffer = text |
|
2032 | 2032 | |
|
2033 | 2033 | self.line_buffer = line_buffer |
|
2034 | 2034 | self.text_until_cursor = self.line_buffer[:cursor_pos] |
|
2035 | 2035 | |
|
2036 | 2036 | # Do magic arg matches |
|
2037 | 2037 | for matcher in self.magic_arg_matchers: |
|
2038 | 2038 | matches = list(matcher(line_buffer))[:MATCHES_LIMIT] |
|
2039 | 2039 | if matches: |
|
2040 | 2040 | origins = [matcher.__qualname__] * len(matches) |
|
2041 | 2041 | return text, matches, origins, () |
|
2042 | 2042 | |
|
2043 | 2043 | # Start with a clean slate of completions |
|
2044 | 2044 | matches = [] |
|
2045 | 2045 | |
|
2046 | 2046 | # FIXME: we should extend our api to return a dict with completions for |
|
2047 | 2047 | # different types of objects. The rlcomplete() method could then |
|
2048 | 2048 | # simply collapse the dict into a list for readline, but we'd have |
|
2049 | 2049 | # richer completion semantics in other environments. |
|
2050 | 2050 | completions = () |
|
2051 | 2051 | if self.use_jedi: |
|
2052 | 2052 | if not full_text: |
|
2053 | 2053 | full_text = line_buffer |
|
2054 | 2054 | completions = self._jedi_matches( |
|
2055 | 2055 | cursor_pos, cursor_line, full_text) |
|
2056 | 2056 | |
|
2057 | 2057 | if self.merge_completions: |
|
2058 | 2058 | matches = [] |
|
2059 | 2059 | for matcher in self.matchers: |
|
2060 | 2060 | try: |
|
2061 | 2061 | matches.extend([(m, matcher.__qualname__) |
|
2062 | 2062 | for m in matcher(text)]) |
|
2063 | 2063 | except: |
|
2064 | 2064 | # Show the ugly traceback if the matcher causes an |
|
2065 | 2065 | # exception, but do NOT crash the kernel! |
|
2066 | 2066 | sys.excepthook(*sys.exc_info()) |
|
2067 | 2067 | else: |
|
2068 | 2068 | for matcher in self.matchers: |
|
2069 | 2069 | matches = [(m, matcher.__qualname__) |
|
2070 | 2070 | for m in matcher(text)] |
|
2071 | 2071 | if matches: |
|
2072 | 2072 | break |
|
2073 | 2073 | |
|
2074 | 2074 | seen = set() |
|
2075 | 2075 | filtered_matches = set() |
|
2076 | 2076 | for m in matches: |
|
2077 | 2077 | t, c = m |
|
2078 | 2078 | if t not in seen: |
|
2079 | 2079 | filtered_matches.add(m) |
|
2080 | 2080 | seen.add(t) |
|
2081 | 2081 | |
|
2082 | 2082 | _filtered_matches = sorted(filtered_matches, key=lambda x: completions_sorting_key(x[0])) |
|
2083 | 2083 | |
|
2084 | 2084 | custom_res = [(m, 'custom') for m in self.dispatch_custom_completer(text) or []] |
|
2085 | 2085 | |
|
2086 | 2086 | _filtered_matches = custom_res or _filtered_matches |
|
2087 | 2087 | |
|
2088 | 2088 | _filtered_matches = _filtered_matches[:MATCHES_LIMIT] |
|
2089 | 2089 | _matches = [m[0] for m in _filtered_matches] |
|
2090 | 2090 | origins = [m[1] for m in _filtered_matches] |
|
2091 | 2091 | |
|
2092 | 2092 | self.matches = _matches |
|
2093 | 2093 | |
|
2094 | 2094 | return text, _matches, origins, completions |
|
2095 | 2095 | |
|
2096 | 2096 | def fwd_unicode_match(self, text:str) -> Tuple[str, list]: |
|
2097 | 2097 | if self._names is None: |
|
2098 | 2098 | self._names = [] |
|
2099 | 2099 | for c in range(0,0x10FFFF + 1): |
|
2100 | 2100 | try: |
|
2101 | 2101 | self._names.append(unicodedata.name(chr(c))) |
|
2102 | 2102 | except ValueError: |
|
2103 | 2103 | pass |
|
2104 | 2104 | |
|
2105 | 2105 | slashpos = text.rfind('\\') |
|
2106 | 2106 | # if text starts with slash |
|
2107 | 2107 | if slashpos > -1: |
|
2108 | 2108 | s = text[slashpos+1:] |
|
2109 | 2109 | candidates = [x for x in self._names if x.startswith(s)] |
|
2110 | 2110 | if candidates: |
|
2111 | 2111 | return s, candidates |
|
2112 | 2112 | else: |
|
2113 | 2113 | return '', () |
|
2114 | 2114 | |
|
2115 | 2115 | # if text does not start with slash |
|
2116 | 2116 | else: |
|
2117 | 2117 | return u'', () |
@@ -1,3907 +1,3935 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """Main IPython class.""" |
|
3 | 3 | |
|
4 | 4 | #----------------------------------------------------------------------------- |
|
5 | 5 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> |
|
6 | 6 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> |
|
7 | 7 | # Copyright (C) 2008-2011 The IPython Development Team |
|
8 | 8 | # |
|
9 | 9 | # Distributed under the terms of the BSD License. The full license is in |
|
10 | 10 | # the file COPYING, distributed as part of this software. |
|
11 | 11 | #----------------------------------------------------------------------------- |
|
12 | 12 | |
|
13 | 13 | |
|
14 | 14 | import abc |
|
15 | 15 | import ast |
|
16 | 16 | import atexit |
|
17 | 17 | import builtins as builtin_mod |
|
18 | 18 | import dis |
|
19 | 19 | import functools |
|
20 | 20 | import inspect |
|
21 | 21 | import os |
|
22 | 22 | import re |
|
23 | 23 | import runpy |
|
24 | 24 | import sys |
|
25 | 25 | import tempfile |
|
26 | 26 | import traceback |
|
27 | 27 | import types |
|
28 | 28 | import subprocess |
|
29 | 29 | import warnings |
|
30 | 30 | from io import open as io_open |
|
31 | 31 | |
|
32 | 32 | from pathlib import Path |
|
33 | 33 | from pickleshare import PickleShareDB |
|
34 | 34 | |
|
35 | 35 | from traitlets.config.configurable import SingletonConfigurable |
|
36 | 36 | from traitlets.utils.importstring import import_item |
|
37 | 37 | from IPython.core import oinspect |
|
38 | 38 | from IPython.core import magic |
|
39 | 39 | from IPython.core import page |
|
40 | 40 | from IPython.core import prefilter |
|
41 | 41 | from IPython.core import ultratb |
|
42 | 42 | from IPython.core.alias import Alias, AliasManager |
|
43 | 43 | from IPython.core.autocall import ExitAutocall |
|
44 | 44 | from IPython.core.builtin_trap import BuiltinTrap |
|
45 | 45 | from IPython.core.events import EventManager, available_events |
|
46 | 46 | from IPython.core.compilerop import CachingCompiler, check_linecache_ipython |
|
47 | 47 | from IPython.core.debugger import InterruptiblePdb |
|
48 | 48 | from IPython.core.display_trap import DisplayTrap |
|
49 | 49 | from IPython.core.displayhook import DisplayHook |
|
50 | 50 | from IPython.core.displaypub import DisplayPublisher |
|
51 | 51 | from IPython.core.error import InputRejected, UsageError |
|
52 | 52 | from IPython.core.extensions import ExtensionManager |
|
53 | 53 | from IPython.core.formatters import DisplayFormatter |
|
54 | 54 | from IPython.core.history import HistoryManager |
|
55 | 55 | from IPython.core.inputtransformer2 import ESC_MAGIC, ESC_MAGIC2 |
|
56 | 56 | from IPython.core.logger import Logger |
|
57 | 57 | from IPython.core.macro import Macro |
|
58 | 58 | from IPython.core.payload import PayloadManager |
|
59 | 59 | from IPython.core.prefilter import PrefilterManager |
|
60 | 60 | from IPython.core.profiledir import ProfileDir |
|
61 | 61 | from IPython.core.usage import default_banner |
|
62 | 62 | from IPython.display import display |
|
63 | 63 | from IPython.testing.skipdoctest import skip_doctest |
|
64 | 64 | from IPython.utils import PyColorize |
|
65 | 65 | from IPython.utils import io |
|
66 | 66 | from IPython.utils import py3compat |
|
67 | 67 | from IPython.utils import openpy |
|
68 | 68 | from IPython.utils.decorators import undoc |
|
69 | 69 | from IPython.utils.io import ask_yes_no |
|
70 | 70 | from IPython.utils.ipstruct import Struct |
|
71 | 71 | from IPython.paths import get_ipython_dir |
|
72 | 72 | from IPython.utils.path import get_home_dir, get_py_filename, ensure_dir_exists |
|
73 | 73 | from IPython.utils.process import system, getoutput |
|
74 | 74 | from IPython.utils.strdispatch import StrDispatch |
|
75 | 75 | from IPython.utils.syspathcontext import prepended_to_syspath |
|
76 | 76 | from IPython.utils.text import format_screen, LSString, SList, DollarFormatter |
|
77 | 77 | from IPython.utils.tempdir import TemporaryDirectory |
|
78 | 78 | from traitlets import ( |
|
79 | 79 | Integer, Bool, CaselessStrEnum, Enum, List, Dict, Unicode, Instance, Type, |
|
80 | 80 | observe, default, validate, Any |
|
81 | 81 | ) |
|
82 | 82 | from warnings import warn |
|
83 | 83 | from logging import error |
|
84 | 84 | import IPython.core.hooks |
|
85 | 85 | |
|
86 | 86 | from typing import List as ListType, Tuple, Optional |
|
87 | 87 | from ast import AST |
|
88 | 88 | |
|
89 | 89 | # NoOpContext is deprecated, but ipykernel imports it from here. |
|
90 | 90 | # See https://github.com/ipython/ipykernel/issues/157 |
|
91 | 91 | # (2016, let's try to remove than in IPython 8.0) |
|
92 | 92 | from IPython.utils.contexts import NoOpContext |
|
93 | 93 | |
|
94 | 94 | try: |
|
95 | 95 | import docrepr.sphinxify as sphx |
|
96 | 96 | |
|
97 | 97 | def sphinxify(oinfo): |
|
98 | 98 | wrapped_docstring = sphx.wrap_main_docstring(oinfo) |
|
99 | 99 | |
|
100 | 100 | def sphinxify_docstring(docstring): |
|
101 | 101 | with TemporaryDirectory() as dirname: |
|
102 | 102 | return { |
|
103 | 103 | "text/html": sphx.sphinxify(wrapped_docstring, dirname), |
|
104 | 104 | "text/plain": docstring, |
|
105 | 105 | } |
|
106 | 106 | |
|
107 | 107 | return sphinxify_docstring |
|
108 | 108 | except ImportError: |
|
109 | 109 | sphinxify = None |
|
110 | 110 | |
|
111 | 111 | |
|
112 | 112 | class ProvisionalWarning(DeprecationWarning): |
|
113 | 113 | """ |
|
114 | 114 | Warning class for unstable features |
|
115 | 115 | """ |
|
116 | 116 | pass |
|
117 | 117 | |
|
118 | 118 | if sys.version_info > (3,8): |
|
119 | 119 | from ast import Module |
|
120 | 120 | else : |
|
121 | 121 | # mock the new API, ignore second argument |
|
122 | 122 | # see https://github.com/ipython/ipython/issues/11590 |
|
123 | 123 | from ast import Module as OriginalModule |
|
124 | 124 | Module = lambda nodelist, type_ignores: OriginalModule(nodelist) |
|
125 | 125 | |
|
126 | 126 | if sys.version_info > (3,6): |
|
127 | 127 | _assign_nodes = (ast.AugAssign, ast.AnnAssign, ast.Assign) |
|
128 | 128 | _single_targets_nodes = (ast.AugAssign, ast.AnnAssign) |
|
129 | 129 | else: |
|
130 | 130 | _assign_nodes = (ast.AugAssign, ast.Assign ) |
|
131 | 131 | _single_targets_nodes = (ast.AugAssign, ) |
|
132 | 132 | |
|
133 | 133 | #----------------------------------------------------------------------------- |
|
134 | 134 | # Await Helpers |
|
135 | 135 | #----------------------------------------------------------------------------- |
|
136 | 136 | |
|
137 | 137 | def removed_co_newlocals(function:types.FunctionType) -> types.FunctionType: |
|
138 | 138 | """Return a function that do not create a new local scope. |
|
139 | 139 | |
|
140 | 140 | Given a function, create a clone of this function where the co_newlocal flag |
|
141 | 141 | has been removed, making this function code actually run in the sourounding |
|
142 | 142 | scope. |
|
143 | 143 | |
|
144 | 144 | We need this in order to run asynchronous code in user level namespace. |
|
145 | 145 | """ |
|
146 | 146 | from types import CodeType, FunctionType |
|
147 | 147 | CO_NEWLOCALS = 0x0002 |
|
148 | 148 | code = function.__code__ |
|
149 | 149 | new_co_flags = code.co_flags & ~CO_NEWLOCALS |
|
150 | 150 | if sys.version_info > (3, 8, 0, 'alpha', 3): |
|
151 | 151 | new_code = code.replace(co_flags=new_co_flags) |
|
152 | 152 | else: |
|
153 | 153 | new_code = CodeType( |
|
154 | 154 | code.co_argcount, |
|
155 | 155 | code.co_kwonlyargcount, |
|
156 | 156 | code.co_nlocals, |
|
157 | 157 | code.co_stacksize, |
|
158 | 158 | new_co_flags, |
|
159 | 159 | code.co_code, |
|
160 | 160 | code.co_consts, |
|
161 | 161 | code.co_names, |
|
162 | 162 | code.co_varnames, |
|
163 | 163 | code.co_filename, |
|
164 | 164 | code.co_name, |
|
165 | 165 | code.co_firstlineno, |
|
166 | 166 | code.co_lnotab, |
|
167 | 167 | code.co_freevars, |
|
168 | 168 | code.co_cellvars |
|
169 | 169 | ) |
|
170 | 170 | return FunctionType(new_code, globals(), function.__name__, function.__defaults__) |
|
171 | 171 | |
|
172 | 172 | |
|
173 | 173 | # we still need to run things using the asyncio eventloop, but there is no |
|
174 | 174 | # async integration |
|
175 | 175 | from .async_helpers import (_asyncio_runner, _asyncify, _pseudo_sync_runner) |
|
176 | 176 | from .async_helpers import _curio_runner, _trio_runner, _should_be_async |
|
177 | 177 | |
|
178 | 178 | |
|
179 | 179 | def _ast_asyncify(cell:str, wrapper_name:str) -> ast.Module: |
|
180 | 180 | """ |
|
181 | 181 | Parse a cell with top-level await and modify the AST to be able to run it later. |
|
182 | 182 | |
|
183 | 183 | Parameter |
|
184 | 184 | --------- |
|
185 | 185 | |
|
186 | 186 | cell: str |
|
187 | 187 | The code cell to asyncronify |
|
188 | 188 | wrapper_name: str |
|
189 | 189 | The name of the function to be used to wrap the passed `cell`. It is |
|
190 | 190 | advised to **not** use a python identifier in order to not pollute the |
|
191 | 191 | global namespace in which the function will be ran. |
|
192 | 192 | |
|
193 | 193 | Return |
|
194 | 194 | ------ |
|
195 | 195 | |
|
196 | 196 | A module object AST containing **one** function named `wrapper_name`. |
|
197 | 197 | |
|
198 | 198 | The given code is wrapped in a async-def function, parsed into an AST, and |
|
199 | 199 | the resulting function definition AST is modified to return the last |
|
200 | 200 | expression. |
|
201 | 201 | |
|
202 | 202 | The last expression or await node is moved into a return statement at the |
|
203 | 203 | end of the function, and removed from its original location. If the last |
|
204 | 204 | node is not Expr or Await nothing is done. |
|
205 | 205 | |
|
206 | 206 | The function `__code__` will need to be later modified (by |
|
207 | 207 | ``removed_co_newlocals``) in a subsequent step to not create new `locals()` |
|
208 | 208 | meaning that the local and global scope are the same, ie as if the body of |
|
209 | 209 | the function was at module level. |
|
210 | 210 | |
|
211 | 211 | Lastly a call to `locals()` is made just before the last expression of the |
|
212 | 212 | function, or just after the last assignment or statement to make sure the |
|
213 | 213 | global dict is updated as python function work with a local fast cache which |
|
214 | 214 | is updated only on `local()` calls. |
|
215 | 215 | """ |
|
216 | 216 | |
|
217 | 217 | from ast import Expr, Await, Return |
|
218 | 218 | if sys.version_info >= (3,8): |
|
219 | 219 | return ast.parse(cell) |
|
220 | 220 | tree = ast.parse(_asyncify(cell)) |
|
221 | 221 | |
|
222 | 222 | function_def = tree.body[0] |
|
223 | 223 | function_def.name = wrapper_name |
|
224 | 224 | try_block = function_def.body[0] |
|
225 | 225 | lastexpr = try_block.body[-1] |
|
226 | 226 | if isinstance(lastexpr, (Expr, Await)): |
|
227 | 227 | try_block.body[-1] = Return(lastexpr.value) |
|
228 | 228 | ast.fix_missing_locations(tree) |
|
229 | 229 | return tree |
|
230 | 230 | #----------------------------------------------------------------------------- |
|
231 | 231 | # Globals |
|
232 | 232 | #----------------------------------------------------------------------------- |
|
233 | 233 | |
|
234 | 234 | # compiled regexps for autoindent management |
|
235 | 235 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') |
|
236 | 236 | |
|
237 | 237 | #----------------------------------------------------------------------------- |
|
238 | 238 | # Utilities |
|
239 | 239 | #----------------------------------------------------------------------------- |
|
240 | 240 | |
|
241 | 241 | @undoc |
|
242 | 242 | def softspace(file, newvalue): |
|
243 | 243 | """Copied from code.py, to remove the dependency""" |
|
244 | 244 | |
|
245 | 245 | oldvalue = 0 |
|
246 | 246 | try: |
|
247 | 247 | oldvalue = file.softspace |
|
248 | 248 | except AttributeError: |
|
249 | 249 | pass |
|
250 | 250 | try: |
|
251 | 251 | file.softspace = newvalue |
|
252 | 252 | except (AttributeError, TypeError): |
|
253 | 253 | # "attribute-less object" or "read-only attributes" |
|
254 | 254 | pass |
|
255 | 255 | return oldvalue |
|
256 | 256 | |
|
257 | 257 | @undoc |
|
258 | 258 | def no_op(*a, **kw): |
|
259 | 259 | pass |
|
260 | 260 | |
|
261 | 261 | |
|
262 | 262 | class SpaceInInput(Exception): pass |
|
263 | 263 | |
|
264 | 264 | |
|
265 | 265 | def get_default_colors(): |
|
266 | 266 | "DEPRECATED" |
|
267 | 267 | warn('get_default_color is deprecated since IPython 5.0, and returns `Neutral` on all platforms.', |
|
268 | 268 | DeprecationWarning, stacklevel=2) |
|
269 | 269 | return 'Neutral' |
|
270 | 270 | |
|
271 | 271 | |
|
272 | 272 | class SeparateUnicode(Unicode): |
|
273 | 273 | r"""A Unicode subclass to validate separate_in, separate_out, etc. |
|
274 | 274 | |
|
275 | 275 | This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``. |
|
276 | 276 | """ |
|
277 | 277 | |
|
278 | 278 | def validate(self, obj, value): |
|
279 | 279 | if value == '0': value = '' |
|
280 | 280 | value = value.replace('\\n','\n') |
|
281 | 281 | return super(SeparateUnicode, self).validate(obj, value) |
|
282 | 282 | |
|
283 | 283 | |
|
284 | 284 | @undoc |
|
285 | 285 | class DummyMod(object): |
|
286 | 286 | """A dummy module used for IPython's interactive module when |
|
287 | 287 | a namespace must be assigned to the module's __dict__.""" |
|
288 | 288 | __spec__ = None |
|
289 | 289 | |
|
290 | 290 | |
|
291 | 291 | class ExecutionInfo(object): |
|
292 | 292 | """The arguments used for a call to :meth:`InteractiveShell.run_cell` |
|
293 | 293 | |
|
294 | 294 | Stores information about what is going to happen. |
|
295 | 295 | """ |
|
296 | 296 | raw_cell = None |
|
297 | 297 | store_history = False |
|
298 | 298 | silent = False |
|
299 | 299 | shell_futures = True |
|
300 | cell_id = None | |
|
300 | 301 | |
|
301 | def __init__(self, raw_cell, store_history, silent, shell_futures): | |
|
302 | def __init__(self, raw_cell, store_history, silent, shell_futures, cell_id): | |
|
302 | 303 | self.raw_cell = raw_cell |
|
303 | 304 | self.store_history = store_history |
|
304 | 305 | self.silent = silent |
|
305 | 306 | self.shell_futures = shell_futures |
|
307 | self.cell_id = cell_id | |
|
306 | 308 | |
|
307 | 309 | def __repr__(self): |
|
308 | 310 | name = self.__class__.__qualname__ |
|
309 |
raw_cell = ( |
|
|
310 |
|
|
|
311 | return '<%s object at %x, raw_cell="%s" store_history=%s silent=%s shell_futures=%s>' %\ | |
|
312 | (name, id(self), raw_cell, self.store_history, self.silent, self.shell_futures) | |
|
311 | raw_cell = ( | |
|
312 | (self.raw_cell[:50] + "..") if len(self.raw_cell) > 50 else self.raw_cell | |
|
313 | ) | |
|
314 | return '<%s object at %x, raw_cell="%s" store_history=%s silent=%s shell_futures=%s cell_id=%s>' % ( | |
|
315 | name, | |
|
316 | id(self), | |
|
317 | raw_cell, | |
|
318 | self.store_history, | |
|
319 | self.silent, | |
|
320 | self.shell_futures, | |
|
321 | self.cell_id, | |
|
322 | ) | |
|
313 | 323 | |
|
314 | 324 | |
|
315 | 325 | class ExecutionResult(object): |
|
316 | 326 | """The result of a call to :meth:`InteractiveShell.run_cell` |
|
317 | 327 | |
|
318 | 328 | Stores information about what took place. |
|
319 | 329 | """ |
|
320 | 330 | execution_count = None |
|
321 | 331 | error_before_exec = None |
|
322 | 332 | error_in_exec = None |
|
323 | 333 | info = None |
|
324 | 334 | result = None |
|
325 | 335 | |
|
326 | 336 | def __init__(self, info): |
|
327 | 337 | self.info = info |
|
328 | 338 | |
|
329 | 339 | @property |
|
330 | 340 | def success(self): |
|
331 | 341 | return (self.error_before_exec is None) and (self.error_in_exec is None) |
|
332 | 342 | |
|
333 | 343 | def raise_error(self): |
|
334 | 344 | """Reraises error if `success` is `False`, otherwise does nothing""" |
|
335 | 345 | if self.error_before_exec is not None: |
|
336 | 346 | raise self.error_before_exec |
|
337 | 347 | if self.error_in_exec is not None: |
|
338 | 348 | raise self.error_in_exec |
|
339 | 349 | |
|
340 | 350 | def __repr__(self): |
|
341 | 351 | name = self.__class__.__qualname__ |
|
342 | 352 | return '<%s object at %x, execution_count=%s error_before_exec=%s error_in_exec=%s info=%s result=%s>' %\ |
|
343 | 353 | (name, id(self), self.execution_count, self.error_before_exec, self.error_in_exec, repr(self.info), repr(self.result)) |
|
344 | 354 | |
|
345 | 355 | |
|
346 | 356 | class InteractiveShell(SingletonConfigurable): |
|
347 | 357 | """An enhanced, interactive shell for Python.""" |
|
348 | 358 | |
|
349 | 359 | _instance = None |
|
350 | 360 | |
|
351 | 361 | ast_transformers = List([], help= |
|
352 | 362 | """ |
|
353 | 363 | A list of ast.NodeTransformer subclass instances, which will be applied |
|
354 | 364 | to user input before code is run. |
|
355 | 365 | """ |
|
356 | 366 | ).tag(config=True) |
|
357 | 367 | |
|
358 | 368 | autocall = Enum((0,1,2), default_value=0, help= |
|
359 | 369 | """ |
|
360 | 370 | Make IPython automatically call any callable object even if you didn't |
|
361 | 371 | type explicit parentheses. For example, 'str 43' becomes 'str(43)' |
|
362 | 372 | automatically. The value can be '0' to disable the feature, '1' for |
|
363 | 373 | 'smart' autocall, where it is not applied if there are no more |
|
364 | 374 | arguments on the line, and '2' for 'full' autocall, where all callable |
|
365 | 375 | objects are automatically called (even if no arguments are present). |
|
366 | 376 | """ |
|
367 | 377 | ).tag(config=True) |
|
368 | 378 | |
|
369 | 379 | autoindent = Bool(True, help= |
|
370 | 380 | """ |
|
371 | 381 | Autoindent IPython code entered interactively. |
|
372 | 382 | """ |
|
373 | 383 | ).tag(config=True) |
|
374 | 384 | |
|
375 | 385 | autoawait = Bool(True, help= |
|
376 | 386 | """ |
|
377 | 387 | Automatically run await statement in the top level repl. |
|
378 | 388 | """ |
|
379 | 389 | ).tag(config=True) |
|
380 | 390 | |
|
381 | 391 | loop_runner_map ={ |
|
382 | 392 | 'asyncio':(_asyncio_runner, True), |
|
383 | 393 | 'curio':(_curio_runner, True), |
|
384 | 394 | 'trio':(_trio_runner, True), |
|
385 | 395 | 'sync': (_pseudo_sync_runner, False) |
|
386 | 396 | } |
|
387 | 397 | |
|
388 | 398 | loop_runner = Any(default_value="IPython.core.interactiveshell._asyncio_runner", |
|
389 | 399 | allow_none=True, |
|
390 | 400 | help="""Select the loop runner that will be used to execute top-level asynchronous code""" |
|
391 | 401 | ).tag(config=True) |
|
392 | 402 | |
|
393 | 403 | @default('loop_runner') |
|
394 | 404 | def _default_loop_runner(self): |
|
395 | 405 | return import_item("IPython.core.interactiveshell._asyncio_runner") |
|
396 | 406 | |
|
397 | 407 | @validate('loop_runner') |
|
398 | 408 | def _import_runner(self, proposal): |
|
399 | 409 | if isinstance(proposal.value, str): |
|
400 | 410 | if proposal.value in self.loop_runner_map: |
|
401 | 411 | runner, autoawait = self.loop_runner_map[proposal.value] |
|
402 | 412 | self.autoawait = autoawait |
|
403 | 413 | return runner |
|
404 | 414 | runner = import_item(proposal.value) |
|
405 | 415 | if not callable(runner): |
|
406 | 416 | raise ValueError('loop_runner must be callable') |
|
407 | 417 | return runner |
|
408 | 418 | if not callable(proposal.value): |
|
409 | 419 | raise ValueError('loop_runner must be callable') |
|
410 | 420 | return proposal.value |
|
411 | 421 | |
|
412 | 422 | automagic = Bool(True, help= |
|
413 | 423 | """ |
|
414 | 424 | Enable magic commands to be called without the leading %. |
|
415 | 425 | """ |
|
416 | 426 | ).tag(config=True) |
|
417 | 427 | |
|
418 | 428 | banner1 = Unicode(default_banner, |
|
419 | 429 | help="""The part of the banner to be printed before the profile""" |
|
420 | 430 | ).tag(config=True) |
|
421 | 431 | banner2 = Unicode('', |
|
422 | 432 | help="""The part of the banner to be printed after the profile""" |
|
423 | 433 | ).tag(config=True) |
|
424 | 434 | |
|
425 | 435 | cache_size = Integer(1000, help= |
|
426 | 436 | """ |
|
427 | 437 | Set the size of the output cache. The default is 1000, you can |
|
428 | 438 | change it permanently in your config file. Setting it to 0 completely |
|
429 | 439 | disables the caching system, and the minimum value accepted is 3 (if |
|
430 | 440 | you provide a value less than 3, it is reset to 0 and a warning is |
|
431 | 441 | issued). This limit is defined because otherwise you'll spend more |
|
432 | 442 | time re-flushing a too small cache than working |
|
433 | 443 | """ |
|
434 | 444 | ).tag(config=True) |
|
435 | 445 | color_info = Bool(True, help= |
|
436 | 446 | """ |
|
437 | 447 | Use colors for displaying information about objects. Because this |
|
438 | 448 | information is passed through a pager (like 'less'), and some pagers |
|
439 | 449 | get confused with color codes, this capability can be turned off. |
|
440 | 450 | """ |
|
441 | 451 | ).tag(config=True) |
|
442 | 452 | colors = CaselessStrEnum(('Neutral', 'NoColor','LightBG','Linux'), |
|
443 | 453 | default_value='Neutral', |
|
444 | 454 | help="Set the color scheme (NoColor, Neutral, Linux, or LightBG)." |
|
445 | 455 | ).tag(config=True) |
|
446 | 456 | debug = Bool(False).tag(config=True) |
|
447 | 457 | disable_failing_post_execute = Bool(False, |
|
448 | 458 | help="Don't call post-execute functions that have failed in the past." |
|
449 | 459 | ).tag(config=True) |
|
450 | 460 | display_formatter = Instance(DisplayFormatter, allow_none=True) |
|
451 | 461 | displayhook_class = Type(DisplayHook) |
|
452 | 462 | display_pub_class = Type(DisplayPublisher) |
|
453 | 463 | compiler_class = Type(CachingCompiler) |
|
454 | 464 | |
|
455 | 465 | sphinxify_docstring = Bool(False, help= |
|
456 | 466 | """ |
|
457 | 467 | Enables rich html representation of docstrings. (This requires the |
|
458 | 468 | docrepr module). |
|
459 | 469 | """).tag(config=True) |
|
460 | 470 | |
|
461 | 471 | @observe("sphinxify_docstring") |
|
462 | 472 | def _sphinxify_docstring_changed(self, change): |
|
463 | 473 | if change['new']: |
|
464 | 474 | warn("`sphinxify_docstring` is provisional since IPython 5.0 and might change in future versions." , ProvisionalWarning) |
|
465 | 475 | |
|
466 | 476 | enable_html_pager = Bool(False, help= |
|
467 | 477 | """ |
|
468 | 478 | (Provisional API) enables html representation in mime bundles sent |
|
469 | 479 | to pagers. |
|
470 | 480 | """).tag(config=True) |
|
471 | 481 | |
|
472 | 482 | @observe("enable_html_pager") |
|
473 | 483 | def _enable_html_pager_changed(self, change): |
|
474 | 484 | if change['new']: |
|
475 | 485 | warn("`enable_html_pager` is provisional since IPython 5.0 and might change in future versions.", ProvisionalWarning) |
|
476 | 486 | |
|
477 | 487 | data_pub_class = None |
|
478 | 488 | |
|
479 | 489 | exit_now = Bool(False) |
|
480 | 490 | exiter = Instance(ExitAutocall) |
|
481 | 491 | @default('exiter') |
|
482 | 492 | def _exiter_default(self): |
|
483 | 493 | return ExitAutocall(self) |
|
484 | 494 | # Monotonically increasing execution counter |
|
485 | 495 | execution_count = Integer(1) |
|
486 | 496 | filename = Unicode("<ipython console>") |
|
487 | 497 | ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__ |
|
488 | 498 | |
|
489 | 499 | # Used to transform cells before running them, and check whether code is complete |
|
490 | 500 | input_transformer_manager = Instance('IPython.core.inputtransformer2.TransformerManager', |
|
491 | 501 | ()) |
|
492 | 502 | |
|
493 | 503 | @property |
|
494 | 504 | def input_transformers_cleanup(self): |
|
495 | 505 | return self.input_transformer_manager.cleanup_transforms |
|
496 | 506 | |
|
497 | 507 | input_transformers_post = List([], |
|
498 | 508 | help="A list of string input transformers, to be applied after IPython's " |
|
499 | 509 | "own input transformations." |
|
500 | 510 | ) |
|
501 | 511 | |
|
502 | 512 | @property |
|
503 | 513 | def input_splitter(self): |
|
504 | 514 | """Make this available for backward compatibility (pre-7.0 release) with existing code. |
|
505 | 515 | |
|
506 | 516 | For example, ipykernel ipykernel currently uses |
|
507 | 517 | `shell.input_splitter.check_complete` |
|
508 | 518 | """ |
|
509 | 519 | from warnings import warn |
|
510 | 520 | warn("`input_splitter` is deprecated since IPython 7.0, prefer `input_transformer_manager`.", |
|
511 | 521 | DeprecationWarning, stacklevel=2 |
|
512 | 522 | ) |
|
513 | 523 | return self.input_transformer_manager |
|
514 | 524 | |
|
515 | 525 | logstart = Bool(False, help= |
|
516 | 526 | """ |
|
517 | 527 | Start logging to the default log file in overwrite mode. |
|
518 | 528 | Use `logappend` to specify a log file to **append** logs to. |
|
519 | 529 | """ |
|
520 | 530 | ).tag(config=True) |
|
521 | 531 | logfile = Unicode('', help= |
|
522 | 532 | """ |
|
523 | 533 | The name of the logfile to use. |
|
524 | 534 | """ |
|
525 | 535 | ).tag(config=True) |
|
526 | 536 | logappend = Unicode('', help= |
|
527 | 537 | """ |
|
528 | 538 | Start logging to the given file in append mode. |
|
529 | 539 | Use `logfile` to specify a log file to **overwrite** logs to. |
|
530 | 540 | """ |
|
531 | 541 | ).tag(config=True) |
|
532 | 542 | object_info_string_level = Enum((0,1,2), default_value=0, |
|
533 | 543 | ).tag(config=True) |
|
534 | 544 | pdb = Bool(False, help= |
|
535 | 545 | """ |
|
536 | 546 | Automatically call the pdb debugger after every exception. |
|
537 | 547 | """ |
|
538 | 548 | ).tag(config=True) |
|
539 | 549 | display_page = Bool(False, |
|
540 | 550 | help="""If True, anything that would be passed to the pager |
|
541 | 551 | will be displayed as regular output instead.""" |
|
542 | 552 | ).tag(config=True) |
|
543 | 553 | |
|
544 | 554 | # deprecated prompt traits: |
|
545 | 555 | |
|
546 | 556 | prompt_in1 = Unicode('In [\\#]: ', |
|
547 | 557 | help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly." |
|
548 | 558 | ).tag(config=True) |
|
549 | 559 | prompt_in2 = Unicode(' .\\D.: ', |
|
550 | 560 | help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly." |
|
551 | 561 | ).tag(config=True) |
|
552 | 562 | prompt_out = Unicode('Out[\\#]: ', |
|
553 | 563 | help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly." |
|
554 | 564 | ).tag(config=True) |
|
555 | 565 | prompts_pad_left = Bool(True, |
|
556 | 566 | help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly." |
|
557 | 567 | ).tag(config=True) |
|
558 | 568 | |
|
559 | 569 | @observe('prompt_in1', 'prompt_in2', 'prompt_out', 'prompt_pad_left') |
|
560 | 570 | def _prompt_trait_changed(self, change): |
|
561 | 571 | name = change['name'] |
|
562 | 572 | warn("InteractiveShell.{name} is deprecated since IPython 4.0" |
|
563 | 573 | " and ignored since 5.0, set TerminalInteractiveShell.prompts" |
|
564 | 574 | " object directly.".format(name=name)) |
|
565 | 575 | |
|
566 | 576 | # protect against weird cases where self.config may not exist: |
|
567 | 577 | |
|
568 | 578 | show_rewritten_input = Bool(True, |
|
569 | 579 | help="Show rewritten input, e.g. for autocall." |
|
570 | 580 | ).tag(config=True) |
|
571 | 581 | |
|
572 | 582 | quiet = Bool(False).tag(config=True) |
|
573 | 583 | |
|
574 | 584 | history_length = Integer(10000, |
|
575 | 585 | help='Total length of command history' |
|
576 | 586 | ).tag(config=True) |
|
577 | 587 | |
|
578 | 588 | history_load_length = Integer(1000, help= |
|
579 | 589 | """ |
|
580 | 590 | The number of saved history entries to be loaded |
|
581 | 591 | into the history buffer at startup. |
|
582 | 592 | """ |
|
583 | 593 | ).tag(config=True) |
|
584 | 594 | |
|
585 | 595 | ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none', 'last_expr_or_assign'], |
|
586 | 596 | default_value='last_expr', |
|
587 | 597 | help=""" |
|
588 | 598 | 'all', 'last', 'last_expr' or 'none', 'last_expr_or_assign' specifying |
|
589 | 599 | which nodes should be run interactively (displaying output from expressions). |
|
590 | 600 | """ |
|
591 | 601 | ).tag(config=True) |
|
592 | 602 | |
|
593 | 603 | # TODO: this part of prompt management should be moved to the frontends. |
|
594 | 604 | # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n' |
|
595 | 605 | separate_in = SeparateUnicode('\n').tag(config=True) |
|
596 | 606 | separate_out = SeparateUnicode('').tag(config=True) |
|
597 | 607 | separate_out2 = SeparateUnicode('').tag(config=True) |
|
598 | 608 | wildcards_case_sensitive = Bool(True).tag(config=True) |
|
599 | 609 | xmode = CaselessStrEnum(('Context', 'Plain', 'Verbose', 'Minimal'), |
|
600 | 610 | default_value='Context', |
|
601 | 611 | help="Switch modes for the IPython exception handlers." |
|
602 | 612 | ).tag(config=True) |
|
603 | 613 | |
|
604 | 614 | # Subcomponents of InteractiveShell |
|
605 | 615 | alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True) |
|
606 | 616 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True) |
|
607 | 617 | builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True) |
|
608 | 618 | display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True) |
|
609 | 619 | extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True) |
|
610 | 620 | payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True) |
|
611 | 621 | history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True) |
|
612 | 622 | magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True) |
|
613 | 623 | |
|
614 | 624 | profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True) |
|
615 | 625 | @property |
|
616 | 626 | def profile(self): |
|
617 | 627 | if self.profile_dir is not None: |
|
618 | 628 | name = os.path.basename(self.profile_dir.location) |
|
619 | 629 | return name.replace('profile_','') |
|
620 | 630 | |
|
621 | 631 | |
|
622 | 632 | # Private interface |
|
623 | 633 | _post_execute = Dict() |
|
624 | 634 | |
|
625 | 635 | # Tracks any GUI loop loaded for pylab |
|
626 | 636 | pylab_gui_select = None |
|
627 | 637 | |
|
628 | 638 | last_execution_succeeded = Bool(True, help='Did last executed command succeeded') |
|
629 | 639 | |
|
630 | 640 | last_execution_result = Instance('IPython.core.interactiveshell.ExecutionResult', help='Result of executing the last command', allow_none=True) |
|
631 | 641 | |
|
632 | 642 | def __init__(self, ipython_dir=None, profile_dir=None, |
|
633 | 643 | user_module=None, user_ns=None, |
|
634 | 644 | custom_exceptions=((), None), **kwargs): |
|
635 | 645 | # This is where traits with a config_key argument are updated |
|
636 | 646 | # from the values on config. |
|
637 | 647 | super(InteractiveShell, self).__init__(**kwargs) |
|
638 | 648 | if 'PromptManager' in self.config: |
|
639 | 649 | warn('As of IPython 5.0 `PromptManager` config will have no effect' |
|
640 | 650 | ' and has been replaced by TerminalInteractiveShell.prompts_class') |
|
641 | 651 | self.configurables = [self] |
|
642 | 652 | |
|
643 | 653 | # These are relatively independent and stateless |
|
644 | 654 | self.init_ipython_dir(ipython_dir) |
|
645 | 655 | self.init_profile_dir(profile_dir) |
|
646 | 656 | self.init_instance_attrs() |
|
647 | 657 | self.init_environment() |
|
648 | 658 | |
|
649 | 659 | # Check if we're in a virtualenv, and set up sys.path. |
|
650 | 660 | self.init_virtualenv() |
|
651 | 661 | |
|
652 | 662 | # Create namespaces (user_ns, user_global_ns, etc.) |
|
653 | 663 | self.init_create_namespaces(user_module, user_ns) |
|
654 | 664 | # This has to be done after init_create_namespaces because it uses |
|
655 | 665 | # something in self.user_ns, but before init_sys_modules, which |
|
656 | 666 | # is the first thing to modify sys. |
|
657 | 667 | # TODO: When we override sys.stdout and sys.stderr before this class |
|
658 | 668 | # is created, we are saving the overridden ones here. Not sure if this |
|
659 | 669 | # is what we want to do. |
|
660 | 670 | self.save_sys_module_state() |
|
661 | 671 | self.init_sys_modules() |
|
662 | 672 | |
|
663 | 673 | # While we're trying to have each part of the code directly access what |
|
664 | 674 | # it needs without keeping redundant references to objects, we have too |
|
665 | 675 | # much legacy code that expects ip.db to exist. |
|
666 | 676 | self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db')) |
|
667 | 677 | |
|
668 | 678 | self.init_history() |
|
669 | 679 | self.init_encoding() |
|
670 | 680 | self.init_prefilter() |
|
671 | 681 | |
|
672 | 682 | self.init_syntax_highlighting() |
|
673 | 683 | self.init_hooks() |
|
674 | 684 | self.init_events() |
|
675 | 685 | self.init_pushd_popd_magic() |
|
676 | 686 | self.init_user_ns() |
|
677 | 687 | self.init_logger() |
|
678 | 688 | self.init_builtins() |
|
679 | 689 | |
|
680 | 690 | # The following was in post_config_initialization |
|
681 | 691 | self.init_inspector() |
|
682 | 692 | self.raw_input_original = input |
|
683 | 693 | self.init_completer() |
|
684 | 694 | # TODO: init_io() needs to happen before init_traceback handlers |
|
685 | 695 | # because the traceback handlers hardcode the stdout/stderr streams. |
|
686 | 696 | # This logic in in debugger.Pdb and should eventually be changed. |
|
687 | 697 | self.init_io() |
|
688 | 698 | self.init_traceback_handlers(custom_exceptions) |
|
689 | 699 | self.init_prompts() |
|
690 | 700 | self.init_display_formatter() |
|
691 | 701 | self.init_display_pub() |
|
692 | 702 | self.init_data_pub() |
|
693 | 703 | self.init_displayhook() |
|
694 | 704 | self.init_magics() |
|
695 | 705 | self.init_alias() |
|
696 | 706 | self.init_logstart() |
|
697 | 707 | self.init_pdb() |
|
698 | 708 | self.init_extension_manager() |
|
699 | 709 | self.init_payload() |
|
700 | 710 | self.init_deprecation_warnings() |
|
701 | 711 | self.hooks.late_startup_hook() |
|
702 | 712 | self.events.trigger('shell_initialized', self) |
|
703 | 713 | atexit.register(self.atexit_operations) |
|
704 | 714 | |
|
705 | 715 | # The trio runner is used for running Trio in the foreground thread. It |
|
706 | 716 | # is different from `_trio_runner(async_fn)` in `async_helpers.py` |
|
707 | 717 | # which calls `trio.run()` for every cell. This runner runs all cells |
|
708 | 718 | # inside a single Trio event loop. If used, it is set from |
|
709 | 719 | # `ipykernel.kernelapp`. |
|
710 | 720 | self.trio_runner = None |
|
711 | 721 | |
|
712 | 722 | def get_ipython(self): |
|
713 | 723 | """Return the currently running IPython instance.""" |
|
714 | 724 | return self |
|
715 | 725 | |
|
716 | 726 | #------------------------------------------------------------------------- |
|
717 | 727 | # Trait changed handlers |
|
718 | 728 | #------------------------------------------------------------------------- |
|
719 | 729 | @observe('ipython_dir') |
|
720 | 730 | def _ipython_dir_changed(self, change): |
|
721 | 731 | ensure_dir_exists(change['new']) |
|
722 | 732 | |
|
723 | 733 | def set_autoindent(self,value=None): |
|
724 | 734 | """Set the autoindent flag. |
|
725 | 735 | |
|
726 | 736 | If called with no arguments, it acts as a toggle.""" |
|
727 | 737 | if value is None: |
|
728 | 738 | self.autoindent = not self.autoindent |
|
729 | 739 | else: |
|
730 | 740 | self.autoindent = value |
|
731 | 741 | |
|
732 | 742 | def set_trio_runner(self, tr): |
|
733 | 743 | self.trio_runner = tr |
|
734 | 744 | |
|
735 | 745 | #------------------------------------------------------------------------- |
|
736 | 746 | # init_* methods called by __init__ |
|
737 | 747 | #------------------------------------------------------------------------- |
|
738 | 748 | |
|
739 | 749 | def init_ipython_dir(self, ipython_dir): |
|
740 | 750 | if ipython_dir is not None: |
|
741 | 751 | self.ipython_dir = ipython_dir |
|
742 | 752 | return |
|
743 | 753 | |
|
744 | 754 | self.ipython_dir = get_ipython_dir() |
|
745 | 755 | |
|
746 | 756 | def init_profile_dir(self, profile_dir): |
|
747 | 757 | if profile_dir is not None: |
|
748 | 758 | self.profile_dir = profile_dir |
|
749 | 759 | return |
|
750 | 760 | self.profile_dir = ProfileDir.create_profile_dir_by_name( |
|
751 | 761 | self.ipython_dir, "default" |
|
752 | 762 | ) |
|
753 | 763 | |
|
754 | 764 | def init_instance_attrs(self): |
|
755 | 765 | self.more = False |
|
756 | 766 | |
|
757 | 767 | # command compiler |
|
758 | 768 | self.compile = self.compiler_class() |
|
759 | 769 | |
|
760 | 770 | # Make an empty namespace, which extension writers can rely on both |
|
761 | 771 | # existing and NEVER being used by ipython itself. This gives them a |
|
762 | 772 | # convenient location for storing additional information and state |
|
763 | 773 | # their extensions may require, without fear of collisions with other |
|
764 | 774 | # ipython names that may develop later. |
|
765 | 775 | self.meta = Struct() |
|
766 | 776 | |
|
767 | 777 | # Temporary files used for various purposes. Deleted at exit. |
|
768 | 778 | self.tempfiles = [] |
|
769 | 779 | self.tempdirs = [] |
|
770 | 780 | |
|
771 | 781 | # keep track of where we started running (mainly for crash post-mortem) |
|
772 | 782 | # This is not being used anywhere currently. |
|
773 | 783 | self.starting_dir = os.getcwd() |
|
774 | 784 | |
|
775 | 785 | # Indentation management |
|
776 | 786 | self.indent_current_nsp = 0 |
|
777 | 787 | |
|
778 | 788 | # Dict to track post-execution functions that have been registered |
|
779 | 789 | self._post_execute = {} |
|
780 | 790 | |
|
781 | 791 | def init_environment(self): |
|
782 | 792 | """Any changes we need to make to the user's environment.""" |
|
783 | 793 | pass |
|
784 | 794 | |
|
785 | 795 | def init_encoding(self): |
|
786 | 796 | # Get system encoding at startup time. Certain terminals (like Emacs |
|
787 | 797 | # under Win32 have it set to None, and we need to have a known valid |
|
788 | 798 | # encoding to use in the raw_input() method |
|
789 | 799 | try: |
|
790 | 800 | self.stdin_encoding = sys.stdin.encoding or 'ascii' |
|
791 | 801 | except AttributeError: |
|
792 | 802 | self.stdin_encoding = 'ascii' |
|
793 | 803 | |
|
794 | 804 | |
|
795 | 805 | @observe('colors') |
|
796 | 806 | def init_syntax_highlighting(self, changes=None): |
|
797 | 807 | # Python source parser/formatter for syntax highlighting |
|
798 | 808 | pyformat = PyColorize.Parser(style=self.colors, parent=self).format |
|
799 | 809 | self.pycolorize = lambda src: pyformat(src,'str') |
|
800 | 810 | |
|
801 | 811 | def refresh_style(self): |
|
802 | 812 | # No-op here, used in subclass |
|
803 | 813 | pass |
|
804 | 814 | |
|
805 | 815 | def init_pushd_popd_magic(self): |
|
806 | 816 | # for pushd/popd management |
|
807 | 817 | self.home_dir = get_home_dir() |
|
808 | 818 | |
|
809 | 819 | self.dir_stack = [] |
|
810 | 820 | |
|
811 | 821 | def init_logger(self): |
|
812 | 822 | self.logger = Logger(self.home_dir, logfname='ipython_log.py', |
|
813 | 823 | logmode='rotate') |
|
814 | 824 | |
|
815 | 825 | def init_logstart(self): |
|
816 | 826 | """Initialize logging in case it was requested at the command line. |
|
817 | 827 | """ |
|
818 | 828 | if self.logappend: |
|
819 | 829 | self.magic('logstart %s append' % self.logappend) |
|
820 | 830 | elif self.logfile: |
|
821 | 831 | self.magic('logstart %s' % self.logfile) |
|
822 | 832 | elif self.logstart: |
|
823 | 833 | self.magic('logstart') |
|
824 | 834 | |
|
825 | 835 | def init_deprecation_warnings(self): |
|
826 | 836 | """ |
|
827 | 837 | register default filter for deprecation warning. |
|
828 | 838 | |
|
829 | 839 | This will allow deprecation warning of function used interactively to show |
|
830 | 840 | warning to users, and still hide deprecation warning from libraries import. |
|
831 | 841 | """ |
|
832 | 842 | if sys.version_info < (3,7): |
|
833 | 843 | warnings.filterwarnings("default", category=DeprecationWarning, module=self.user_ns.get("__name__")) |
|
834 | 844 | |
|
835 | 845 | |
|
836 | 846 | def init_builtins(self): |
|
837 | 847 | # A single, static flag that we set to True. Its presence indicates |
|
838 | 848 | # that an IPython shell has been created, and we make no attempts at |
|
839 | 849 | # removing on exit or representing the existence of more than one |
|
840 | 850 | # IPython at a time. |
|
841 | 851 | builtin_mod.__dict__['__IPYTHON__'] = True |
|
842 | 852 | builtin_mod.__dict__['display'] = display |
|
843 | 853 | |
|
844 | 854 | self.builtin_trap = BuiltinTrap(shell=self) |
|
845 | 855 | |
|
846 | 856 | @observe('colors') |
|
847 | 857 | def init_inspector(self, changes=None): |
|
848 | 858 | # Object inspector |
|
849 | 859 | self.inspector = oinspect.Inspector(oinspect.InspectColors, |
|
850 | 860 | PyColorize.ANSICodeColors, |
|
851 | 861 | self.colors, |
|
852 | 862 | self.object_info_string_level) |
|
853 | 863 | |
|
854 | 864 | def init_io(self): |
|
855 | 865 | # This will just use sys.stdout and sys.stderr. If you want to |
|
856 | 866 | # override sys.stdout and sys.stderr themselves, you need to do that |
|
857 | 867 | # *before* instantiating this class, because io holds onto |
|
858 | 868 | # references to the underlying streams. |
|
859 | 869 | # io.std* are deprecated, but don't show our own deprecation warnings |
|
860 | 870 | # during initialization of the deprecated API. |
|
861 | 871 | with warnings.catch_warnings(): |
|
862 | 872 | warnings.simplefilter('ignore', DeprecationWarning) |
|
863 | 873 | io.stdout = io.IOStream(sys.stdout) |
|
864 | 874 | io.stderr = io.IOStream(sys.stderr) |
|
865 | 875 | |
|
866 | 876 | def init_prompts(self): |
|
867 | 877 | # Set system prompts, so that scripts can decide if they are running |
|
868 | 878 | # interactively. |
|
869 | 879 | sys.ps1 = 'In : ' |
|
870 | 880 | sys.ps2 = '...: ' |
|
871 | 881 | sys.ps3 = 'Out: ' |
|
872 | 882 | |
|
873 | 883 | def init_display_formatter(self): |
|
874 | 884 | self.display_formatter = DisplayFormatter(parent=self) |
|
875 | 885 | self.configurables.append(self.display_formatter) |
|
876 | 886 | |
|
877 | 887 | def init_display_pub(self): |
|
878 | 888 | self.display_pub = self.display_pub_class(parent=self, shell=self) |
|
879 | 889 | self.configurables.append(self.display_pub) |
|
880 | 890 | |
|
881 | 891 | def init_data_pub(self): |
|
882 | 892 | if not self.data_pub_class: |
|
883 | 893 | self.data_pub = None |
|
884 | 894 | return |
|
885 | 895 | self.data_pub = self.data_pub_class(parent=self) |
|
886 | 896 | self.configurables.append(self.data_pub) |
|
887 | 897 | |
|
888 | 898 | def init_displayhook(self): |
|
889 | 899 | # Initialize displayhook, set in/out prompts and printing system |
|
890 | 900 | self.displayhook = self.displayhook_class( |
|
891 | 901 | parent=self, |
|
892 | 902 | shell=self, |
|
893 | 903 | cache_size=self.cache_size, |
|
894 | 904 | ) |
|
895 | 905 | self.configurables.append(self.displayhook) |
|
896 | 906 | # This is a context manager that installs/revmoes the displayhook at |
|
897 | 907 | # the appropriate time. |
|
898 | 908 | self.display_trap = DisplayTrap(hook=self.displayhook) |
|
899 | 909 | |
|
900 | 910 | def init_virtualenv(self): |
|
901 | 911 | """Add the current virtualenv to sys.path so the user can import modules from it. |
|
902 | 912 | This isn't perfect: it doesn't use the Python interpreter with which the |
|
903 | 913 | virtualenv was built, and it ignores the --no-site-packages option. A |
|
904 | 914 | warning will appear suggesting the user installs IPython in the |
|
905 | 915 | virtualenv, but for many cases, it probably works well enough. |
|
906 | 916 | Adapted from code snippets online. |
|
907 | 917 | http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv |
|
908 | 918 | """ |
|
909 | 919 | if 'VIRTUAL_ENV' not in os.environ: |
|
910 | 920 | # Not in a virtualenv |
|
911 | 921 | return |
|
912 | 922 | elif os.environ["VIRTUAL_ENV"] == "": |
|
913 | 923 | warn("Virtual env path set to '', please check if this is intended.") |
|
914 | 924 | return |
|
915 | 925 | |
|
916 | 926 | p = Path(sys.executable) |
|
917 | 927 | p_venv = Path(os.environ["VIRTUAL_ENV"]) |
|
918 | 928 | |
|
919 | 929 | # fallback venv detection: |
|
920 | 930 | # stdlib venv may symlink sys.executable, so we can't use realpath. |
|
921 | 931 | # but others can symlink *to* the venv Python, so we can't just use sys.executable. |
|
922 | 932 | # So we just check every item in the symlink tree (generally <= 3) |
|
923 | 933 | paths = [p] |
|
924 | 934 | while p.is_symlink(): |
|
925 | 935 | p = Path(os.readlink(p)) |
|
926 | 936 | paths.append(p.resolve()) |
|
927 | 937 | |
|
928 | 938 | # In Cygwin paths like "c:\..." and '\cygdrive\c\...' are possible |
|
929 | 939 | if p_venv.parts[1] == "cygdrive": |
|
930 | 940 | drive_name = p_venv.parts[2] |
|
931 | 941 | p_venv = (drive_name + ":/") / Path(*p_venv.parts[3:]) |
|
932 | 942 | |
|
933 | 943 | if any(p_venv == p.parents[1] for p in paths): |
|
934 | 944 | # Our exe is inside or has access to the virtualenv, don't need to do anything. |
|
935 | 945 | return |
|
936 | 946 | |
|
937 | 947 | if sys.platform == "win32": |
|
938 | 948 | virtual_env = str(Path(os.environ["VIRTUAL_ENV"], "Lib", "site-packages")) |
|
939 | 949 | else: |
|
940 | 950 | virtual_env_path = Path( |
|
941 | 951 | os.environ["VIRTUAL_ENV"], "lib", "python{}.{}", "site-packages" |
|
942 | 952 | ) |
|
943 | 953 | p_ver = sys.version_info[:2] |
|
944 | 954 | |
|
945 | 955 | # Predict version from py[thon]-x.x in the $VIRTUAL_ENV |
|
946 | 956 | re_m = re.search(r"\bpy(?:thon)?([23])\.(\d+)\b", os.environ["VIRTUAL_ENV"]) |
|
947 | 957 | if re_m: |
|
948 | 958 | predicted_path = Path(str(virtual_env_path).format(*re_m.groups())) |
|
949 | 959 | if predicted_path.exists(): |
|
950 | 960 | p_ver = re_m.groups() |
|
951 | 961 | |
|
952 | 962 | virtual_env = str(virtual_env_path).format(*p_ver) |
|
953 | 963 | |
|
954 | 964 | warn( |
|
955 | 965 | "Attempting to work in a virtualenv. If you encounter problems, " |
|
956 | 966 | "please install IPython inside the virtualenv." |
|
957 | 967 | ) |
|
958 | 968 | import site |
|
959 | 969 | sys.path.insert(0, virtual_env) |
|
960 | 970 | site.addsitedir(virtual_env) |
|
961 | 971 | |
|
962 | 972 | #------------------------------------------------------------------------- |
|
963 | 973 | # Things related to injections into the sys module |
|
964 | 974 | #------------------------------------------------------------------------- |
|
965 | 975 | |
|
966 | 976 | def save_sys_module_state(self): |
|
967 | 977 | """Save the state of hooks in the sys module. |
|
968 | 978 | |
|
969 | 979 | This has to be called after self.user_module is created. |
|
970 | 980 | """ |
|
971 | 981 | self._orig_sys_module_state = {'stdin': sys.stdin, |
|
972 | 982 | 'stdout': sys.stdout, |
|
973 | 983 | 'stderr': sys.stderr, |
|
974 | 984 | 'excepthook': sys.excepthook} |
|
975 | 985 | self._orig_sys_modules_main_name = self.user_module.__name__ |
|
976 | 986 | self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__) |
|
977 | 987 | |
|
978 | 988 | def restore_sys_module_state(self): |
|
979 | 989 | """Restore the state of the sys module.""" |
|
980 | 990 | try: |
|
981 | 991 | for k, v in self._orig_sys_module_state.items(): |
|
982 | 992 | setattr(sys, k, v) |
|
983 | 993 | except AttributeError: |
|
984 | 994 | pass |
|
985 | 995 | # Reset what what done in self.init_sys_modules |
|
986 | 996 | if self._orig_sys_modules_main_mod is not None: |
|
987 | 997 | sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod |
|
988 | 998 | |
|
989 | 999 | #------------------------------------------------------------------------- |
|
990 | 1000 | # Things related to the banner |
|
991 | 1001 | #------------------------------------------------------------------------- |
|
992 | 1002 | |
|
993 | 1003 | @property |
|
994 | 1004 | def banner(self): |
|
995 | 1005 | banner = self.banner1 |
|
996 | 1006 | if self.profile and self.profile != 'default': |
|
997 | 1007 | banner += '\nIPython profile: %s\n' % self.profile |
|
998 | 1008 | if self.banner2: |
|
999 | 1009 | banner += '\n' + self.banner2 |
|
1000 | 1010 | return banner |
|
1001 | 1011 | |
|
1002 | 1012 | def show_banner(self, banner=None): |
|
1003 | 1013 | if banner is None: |
|
1004 | 1014 | banner = self.banner |
|
1005 | 1015 | sys.stdout.write(banner) |
|
1006 | 1016 | |
|
1007 | 1017 | #------------------------------------------------------------------------- |
|
1008 | 1018 | # Things related to hooks |
|
1009 | 1019 | #------------------------------------------------------------------------- |
|
1010 | 1020 | |
|
1011 | 1021 | def init_hooks(self): |
|
1012 | 1022 | # hooks holds pointers used for user-side customizations |
|
1013 | 1023 | self.hooks = Struct() |
|
1014 | 1024 | |
|
1015 | 1025 | self.strdispatchers = {} |
|
1016 | 1026 | |
|
1017 | 1027 | # Set all default hooks, defined in the IPython.hooks module. |
|
1018 | 1028 | hooks = IPython.core.hooks |
|
1019 | 1029 | for hook_name in hooks.__all__: |
|
1020 | 1030 | # default hooks have priority 100, i.e. low; user hooks should have |
|
1021 | 1031 | # 0-100 priority |
|
1022 | 1032 | self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False) |
|
1023 | 1033 | |
|
1024 | 1034 | if self.display_page: |
|
1025 | 1035 | self.set_hook('show_in_pager', page.as_hook(page.display_page), 90) |
|
1026 | 1036 | |
|
1027 | 1037 | def set_hook(self,name,hook, priority=50, str_key=None, re_key=None, |
|
1028 | 1038 | _warn_deprecated=True): |
|
1029 | 1039 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
1030 | 1040 | |
|
1031 | 1041 | IPython exposes some of its internal API as user-modifiable hooks. By |
|
1032 | 1042 | adding your function to one of these hooks, you can modify IPython's |
|
1033 | 1043 | behavior to call at runtime your own routines.""" |
|
1034 | 1044 | |
|
1035 | 1045 | # At some point in the future, this should validate the hook before it |
|
1036 | 1046 | # accepts it. Probably at least check that the hook takes the number |
|
1037 | 1047 | # of args it's supposed to. |
|
1038 | 1048 | |
|
1039 | 1049 | f = types.MethodType(hook,self) |
|
1040 | 1050 | |
|
1041 | 1051 | # check if the hook is for strdispatcher first |
|
1042 | 1052 | if str_key is not None: |
|
1043 | 1053 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
1044 | 1054 | sdp.add_s(str_key, f, priority ) |
|
1045 | 1055 | self.strdispatchers[name] = sdp |
|
1046 | 1056 | return |
|
1047 | 1057 | if re_key is not None: |
|
1048 | 1058 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
1049 | 1059 | sdp.add_re(re.compile(re_key), f, priority ) |
|
1050 | 1060 | self.strdispatchers[name] = sdp |
|
1051 | 1061 | return |
|
1052 | 1062 | |
|
1053 | 1063 | dp = getattr(self.hooks, name, None) |
|
1054 | 1064 | if name not in IPython.core.hooks.__all__: |
|
1055 | 1065 | print("Warning! Hook '%s' is not one of %s" % \ |
|
1056 | 1066 | (name, IPython.core.hooks.__all__ )) |
|
1057 | 1067 | |
|
1058 | 1068 | if _warn_deprecated and (name in IPython.core.hooks.deprecated): |
|
1059 | 1069 | alternative = IPython.core.hooks.deprecated[name] |
|
1060 | 1070 | warn("Hook {} is deprecated. Use {} instead.".format(name, alternative), stacklevel=2) |
|
1061 | 1071 | |
|
1062 | 1072 | if not dp: |
|
1063 | 1073 | dp = IPython.core.hooks.CommandChainDispatcher() |
|
1064 | 1074 | |
|
1065 | 1075 | try: |
|
1066 | 1076 | dp.add(f,priority) |
|
1067 | 1077 | except AttributeError: |
|
1068 | 1078 | # it was not commandchain, plain old func - replace |
|
1069 | 1079 | dp = f |
|
1070 | 1080 | |
|
1071 | 1081 | setattr(self.hooks,name, dp) |
|
1072 | 1082 | |
|
1073 | 1083 | #------------------------------------------------------------------------- |
|
1074 | 1084 | # Things related to events |
|
1075 | 1085 | #------------------------------------------------------------------------- |
|
1076 | 1086 | |
|
1077 | 1087 | def init_events(self): |
|
1078 | 1088 | self.events = EventManager(self, available_events) |
|
1079 | 1089 | |
|
1080 | 1090 | self.events.register("pre_execute", self._clear_warning_registry) |
|
1081 | 1091 | |
|
1082 | 1092 | def register_post_execute(self, func): |
|
1083 | 1093 | """DEPRECATED: Use ip.events.register('post_run_cell', func) |
|
1084 | 1094 | |
|
1085 | 1095 | Register a function for calling after code execution. |
|
1086 | 1096 | """ |
|
1087 | 1097 | warn("ip.register_post_execute is deprecated, use " |
|
1088 | 1098 | "ip.events.register('post_run_cell', func) instead.", stacklevel=2) |
|
1089 | 1099 | self.events.register('post_run_cell', func) |
|
1090 | 1100 | |
|
1091 | 1101 | def _clear_warning_registry(self): |
|
1092 | 1102 | # clear the warning registry, so that different code blocks with |
|
1093 | 1103 | # overlapping line number ranges don't cause spurious suppression of |
|
1094 | 1104 | # warnings (see gh-6611 for details) |
|
1095 | 1105 | if "__warningregistry__" in self.user_global_ns: |
|
1096 | 1106 | del self.user_global_ns["__warningregistry__"] |
|
1097 | 1107 | |
|
1098 | 1108 | #------------------------------------------------------------------------- |
|
1099 | 1109 | # Things related to the "main" module |
|
1100 | 1110 | #------------------------------------------------------------------------- |
|
1101 | 1111 | |
|
1102 | 1112 | def new_main_mod(self, filename, modname): |
|
1103 | 1113 | """Return a new 'main' module object for user code execution. |
|
1104 | 1114 | |
|
1105 | 1115 | ``filename`` should be the path of the script which will be run in the |
|
1106 | 1116 | module. Requests with the same filename will get the same module, with |
|
1107 | 1117 | its namespace cleared. |
|
1108 | 1118 | |
|
1109 | 1119 | ``modname`` should be the module name - normally either '__main__' or |
|
1110 | 1120 | the basename of the file without the extension. |
|
1111 | 1121 | |
|
1112 | 1122 | When scripts are executed via %run, we must keep a reference to their |
|
1113 | 1123 | __main__ module around so that Python doesn't |
|
1114 | 1124 | clear it, rendering references to module globals useless. |
|
1115 | 1125 | |
|
1116 | 1126 | This method keeps said reference in a private dict, keyed by the |
|
1117 | 1127 | absolute path of the script. This way, for multiple executions of the |
|
1118 | 1128 | same script we only keep one copy of the namespace (the last one), |
|
1119 | 1129 | thus preventing memory leaks from old references while allowing the |
|
1120 | 1130 | objects from the last execution to be accessible. |
|
1121 | 1131 | """ |
|
1122 | 1132 | filename = os.path.abspath(filename) |
|
1123 | 1133 | try: |
|
1124 | 1134 | main_mod = self._main_mod_cache[filename] |
|
1125 | 1135 | except KeyError: |
|
1126 | 1136 | main_mod = self._main_mod_cache[filename] = types.ModuleType( |
|
1127 | 1137 | modname, |
|
1128 | 1138 | doc="Module created for script run in IPython") |
|
1129 | 1139 | else: |
|
1130 | 1140 | main_mod.__dict__.clear() |
|
1131 | 1141 | main_mod.__name__ = modname |
|
1132 | 1142 | |
|
1133 | 1143 | main_mod.__file__ = filename |
|
1134 | 1144 | # It seems pydoc (and perhaps others) needs any module instance to |
|
1135 | 1145 | # implement a __nonzero__ method |
|
1136 | 1146 | main_mod.__nonzero__ = lambda : True |
|
1137 | 1147 | |
|
1138 | 1148 | return main_mod |
|
1139 | 1149 | |
|
1140 | 1150 | def clear_main_mod_cache(self): |
|
1141 | 1151 | """Clear the cache of main modules. |
|
1142 | 1152 | |
|
1143 | 1153 | Mainly for use by utilities like %reset. |
|
1144 | 1154 | |
|
1145 | 1155 | Examples |
|
1146 | 1156 | -------- |
|
1147 | 1157 | |
|
1148 | 1158 | In [15]: import IPython |
|
1149 | 1159 | |
|
1150 | 1160 | In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython') |
|
1151 | 1161 | |
|
1152 | 1162 | In [17]: len(_ip._main_mod_cache) > 0 |
|
1153 | 1163 | Out[17]: True |
|
1154 | 1164 | |
|
1155 | 1165 | In [18]: _ip.clear_main_mod_cache() |
|
1156 | 1166 | |
|
1157 | 1167 | In [19]: len(_ip._main_mod_cache) == 0 |
|
1158 | 1168 | Out[19]: True |
|
1159 | 1169 | """ |
|
1160 | 1170 | self._main_mod_cache.clear() |
|
1161 | 1171 | |
|
1162 | 1172 | #------------------------------------------------------------------------- |
|
1163 | 1173 | # Things related to debugging |
|
1164 | 1174 | #------------------------------------------------------------------------- |
|
1165 | 1175 | |
|
1166 | 1176 | def init_pdb(self): |
|
1167 | 1177 | # Set calling of pdb on exceptions |
|
1168 | 1178 | # self.call_pdb is a property |
|
1169 | 1179 | self.call_pdb = self.pdb |
|
1170 | 1180 | |
|
1171 | 1181 | def _get_call_pdb(self): |
|
1172 | 1182 | return self._call_pdb |
|
1173 | 1183 | |
|
1174 | 1184 | def _set_call_pdb(self,val): |
|
1175 | 1185 | |
|
1176 | 1186 | if val not in (0,1,False,True): |
|
1177 | 1187 | raise ValueError('new call_pdb value must be boolean') |
|
1178 | 1188 | |
|
1179 | 1189 | # store value in instance |
|
1180 | 1190 | self._call_pdb = val |
|
1181 | 1191 | |
|
1182 | 1192 | # notify the actual exception handlers |
|
1183 | 1193 | self.InteractiveTB.call_pdb = val |
|
1184 | 1194 | |
|
1185 | 1195 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, |
|
1186 | 1196 | 'Control auto-activation of pdb at exceptions') |
|
1187 | 1197 | |
|
1188 | 1198 | def debugger(self,force=False): |
|
1189 | 1199 | """Call the pdb debugger. |
|
1190 | 1200 | |
|
1191 | 1201 | Keywords: |
|
1192 | 1202 | |
|
1193 | 1203 | - force(False): by default, this routine checks the instance call_pdb |
|
1194 | 1204 | flag and does not actually invoke the debugger if the flag is false. |
|
1195 | 1205 | The 'force' option forces the debugger to activate even if the flag |
|
1196 | 1206 | is false. |
|
1197 | 1207 | """ |
|
1198 | 1208 | |
|
1199 | 1209 | if not (force or self.call_pdb): |
|
1200 | 1210 | return |
|
1201 | 1211 | |
|
1202 | 1212 | if not hasattr(sys,'last_traceback'): |
|
1203 | 1213 | error('No traceback has been produced, nothing to debug.') |
|
1204 | 1214 | return |
|
1205 | 1215 | |
|
1206 | 1216 | self.InteractiveTB.debugger(force=True) |
|
1207 | 1217 | |
|
1208 | 1218 | #------------------------------------------------------------------------- |
|
1209 | 1219 | # Things related to IPython's various namespaces |
|
1210 | 1220 | #------------------------------------------------------------------------- |
|
1211 | 1221 | default_user_namespaces = True |
|
1212 | 1222 | |
|
1213 | 1223 | def init_create_namespaces(self, user_module=None, user_ns=None): |
|
1214 | 1224 | # Create the namespace where the user will operate. user_ns is |
|
1215 | 1225 | # normally the only one used, and it is passed to the exec calls as |
|
1216 | 1226 | # the locals argument. But we do carry a user_global_ns namespace |
|
1217 | 1227 | # given as the exec 'globals' argument, This is useful in embedding |
|
1218 | 1228 | # situations where the ipython shell opens in a context where the |
|
1219 | 1229 | # distinction between locals and globals is meaningful. For |
|
1220 | 1230 | # non-embedded contexts, it is just the same object as the user_ns dict. |
|
1221 | 1231 | |
|
1222 | 1232 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
1223 | 1233 | # level as a dict instead of a module. This is a manual fix, but I |
|
1224 | 1234 | # should really track down where the problem is coming from. Alex |
|
1225 | 1235 | # Schmolck reported this problem first. |
|
1226 | 1236 | |
|
1227 | 1237 | # A useful post by Alex Martelli on this topic: |
|
1228 | 1238 | # Re: inconsistent value from __builtins__ |
|
1229 | 1239 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
1230 | 1240 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
1231 | 1241 | # Gruppen: comp.lang.python |
|
1232 | 1242 | |
|
1233 | 1243 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
1234 | 1244 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
1235 | 1245 | # > <type 'dict'> |
|
1236 | 1246 | # > >>> print type(__builtins__) |
|
1237 | 1247 | # > <type 'module'> |
|
1238 | 1248 | # > Is this difference in return value intentional? |
|
1239 | 1249 | |
|
1240 | 1250 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
1241 | 1251 | # or a module, and it's been that way for a long time. Whether it's |
|
1242 | 1252 | # intentional (or sensible), I don't know. In any case, the idea is |
|
1243 | 1253 | # that if you need to access the built-in namespace directly, you |
|
1244 | 1254 | # should start with "import __builtin__" (note, no 's') which will |
|
1245 | 1255 | # definitely give you a module. Yeah, it's somewhat confusing:-(. |
|
1246 | 1256 | |
|
1247 | 1257 | # These routines return a properly built module and dict as needed by |
|
1248 | 1258 | # the rest of the code, and can also be used by extension writers to |
|
1249 | 1259 | # generate properly initialized namespaces. |
|
1250 | 1260 | if (user_ns is not None) or (user_module is not None): |
|
1251 | 1261 | self.default_user_namespaces = False |
|
1252 | 1262 | self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns) |
|
1253 | 1263 | |
|
1254 | 1264 | # A record of hidden variables we have added to the user namespace, so |
|
1255 | 1265 | # we can list later only variables defined in actual interactive use. |
|
1256 | 1266 | self.user_ns_hidden = {} |
|
1257 | 1267 | |
|
1258 | 1268 | # Now that FakeModule produces a real module, we've run into a nasty |
|
1259 | 1269 | # problem: after script execution (via %run), the module where the user |
|
1260 | 1270 | # code ran is deleted. Now that this object is a true module (needed |
|
1261 | 1271 | # so doctest and other tools work correctly), the Python module |
|
1262 | 1272 | # teardown mechanism runs over it, and sets to None every variable |
|
1263 | 1273 | # present in that module. Top-level references to objects from the |
|
1264 | 1274 | # script survive, because the user_ns is updated with them. However, |
|
1265 | 1275 | # calling functions defined in the script that use other things from |
|
1266 | 1276 | # the script will fail, because the function's closure had references |
|
1267 | 1277 | # to the original objects, which are now all None. So we must protect |
|
1268 | 1278 | # these modules from deletion by keeping a cache. |
|
1269 | 1279 | # |
|
1270 | 1280 | # To avoid keeping stale modules around (we only need the one from the |
|
1271 | 1281 | # last run), we use a dict keyed with the full path to the script, so |
|
1272 | 1282 | # only the last version of the module is held in the cache. Note, |
|
1273 | 1283 | # however, that we must cache the module *namespace contents* (their |
|
1274 | 1284 | # __dict__). Because if we try to cache the actual modules, old ones |
|
1275 | 1285 | # (uncached) could be destroyed while still holding references (such as |
|
1276 | 1286 | # those held by GUI objects that tend to be long-lived)> |
|
1277 | 1287 | # |
|
1278 | 1288 | # The %reset command will flush this cache. See the cache_main_mod() |
|
1279 | 1289 | # and clear_main_mod_cache() methods for details on use. |
|
1280 | 1290 | |
|
1281 | 1291 | # This is the cache used for 'main' namespaces |
|
1282 | 1292 | self._main_mod_cache = {} |
|
1283 | 1293 | |
|
1284 | 1294 | # A table holding all the namespaces IPython deals with, so that |
|
1285 | 1295 | # introspection facilities can search easily. |
|
1286 | 1296 | self.ns_table = {'user_global':self.user_module.__dict__, |
|
1287 | 1297 | 'user_local':self.user_ns, |
|
1288 | 1298 | 'builtin':builtin_mod.__dict__ |
|
1289 | 1299 | } |
|
1290 | 1300 | |
|
1291 | 1301 | @property |
|
1292 | 1302 | def user_global_ns(self): |
|
1293 | 1303 | return self.user_module.__dict__ |
|
1294 | 1304 | |
|
1295 | 1305 | def prepare_user_module(self, user_module=None, user_ns=None): |
|
1296 | 1306 | """Prepare the module and namespace in which user code will be run. |
|
1297 | 1307 | |
|
1298 | 1308 | When IPython is started normally, both parameters are None: a new module |
|
1299 | 1309 | is created automatically, and its __dict__ used as the namespace. |
|
1300 | 1310 | |
|
1301 | 1311 | If only user_module is provided, its __dict__ is used as the namespace. |
|
1302 | 1312 | If only user_ns is provided, a dummy module is created, and user_ns |
|
1303 | 1313 | becomes the global namespace. If both are provided (as they may be |
|
1304 | 1314 | when embedding), user_ns is the local namespace, and user_module |
|
1305 | 1315 | provides the global namespace. |
|
1306 | 1316 | |
|
1307 | 1317 | Parameters |
|
1308 | 1318 | ---------- |
|
1309 | 1319 | user_module : module, optional |
|
1310 | 1320 | The current user module in which IPython is being run. If None, |
|
1311 | 1321 | a clean module will be created. |
|
1312 | 1322 | user_ns : dict, optional |
|
1313 | 1323 | A namespace in which to run interactive commands. |
|
1314 | 1324 | |
|
1315 | 1325 | Returns |
|
1316 | 1326 | ------- |
|
1317 | 1327 | A tuple of user_module and user_ns, each properly initialised. |
|
1318 | 1328 | """ |
|
1319 | 1329 | if user_module is None and user_ns is not None: |
|
1320 | 1330 | user_ns.setdefault("__name__", "__main__") |
|
1321 | 1331 | user_module = DummyMod() |
|
1322 | 1332 | user_module.__dict__ = user_ns |
|
1323 | 1333 | |
|
1324 | 1334 | if user_module is None: |
|
1325 | 1335 | user_module = types.ModuleType("__main__", |
|
1326 | 1336 | doc="Automatically created module for IPython interactive environment") |
|
1327 | 1337 | |
|
1328 | 1338 | # We must ensure that __builtin__ (without the final 's') is always |
|
1329 | 1339 | # available and pointing to the __builtin__ *module*. For more details: |
|
1330 | 1340 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
1331 | 1341 | user_module.__dict__.setdefault('__builtin__', builtin_mod) |
|
1332 | 1342 | user_module.__dict__.setdefault('__builtins__', builtin_mod) |
|
1333 | 1343 | |
|
1334 | 1344 | if user_ns is None: |
|
1335 | 1345 | user_ns = user_module.__dict__ |
|
1336 | 1346 | |
|
1337 | 1347 | return user_module, user_ns |
|
1338 | 1348 | |
|
1339 | 1349 | def init_sys_modules(self): |
|
1340 | 1350 | # We need to insert into sys.modules something that looks like a |
|
1341 | 1351 | # module but which accesses the IPython namespace, for shelve and |
|
1342 | 1352 | # pickle to work interactively. Normally they rely on getting |
|
1343 | 1353 | # everything out of __main__, but for embedding purposes each IPython |
|
1344 | 1354 | # instance has its own private namespace, so we can't go shoving |
|
1345 | 1355 | # everything into __main__. |
|
1346 | 1356 | |
|
1347 | 1357 | # note, however, that we should only do this for non-embedded |
|
1348 | 1358 | # ipythons, which really mimic the __main__.__dict__ with their own |
|
1349 | 1359 | # namespace. Embedded instances, on the other hand, should not do |
|
1350 | 1360 | # this because they need to manage the user local/global namespaces |
|
1351 | 1361 | # only, but they live within a 'normal' __main__ (meaning, they |
|
1352 | 1362 | # shouldn't overtake the execution environment of the script they're |
|
1353 | 1363 | # embedded in). |
|
1354 | 1364 | |
|
1355 | 1365 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. |
|
1356 | 1366 | main_name = self.user_module.__name__ |
|
1357 | 1367 | sys.modules[main_name] = self.user_module |
|
1358 | 1368 | |
|
1359 | 1369 | def init_user_ns(self): |
|
1360 | 1370 | """Initialize all user-visible namespaces to their minimum defaults. |
|
1361 | 1371 | |
|
1362 | 1372 | Certain history lists are also initialized here, as they effectively |
|
1363 | 1373 | act as user namespaces. |
|
1364 | 1374 | |
|
1365 | 1375 | Notes |
|
1366 | 1376 | ----- |
|
1367 | 1377 | All data structures here are only filled in, they are NOT reset by this |
|
1368 | 1378 | method. If they were not empty before, data will simply be added to |
|
1369 | 1379 | them. |
|
1370 | 1380 | """ |
|
1371 | 1381 | # This function works in two parts: first we put a few things in |
|
1372 | 1382 | # user_ns, and we sync that contents into user_ns_hidden so that these |
|
1373 | 1383 | # initial variables aren't shown by %who. After the sync, we add the |
|
1374 | 1384 | # rest of what we *do* want the user to see with %who even on a new |
|
1375 | 1385 | # session (probably nothing, so they really only see their own stuff) |
|
1376 | 1386 | |
|
1377 | 1387 | # The user dict must *always* have a __builtin__ reference to the |
|
1378 | 1388 | # Python standard __builtin__ namespace, which must be imported. |
|
1379 | 1389 | # This is so that certain operations in prompt evaluation can be |
|
1380 | 1390 | # reliably executed with builtins. Note that we can NOT use |
|
1381 | 1391 | # __builtins__ (note the 's'), because that can either be a dict or a |
|
1382 | 1392 | # module, and can even mutate at runtime, depending on the context |
|
1383 | 1393 | # (Python makes no guarantees on it). In contrast, __builtin__ is |
|
1384 | 1394 | # always a module object, though it must be explicitly imported. |
|
1385 | 1395 | |
|
1386 | 1396 | # For more details: |
|
1387 | 1397 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
1388 | 1398 | ns = {} |
|
1389 | 1399 | |
|
1390 | 1400 | # make global variables for user access to the histories |
|
1391 | 1401 | ns['_ih'] = self.history_manager.input_hist_parsed |
|
1392 | 1402 | ns['_oh'] = self.history_manager.output_hist |
|
1393 | 1403 | ns['_dh'] = self.history_manager.dir_hist |
|
1394 | 1404 | |
|
1395 | 1405 | # user aliases to input and output histories. These shouldn't show up |
|
1396 | 1406 | # in %who, as they can have very large reprs. |
|
1397 | 1407 | ns['In'] = self.history_manager.input_hist_parsed |
|
1398 | 1408 | ns['Out'] = self.history_manager.output_hist |
|
1399 | 1409 | |
|
1400 | 1410 | # Store myself as the public api!!! |
|
1401 | 1411 | ns['get_ipython'] = self.get_ipython |
|
1402 | 1412 | |
|
1403 | 1413 | ns['exit'] = self.exiter |
|
1404 | 1414 | ns['quit'] = self.exiter |
|
1405 | 1415 | |
|
1406 | 1416 | # Sync what we've added so far to user_ns_hidden so these aren't seen |
|
1407 | 1417 | # by %who |
|
1408 | 1418 | self.user_ns_hidden.update(ns) |
|
1409 | 1419 | |
|
1410 | 1420 | # Anything put into ns now would show up in %who. Think twice before |
|
1411 | 1421 | # putting anything here, as we really want %who to show the user their |
|
1412 | 1422 | # stuff, not our variables. |
|
1413 | 1423 | |
|
1414 | 1424 | # Finally, update the real user's namespace |
|
1415 | 1425 | self.user_ns.update(ns) |
|
1416 | 1426 | |
|
1417 | 1427 | @property |
|
1418 | 1428 | def all_ns_refs(self): |
|
1419 | 1429 | """Get a list of references to all the namespace dictionaries in which |
|
1420 | 1430 | IPython might store a user-created object. |
|
1421 | 1431 | |
|
1422 | 1432 | Note that this does not include the displayhook, which also caches |
|
1423 | 1433 | objects from the output.""" |
|
1424 | 1434 | return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \ |
|
1425 | 1435 | [m.__dict__ for m in self._main_mod_cache.values()] |
|
1426 | 1436 | |
|
1427 | 1437 | def reset(self, new_session=True, aggressive=False): |
|
1428 | 1438 | """Clear all internal namespaces, and attempt to release references to |
|
1429 | 1439 | user objects. |
|
1430 | 1440 | |
|
1431 | 1441 | If new_session is True, a new history session will be opened. |
|
1432 | 1442 | """ |
|
1433 | 1443 | # Clear histories |
|
1434 | 1444 | self.history_manager.reset(new_session) |
|
1435 | 1445 | # Reset counter used to index all histories |
|
1436 | 1446 | if new_session: |
|
1437 | 1447 | self.execution_count = 1 |
|
1438 | 1448 | |
|
1439 | 1449 | # Reset last execution result |
|
1440 | 1450 | self.last_execution_succeeded = True |
|
1441 | 1451 | self.last_execution_result = None |
|
1442 | 1452 | |
|
1443 | 1453 | # Flush cached output items |
|
1444 | 1454 | if self.displayhook.do_full_cache: |
|
1445 | 1455 | self.displayhook.flush() |
|
1446 | 1456 | |
|
1447 | 1457 | # The main execution namespaces must be cleared very carefully, |
|
1448 | 1458 | # skipping the deletion of the builtin-related keys, because doing so |
|
1449 | 1459 | # would cause errors in many object's __del__ methods. |
|
1450 | 1460 | if self.user_ns is not self.user_global_ns: |
|
1451 | 1461 | self.user_ns.clear() |
|
1452 | 1462 | ns = self.user_global_ns |
|
1453 | 1463 | drop_keys = set(ns.keys()) |
|
1454 | 1464 | drop_keys.discard('__builtin__') |
|
1455 | 1465 | drop_keys.discard('__builtins__') |
|
1456 | 1466 | drop_keys.discard('__name__') |
|
1457 | 1467 | for k in drop_keys: |
|
1458 | 1468 | del ns[k] |
|
1459 | 1469 | |
|
1460 | 1470 | self.user_ns_hidden.clear() |
|
1461 | 1471 | |
|
1462 | 1472 | # Restore the user namespaces to minimal usability |
|
1463 | 1473 | self.init_user_ns() |
|
1464 | 1474 | if aggressive and not hasattr(self, "_sys_modules_keys"): |
|
1465 | 1475 | print("Cannot restore sys.module, no snapshot") |
|
1466 | 1476 | elif aggressive: |
|
1467 | 1477 | print("culling sys module...") |
|
1468 | 1478 | current_keys = set(sys.modules.keys()) |
|
1469 | 1479 | for k in current_keys - self._sys_modules_keys: |
|
1470 | 1480 | if k.startswith("multiprocessing"): |
|
1471 | 1481 | continue |
|
1472 | 1482 | del sys.modules[k] |
|
1473 | 1483 | |
|
1474 | 1484 | # Restore the default and user aliases |
|
1475 | 1485 | self.alias_manager.clear_aliases() |
|
1476 | 1486 | self.alias_manager.init_aliases() |
|
1477 | 1487 | |
|
1478 | 1488 | # Now define aliases that only make sense on the terminal, because they |
|
1479 | 1489 | # need direct access to the console in a way that we can't emulate in |
|
1480 | 1490 | # GUI or web frontend |
|
1481 | 1491 | if os.name == 'posix': |
|
1482 | 1492 | for cmd in ('clear', 'more', 'less', 'man'): |
|
1483 | 1493 | if cmd not in self.magics_manager.magics['line']: |
|
1484 | 1494 | self.alias_manager.soft_define_alias(cmd, cmd) |
|
1485 | 1495 | |
|
1486 | 1496 | # Flush the private list of module references kept for script |
|
1487 | 1497 | # execution protection |
|
1488 | 1498 | self.clear_main_mod_cache() |
|
1489 | 1499 | |
|
1490 | 1500 | def del_var(self, varname, by_name=False): |
|
1491 | 1501 | """Delete a variable from the various namespaces, so that, as |
|
1492 | 1502 | far as possible, we're not keeping any hidden references to it. |
|
1493 | 1503 | |
|
1494 | 1504 | Parameters |
|
1495 | 1505 | ---------- |
|
1496 | 1506 | varname : str |
|
1497 | 1507 | The name of the variable to delete. |
|
1498 | 1508 | by_name : bool |
|
1499 | 1509 | If True, delete variables with the given name in each |
|
1500 | 1510 | namespace. If False (default), find the variable in the user |
|
1501 | 1511 | namespace, and delete references to it. |
|
1502 | 1512 | """ |
|
1503 | 1513 | if varname in ('__builtin__', '__builtins__'): |
|
1504 | 1514 | raise ValueError("Refusing to delete %s" % varname) |
|
1505 | 1515 | |
|
1506 | 1516 | ns_refs = self.all_ns_refs |
|
1507 | 1517 | |
|
1508 | 1518 | if by_name: # Delete by name |
|
1509 | 1519 | for ns in ns_refs: |
|
1510 | 1520 | try: |
|
1511 | 1521 | del ns[varname] |
|
1512 | 1522 | except KeyError: |
|
1513 | 1523 | pass |
|
1514 | 1524 | else: # Delete by object |
|
1515 | 1525 | try: |
|
1516 | 1526 | obj = self.user_ns[varname] |
|
1517 | 1527 | except KeyError: |
|
1518 | 1528 | raise NameError("name '%s' is not defined" % varname) |
|
1519 | 1529 | # Also check in output history |
|
1520 | 1530 | ns_refs.append(self.history_manager.output_hist) |
|
1521 | 1531 | for ns in ns_refs: |
|
1522 | 1532 | to_delete = [n for n, o in ns.items() if o is obj] |
|
1523 | 1533 | for name in to_delete: |
|
1524 | 1534 | del ns[name] |
|
1525 | 1535 | |
|
1526 | 1536 | # Ensure it is removed from the last execution result |
|
1527 | 1537 | if self.last_execution_result.result is obj: |
|
1528 | 1538 | self.last_execution_result = None |
|
1529 | 1539 | |
|
1530 | 1540 | # displayhook keeps extra references, but not in a dictionary |
|
1531 | 1541 | for name in ('_', '__', '___'): |
|
1532 | 1542 | if getattr(self.displayhook, name) is obj: |
|
1533 | 1543 | setattr(self.displayhook, name, None) |
|
1534 | 1544 | |
|
1535 | 1545 | def reset_selective(self, regex=None): |
|
1536 | 1546 | """Clear selective variables from internal namespaces based on a |
|
1537 | 1547 | specified regular expression. |
|
1538 | 1548 | |
|
1539 | 1549 | Parameters |
|
1540 | 1550 | ---------- |
|
1541 | 1551 | regex : string or compiled pattern, optional |
|
1542 | 1552 | A regular expression pattern that will be used in searching |
|
1543 | 1553 | variable names in the users namespaces. |
|
1544 | 1554 | """ |
|
1545 | 1555 | if regex is not None: |
|
1546 | 1556 | try: |
|
1547 | 1557 | m = re.compile(regex) |
|
1548 | 1558 | except TypeError: |
|
1549 | 1559 | raise TypeError('regex must be a string or compiled pattern') |
|
1550 | 1560 | # Search for keys in each namespace that match the given regex |
|
1551 | 1561 | # If a match is found, delete the key/value pair. |
|
1552 | 1562 | for ns in self.all_ns_refs: |
|
1553 | 1563 | for var in ns: |
|
1554 | 1564 | if m.search(var): |
|
1555 | 1565 | del ns[var] |
|
1556 | 1566 | |
|
1557 | 1567 | def push(self, variables, interactive=True): |
|
1558 | 1568 | """Inject a group of variables into the IPython user namespace. |
|
1559 | 1569 | |
|
1560 | 1570 | Parameters |
|
1561 | 1571 | ---------- |
|
1562 | 1572 | variables : dict, str or list/tuple of str |
|
1563 | 1573 | The variables to inject into the user's namespace. If a dict, a |
|
1564 | 1574 | simple update is done. If a str, the string is assumed to have |
|
1565 | 1575 | variable names separated by spaces. A list/tuple of str can also |
|
1566 | 1576 | be used to give the variable names. If just the variable names are |
|
1567 | 1577 | give (list/tuple/str) then the variable values looked up in the |
|
1568 | 1578 | callers frame. |
|
1569 | 1579 | interactive : bool |
|
1570 | 1580 | If True (default), the variables will be listed with the ``who`` |
|
1571 | 1581 | magic. |
|
1572 | 1582 | """ |
|
1573 | 1583 | vdict = None |
|
1574 | 1584 | |
|
1575 | 1585 | # We need a dict of name/value pairs to do namespace updates. |
|
1576 | 1586 | if isinstance(variables, dict): |
|
1577 | 1587 | vdict = variables |
|
1578 | 1588 | elif isinstance(variables, (str, list, tuple)): |
|
1579 | 1589 | if isinstance(variables, str): |
|
1580 | 1590 | vlist = variables.split() |
|
1581 | 1591 | else: |
|
1582 | 1592 | vlist = variables |
|
1583 | 1593 | vdict = {} |
|
1584 | 1594 | cf = sys._getframe(1) |
|
1585 | 1595 | for name in vlist: |
|
1586 | 1596 | try: |
|
1587 | 1597 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) |
|
1588 | 1598 | except: |
|
1589 | 1599 | print('Could not get variable %s from %s' % |
|
1590 | 1600 | (name,cf.f_code.co_name)) |
|
1591 | 1601 | else: |
|
1592 | 1602 | raise ValueError('variables must be a dict/str/list/tuple') |
|
1593 | 1603 | |
|
1594 | 1604 | # Propagate variables to user namespace |
|
1595 | 1605 | self.user_ns.update(vdict) |
|
1596 | 1606 | |
|
1597 | 1607 | # And configure interactive visibility |
|
1598 | 1608 | user_ns_hidden = self.user_ns_hidden |
|
1599 | 1609 | if interactive: |
|
1600 | 1610 | for name in vdict: |
|
1601 | 1611 | user_ns_hidden.pop(name, None) |
|
1602 | 1612 | else: |
|
1603 | 1613 | user_ns_hidden.update(vdict) |
|
1604 | 1614 | |
|
1605 | 1615 | def drop_by_id(self, variables): |
|
1606 | 1616 | """Remove a dict of variables from the user namespace, if they are the |
|
1607 | 1617 | same as the values in the dictionary. |
|
1608 | 1618 | |
|
1609 | 1619 | This is intended for use by extensions: variables that they've added can |
|
1610 | 1620 | be taken back out if they are unloaded, without removing any that the |
|
1611 | 1621 | user has overwritten. |
|
1612 | 1622 | |
|
1613 | 1623 | Parameters |
|
1614 | 1624 | ---------- |
|
1615 | 1625 | variables : dict |
|
1616 | 1626 | A dictionary mapping object names (as strings) to the objects. |
|
1617 | 1627 | """ |
|
1618 | 1628 | for name, obj in variables.items(): |
|
1619 | 1629 | if name in self.user_ns and self.user_ns[name] is obj: |
|
1620 | 1630 | del self.user_ns[name] |
|
1621 | 1631 | self.user_ns_hidden.pop(name, None) |
|
1622 | 1632 | |
|
1623 | 1633 | #------------------------------------------------------------------------- |
|
1624 | 1634 | # Things related to object introspection |
|
1625 | 1635 | #------------------------------------------------------------------------- |
|
1626 | 1636 | |
|
1627 | 1637 | def _ofind(self, oname, namespaces=None): |
|
1628 | 1638 | """Find an object in the available namespaces. |
|
1629 | 1639 | |
|
1630 | 1640 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic |
|
1631 | 1641 | |
|
1632 | 1642 | Has special code to detect magic functions. |
|
1633 | 1643 | """ |
|
1634 | 1644 | oname = oname.strip() |
|
1635 | 1645 | if not oname.startswith(ESC_MAGIC) and \ |
|
1636 | 1646 | not oname.startswith(ESC_MAGIC2) and \ |
|
1637 | 1647 | not all(a.isidentifier() for a in oname.split(".")): |
|
1638 | 1648 | return {'found': False} |
|
1639 | 1649 | |
|
1640 | 1650 | if namespaces is None: |
|
1641 | 1651 | # Namespaces to search in: |
|
1642 | 1652 | # Put them in a list. The order is important so that we |
|
1643 | 1653 | # find things in the same order that Python finds them. |
|
1644 | 1654 | namespaces = [ ('Interactive', self.user_ns), |
|
1645 | 1655 | ('Interactive (global)', self.user_global_ns), |
|
1646 | 1656 | ('Python builtin', builtin_mod.__dict__), |
|
1647 | 1657 | ] |
|
1648 | 1658 | |
|
1649 | 1659 | ismagic = False |
|
1650 | 1660 | isalias = False |
|
1651 | 1661 | found = False |
|
1652 | 1662 | ospace = None |
|
1653 | 1663 | parent = None |
|
1654 | 1664 | obj = None |
|
1655 | 1665 | |
|
1656 | 1666 | |
|
1657 | 1667 | # Look for the given name by splitting it in parts. If the head is |
|
1658 | 1668 | # found, then we look for all the remaining parts as members, and only |
|
1659 | 1669 | # declare success if we can find them all. |
|
1660 | 1670 | oname_parts = oname.split('.') |
|
1661 | 1671 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] |
|
1662 | 1672 | for nsname,ns in namespaces: |
|
1663 | 1673 | try: |
|
1664 | 1674 | obj = ns[oname_head] |
|
1665 | 1675 | except KeyError: |
|
1666 | 1676 | continue |
|
1667 | 1677 | else: |
|
1668 | 1678 | for idx, part in enumerate(oname_rest): |
|
1669 | 1679 | try: |
|
1670 | 1680 | parent = obj |
|
1671 | 1681 | # The last part is looked up in a special way to avoid |
|
1672 | 1682 | # descriptor invocation as it may raise or have side |
|
1673 | 1683 | # effects. |
|
1674 | 1684 | if idx == len(oname_rest) - 1: |
|
1675 | 1685 | obj = self._getattr_property(obj, part) |
|
1676 | 1686 | else: |
|
1677 | 1687 | obj = getattr(obj, part) |
|
1678 | 1688 | except: |
|
1679 | 1689 | # Blanket except b/c some badly implemented objects |
|
1680 | 1690 | # allow __getattr__ to raise exceptions other than |
|
1681 | 1691 | # AttributeError, which then crashes IPython. |
|
1682 | 1692 | break |
|
1683 | 1693 | else: |
|
1684 | 1694 | # If we finish the for loop (no break), we got all members |
|
1685 | 1695 | found = True |
|
1686 | 1696 | ospace = nsname |
|
1687 | 1697 | break # namespace loop |
|
1688 | 1698 | |
|
1689 | 1699 | # Try to see if it's magic |
|
1690 | 1700 | if not found: |
|
1691 | 1701 | obj = None |
|
1692 | 1702 | if oname.startswith(ESC_MAGIC2): |
|
1693 | 1703 | oname = oname.lstrip(ESC_MAGIC2) |
|
1694 | 1704 | obj = self.find_cell_magic(oname) |
|
1695 | 1705 | elif oname.startswith(ESC_MAGIC): |
|
1696 | 1706 | oname = oname.lstrip(ESC_MAGIC) |
|
1697 | 1707 | obj = self.find_line_magic(oname) |
|
1698 | 1708 | else: |
|
1699 | 1709 | # search without prefix, so run? will find %run? |
|
1700 | 1710 | obj = self.find_line_magic(oname) |
|
1701 | 1711 | if obj is None: |
|
1702 | 1712 | obj = self.find_cell_magic(oname) |
|
1703 | 1713 | if obj is not None: |
|
1704 | 1714 | found = True |
|
1705 | 1715 | ospace = 'IPython internal' |
|
1706 | 1716 | ismagic = True |
|
1707 | 1717 | isalias = isinstance(obj, Alias) |
|
1708 | 1718 | |
|
1709 | 1719 | # Last try: special-case some literals like '', [], {}, etc: |
|
1710 | 1720 | if not found and oname_head in ["''",'""','[]','{}','()']: |
|
1711 | 1721 | obj = eval(oname_head) |
|
1712 | 1722 | found = True |
|
1713 | 1723 | ospace = 'Interactive' |
|
1714 | 1724 | |
|
1715 | 1725 | return { |
|
1716 | 1726 | 'obj':obj, |
|
1717 | 1727 | 'found':found, |
|
1718 | 1728 | 'parent':parent, |
|
1719 | 1729 | 'ismagic':ismagic, |
|
1720 | 1730 | 'isalias':isalias, |
|
1721 | 1731 | 'namespace':ospace |
|
1722 | 1732 | } |
|
1723 | 1733 | |
|
1724 | 1734 | @staticmethod |
|
1725 | 1735 | def _getattr_property(obj, attrname): |
|
1726 | 1736 | """Property-aware getattr to use in object finding. |
|
1727 | 1737 | |
|
1728 | 1738 | If attrname represents a property, return it unevaluated (in case it has |
|
1729 | 1739 | side effects or raises an error. |
|
1730 | 1740 | |
|
1731 | 1741 | """ |
|
1732 | 1742 | if not isinstance(obj, type): |
|
1733 | 1743 | try: |
|
1734 | 1744 | # `getattr(type(obj), attrname)` is not guaranteed to return |
|
1735 | 1745 | # `obj`, but does so for property: |
|
1736 | 1746 | # |
|
1737 | 1747 | # property.__get__(self, None, cls) -> self |
|
1738 | 1748 | # |
|
1739 | 1749 | # The universal alternative is to traverse the mro manually |
|
1740 | 1750 | # searching for attrname in class dicts. |
|
1741 | 1751 | attr = getattr(type(obj), attrname) |
|
1742 | 1752 | except AttributeError: |
|
1743 | 1753 | pass |
|
1744 | 1754 | else: |
|
1745 | 1755 | # This relies on the fact that data descriptors (with both |
|
1746 | 1756 | # __get__ & __set__ magic methods) take precedence over |
|
1747 | 1757 | # instance-level attributes: |
|
1748 | 1758 | # |
|
1749 | 1759 | # class A(object): |
|
1750 | 1760 | # @property |
|
1751 | 1761 | # def foobar(self): return 123 |
|
1752 | 1762 | # a = A() |
|
1753 | 1763 | # a.__dict__['foobar'] = 345 |
|
1754 | 1764 | # a.foobar # == 123 |
|
1755 | 1765 | # |
|
1756 | 1766 | # So, a property may be returned right away. |
|
1757 | 1767 | if isinstance(attr, property): |
|
1758 | 1768 | return attr |
|
1759 | 1769 | |
|
1760 | 1770 | # Nothing helped, fall back. |
|
1761 | 1771 | return getattr(obj, attrname) |
|
1762 | 1772 | |
|
1763 | 1773 | def _object_find(self, oname, namespaces=None): |
|
1764 | 1774 | """Find an object and return a struct with info about it.""" |
|
1765 | 1775 | return Struct(self._ofind(oname, namespaces)) |
|
1766 | 1776 | |
|
1767 | 1777 | def _inspect(self, meth, oname, namespaces=None, **kw): |
|
1768 | 1778 | """Generic interface to the inspector system. |
|
1769 | 1779 | |
|
1770 | 1780 | This function is meant to be called by pdef, pdoc & friends. |
|
1771 | 1781 | """ |
|
1772 | 1782 | info = self._object_find(oname, namespaces) |
|
1773 | 1783 | docformat = ( |
|
1774 | 1784 | sphinxify(self.object_inspect(oname)) if self.sphinxify_docstring else None |
|
1775 | 1785 | ) |
|
1776 | 1786 | if info.found: |
|
1777 | 1787 | pmethod = getattr(self.inspector, meth) |
|
1778 | 1788 | # TODO: only apply format_screen to the plain/text repr of the mime |
|
1779 | 1789 | # bundle. |
|
1780 | 1790 | formatter = format_screen if info.ismagic else docformat |
|
1781 | 1791 | if meth == 'pdoc': |
|
1782 | 1792 | pmethod(info.obj, oname, formatter) |
|
1783 | 1793 | elif meth == 'pinfo': |
|
1784 | 1794 | pmethod( |
|
1785 | 1795 | info.obj, |
|
1786 | 1796 | oname, |
|
1787 | 1797 | formatter, |
|
1788 | 1798 | info, |
|
1789 | 1799 | enable_html_pager=self.enable_html_pager, |
|
1790 | 1800 | **kw, |
|
1791 | 1801 | ) |
|
1792 | 1802 | else: |
|
1793 | 1803 | pmethod(info.obj, oname) |
|
1794 | 1804 | else: |
|
1795 | 1805 | print('Object `%s` not found.' % oname) |
|
1796 | 1806 | return 'not found' # so callers can take other action |
|
1797 | 1807 | |
|
1798 | 1808 | def object_inspect(self, oname, detail_level=0): |
|
1799 | 1809 | """Get object info about oname""" |
|
1800 | 1810 | with self.builtin_trap: |
|
1801 | 1811 | info = self._object_find(oname) |
|
1802 | 1812 | if info.found: |
|
1803 | 1813 | return self.inspector.info(info.obj, oname, info=info, |
|
1804 | 1814 | detail_level=detail_level |
|
1805 | 1815 | ) |
|
1806 | 1816 | else: |
|
1807 | 1817 | return oinspect.object_info(name=oname, found=False) |
|
1808 | 1818 | |
|
1809 | 1819 | def object_inspect_text(self, oname, detail_level=0): |
|
1810 | 1820 | """Get object info as formatted text""" |
|
1811 | 1821 | return self.object_inspect_mime(oname, detail_level)['text/plain'] |
|
1812 | 1822 | |
|
1813 | 1823 | def object_inspect_mime(self, oname, detail_level=0): |
|
1814 | 1824 | """Get object info as a mimebundle of formatted representations. |
|
1815 | 1825 | |
|
1816 | 1826 | A mimebundle is a dictionary, keyed by mime-type. |
|
1817 | 1827 | It must always have the key `'text/plain'`. |
|
1818 | 1828 | """ |
|
1819 | 1829 | with self.builtin_trap: |
|
1820 | 1830 | info = self._object_find(oname) |
|
1821 | 1831 | if info.found: |
|
1822 | 1832 | docformat = ( |
|
1823 | 1833 | sphinxify(self.object_inspect(oname)) |
|
1824 | 1834 | if self.sphinxify_docstring |
|
1825 | 1835 | else None |
|
1826 | 1836 | ) |
|
1827 | 1837 | return self.inspector._get_info( |
|
1828 | 1838 | info.obj, |
|
1829 | 1839 | oname, |
|
1830 | 1840 | info=info, |
|
1831 | 1841 | detail_level=detail_level, |
|
1832 | 1842 | formatter=docformat, |
|
1833 | 1843 | ) |
|
1834 | 1844 | else: |
|
1835 | 1845 | raise KeyError(oname) |
|
1836 | 1846 | |
|
1837 | 1847 | #------------------------------------------------------------------------- |
|
1838 | 1848 | # Things related to history management |
|
1839 | 1849 | #------------------------------------------------------------------------- |
|
1840 | 1850 | |
|
1841 | 1851 | def init_history(self): |
|
1842 | 1852 | """Sets up the command history, and starts regular autosaves.""" |
|
1843 | 1853 | self.history_manager = HistoryManager(shell=self, parent=self) |
|
1844 | 1854 | self.configurables.append(self.history_manager) |
|
1845 | 1855 | |
|
1846 | 1856 | #------------------------------------------------------------------------- |
|
1847 | 1857 | # Things related to exception handling and tracebacks (not debugging) |
|
1848 | 1858 | #------------------------------------------------------------------------- |
|
1849 | 1859 | |
|
1850 | 1860 | debugger_cls = InterruptiblePdb |
|
1851 | 1861 | |
|
1852 | 1862 | def init_traceback_handlers(self, custom_exceptions): |
|
1853 | 1863 | # Syntax error handler. |
|
1854 | 1864 | self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor', parent=self) |
|
1855 | 1865 | |
|
1856 | 1866 | # The interactive one is initialized with an offset, meaning we always |
|
1857 | 1867 | # want to remove the topmost item in the traceback, which is our own |
|
1858 | 1868 | # internal code. Valid modes: ['Plain','Context','Verbose','Minimal'] |
|
1859 | 1869 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', |
|
1860 | 1870 | color_scheme='NoColor', |
|
1861 | 1871 | tb_offset = 1, |
|
1862 | 1872 | check_cache=check_linecache_ipython, |
|
1863 | 1873 | debugger_cls=self.debugger_cls, parent=self) |
|
1864 | 1874 | |
|
1865 | 1875 | # The instance will store a pointer to the system-wide exception hook, |
|
1866 | 1876 | # so that runtime code (such as magics) can access it. This is because |
|
1867 | 1877 | # during the read-eval loop, it may get temporarily overwritten. |
|
1868 | 1878 | self.sys_excepthook = sys.excepthook |
|
1869 | 1879 | |
|
1870 | 1880 | # and add any custom exception handlers the user may have specified |
|
1871 | 1881 | self.set_custom_exc(*custom_exceptions) |
|
1872 | 1882 | |
|
1873 | 1883 | # Set the exception mode |
|
1874 | 1884 | self.InteractiveTB.set_mode(mode=self.xmode) |
|
1875 | 1885 | |
|
1876 | 1886 | def set_custom_exc(self, exc_tuple, handler): |
|
1877 | 1887 | """set_custom_exc(exc_tuple, handler) |
|
1878 | 1888 | |
|
1879 | 1889 | Set a custom exception handler, which will be called if any of the |
|
1880 | 1890 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
1881 | 1891 | run_code() method). |
|
1882 | 1892 | |
|
1883 | 1893 | Parameters |
|
1884 | 1894 | ---------- |
|
1885 | 1895 | |
|
1886 | 1896 | exc_tuple : tuple of exception classes |
|
1887 | 1897 | A *tuple* of exception classes, for which to call the defined |
|
1888 | 1898 | handler. It is very important that you use a tuple, and NOT A |
|
1889 | 1899 | LIST here, because of the way Python's except statement works. If |
|
1890 | 1900 | you only want to trap a single exception, use a singleton tuple:: |
|
1891 | 1901 | |
|
1892 | 1902 | exc_tuple == (MyCustomException,) |
|
1893 | 1903 | |
|
1894 | 1904 | handler : callable |
|
1895 | 1905 | handler must have the following signature:: |
|
1896 | 1906 | |
|
1897 | 1907 | def my_handler(self, etype, value, tb, tb_offset=None): |
|
1898 | 1908 | ... |
|
1899 | 1909 | return structured_traceback |
|
1900 | 1910 | |
|
1901 | 1911 | Your handler must return a structured traceback (a list of strings), |
|
1902 | 1912 | or None. |
|
1903 | 1913 | |
|
1904 | 1914 | This will be made into an instance method (via types.MethodType) |
|
1905 | 1915 | of IPython itself, and it will be called if any of the exceptions |
|
1906 | 1916 | listed in the exc_tuple are caught. If the handler is None, an |
|
1907 | 1917 | internal basic one is used, which just prints basic info. |
|
1908 | 1918 | |
|
1909 | 1919 | To protect IPython from crashes, if your handler ever raises an |
|
1910 | 1920 | exception or returns an invalid result, it will be immediately |
|
1911 | 1921 | disabled. |
|
1912 | 1922 | |
|
1913 | 1923 | Notes |
|
1914 | 1924 | ----- |
|
1915 | 1925 | |
|
1916 | 1926 | WARNING: by putting in your own exception handler into IPython's main |
|
1917 | 1927 | execution loop, you run a very good chance of nasty crashes. This |
|
1918 | 1928 | facility should only be used if you really know what you are doing.""" |
|
1919 | 1929 | if not isinstance(exc_tuple, tuple): |
|
1920 | 1930 | raise TypeError("The custom exceptions must be given as a tuple.") |
|
1921 | 1931 | |
|
1922 | 1932 | def dummy_handler(self, etype, value, tb, tb_offset=None): |
|
1923 | 1933 | print('*** Simple custom exception handler ***') |
|
1924 | 1934 | print('Exception type :', etype) |
|
1925 | 1935 | print('Exception value:', value) |
|
1926 | 1936 | print('Traceback :', tb) |
|
1927 | 1937 | |
|
1928 | 1938 | def validate_stb(stb): |
|
1929 | 1939 | """validate structured traceback return type |
|
1930 | 1940 | |
|
1931 | 1941 | return type of CustomTB *should* be a list of strings, but allow |
|
1932 | 1942 | single strings or None, which are harmless. |
|
1933 | 1943 | |
|
1934 | 1944 | This function will *always* return a list of strings, |
|
1935 | 1945 | and will raise a TypeError if stb is inappropriate. |
|
1936 | 1946 | """ |
|
1937 | 1947 | msg = "CustomTB must return list of strings, not %r" % stb |
|
1938 | 1948 | if stb is None: |
|
1939 | 1949 | return [] |
|
1940 | 1950 | elif isinstance(stb, str): |
|
1941 | 1951 | return [stb] |
|
1942 | 1952 | elif not isinstance(stb, list): |
|
1943 | 1953 | raise TypeError(msg) |
|
1944 | 1954 | # it's a list |
|
1945 | 1955 | for line in stb: |
|
1946 | 1956 | # check every element |
|
1947 | 1957 | if not isinstance(line, str): |
|
1948 | 1958 | raise TypeError(msg) |
|
1949 | 1959 | return stb |
|
1950 | 1960 | |
|
1951 | 1961 | if handler is None: |
|
1952 | 1962 | wrapped = dummy_handler |
|
1953 | 1963 | else: |
|
1954 | 1964 | def wrapped(self,etype,value,tb,tb_offset=None): |
|
1955 | 1965 | """wrap CustomTB handler, to protect IPython from user code |
|
1956 | 1966 | |
|
1957 | 1967 | This makes it harder (but not impossible) for custom exception |
|
1958 | 1968 | handlers to crash IPython. |
|
1959 | 1969 | """ |
|
1960 | 1970 | try: |
|
1961 | 1971 | stb = handler(self,etype,value,tb,tb_offset=tb_offset) |
|
1962 | 1972 | return validate_stb(stb) |
|
1963 | 1973 | except: |
|
1964 | 1974 | # clear custom handler immediately |
|
1965 | 1975 | self.set_custom_exc((), None) |
|
1966 | 1976 | print("Custom TB Handler failed, unregistering", file=sys.stderr) |
|
1967 | 1977 | # show the exception in handler first |
|
1968 | 1978 | stb = self.InteractiveTB.structured_traceback(*sys.exc_info()) |
|
1969 | 1979 | print(self.InteractiveTB.stb2text(stb)) |
|
1970 | 1980 | print("The original exception:") |
|
1971 | 1981 | stb = self.InteractiveTB.structured_traceback( |
|
1972 | 1982 | (etype,value,tb), tb_offset=tb_offset |
|
1973 | 1983 | ) |
|
1974 | 1984 | return stb |
|
1975 | 1985 | |
|
1976 | 1986 | self.CustomTB = types.MethodType(wrapped,self) |
|
1977 | 1987 | self.custom_exceptions = exc_tuple |
|
1978 | 1988 | |
|
1979 | 1989 | def excepthook(self, etype, value, tb): |
|
1980 | 1990 | """One more defense for GUI apps that call sys.excepthook. |
|
1981 | 1991 | |
|
1982 | 1992 | GUI frameworks like wxPython trap exceptions and call |
|
1983 | 1993 | sys.excepthook themselves. I guess this is a feature that |
|
1984 | 1994 | enables them to keep running after exceptions that would |
|
1985 | 1995 | otherwise kill their mainloop. This is a bother for IPython |
|
1986 | 1996 | which expects to catch all of the program exceptions with a try: |
|
1987 | 1997 | except: statement. |
|
1988 | 1998 | |
|
1989 | 1999 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
1990 | 2000 | any app directly invokes sys.excepthook, it will look to the user like |
|
1991 | 2001 | IPython crashed. In order to work around this, we can disable the |
|
1992 | 2002 | CrashHandler and replace it with this excepthook instead, which prints a |
|
1993 | 2003 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
1994 | 2004 | call sys.excepthook will generate a regular-looking exception from |
|
1995 | 2005 | IPython, and the CrashHandler will only be triggered by real IPython |
|
1996 | 2006 | crashes. |
|
1997 | 2007 | |
|
1998 | 2008 | This hook should be used sparingly, only in places which are not likely |
|
1999 | 2009 | to be true IPython errors. |
|
2000 | 2010 | """ |
|
2001 | 2011 | self.showtraceback((etype, value, tb), tb_offset=0) |
|
2002 | 2012 | |
|
2003 | 2013 | def _get_exc_info(self, exc_tuple=None): |
|
2004 | 2014 | """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc. |
|
2005 | 2015 | |
|
2006 | 2016 | Ensures sys.last_type,value,traceback hold the exc_info we found, |
|
2007 | 2017 | from whichever source. |
|
2008 | 2018 | |
|
2009 | 2019 | raises ValueError if none of these contain any information |
|
2010 | 2020 | """ |
|
2011 | 2021 | if exc_tuple is None: |
|
2012 | 2022 | etype, value, tb = sys.exc_info() |
|
2013 | 2023 | else: |
|
2014 | 2024 | etype, value, tb = exc_tuple |
|
2015 | 2025 | |
|
2016 | 2026 | if etype is None: |
|
2017 | 2027 | if hasattr(sys, 'last_type'): |
|
2018 | 2028 | etype, value, tb = sys.last_type, sys.last_value, \ |
|
2019 | 2029 | sys.last_traceback |
|
2020 | 2030 | |
|
2021 | 2031 | if etype is None: |
|
2022 | 2032 | raise ValueError("No exception to find") |
|
2023 | 2033 | |
|
2024 | 2034 | # Now store the exception info in sys.last_type etc. |
|
2025 | 2035 | # WARNING: these variables are somewhat deprecated and not |
|
2026 | 2036 | # necessarily safe to use in a threaded environment, but tools |
|
2027 | 2037 | # like pdb depend on their existence, so let's set them. If we |
|
2028 | 2038 | # find problems in the field, we'll need to revisit their use. |
|
2029 | 2039 | sys.last_type = etype |
|
2030 | 2040 | sys.last_value = value |
|
2031 | 2041 | sys.last_traceback = tb |
|
2032 | 2042 | |
|
2033 | 2043 | return etype, value, tb |
|
2034 | 2044 | |
|
2035 | 2045 | def show_usage_error(self, exc): |
|
2036 | 2046 | """Show a short message for UsageErrors |
|
2037 | 2047 | |
|
2038 | 2048 | These are special exceptions that shouldn't show a traceback. |
|
2039 | 2049 | """ |
|
2040 | 2050 | print("UsageError: %s" % exc, file=sys.stderr) |
|
2041 | 2051 | |
|
2042 | 2052 | def get_exception_only(self, exc_tuple=None): |
|
2043 | 2053 | """ |
|
2044 | 2054 | Return as a string (ending with a newline) the exception that |
|
2045 | 2055 | just occurred, without any traceback. |
|
2046 | 2056 | """ |
|
2047 | 2057 | etype, value, tb = self._get_exc_info(exc_tuple) |
|
2048 | 2058 | msg = traceback.format_exception_only(etype, value) |
|
2049 | 2059 | return ''.join(msg) |
|
2050 | 2060 | |
|
2051 | 2061 | def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None, |
|
2052 | 2062 | exception_only=False, running_compiled_code=False): |
|
2053 | 2063 | """Display the exception that just occurred. |
|
2054 | 2064 | |
|
2055 | 2065 | If nothing is known about the exception, this is the method which |
|
2056 | 2066 | should be used throughout the code for presenting user tracebacks, |
|
2057 | 2067 | rather than directly invoking the InteractiveTB object. |
|
2058 | 2068 | |
|
2059 | 2069 | A specific showsyntaxerror() also exists, but this method can take |
|
2060 | 2070 | care of calling it if needed, so unless you are explicitly catching a |
|
2061 | 2071 | SyntaxError exception, don't try to analyze the stack manually and |
|
2062 | 2072 | simply call this method.""" |
|
2063 | 2073 | |
|
2064 | 2074 | try: |
|
2065 | 2075 | try: |
|
2066 | 2076 | etype, value, tb = self._get_exc_info(exc_tuple) |
|
2067 | 2077 | except ValueError: |
|
2068 | 2078 | print('No traceback available to show.', file=sys.stderr) |
|
2069 | 2079 | return |
|
2070 | 2080 | |
|
2071 | 2081 | if issubclass(etype, SyntaxError): |
|
2072 | 2082 | # Though this won't be called by syntax errors in the input |
|
2073 | 2083 | # line, there may be SyntaxError cases with imported code. |
|
2074 | 2084 | self.showsyntaxerror(filename, running_compiled_code) |
|
2075 | 2085 | elif etype is UsageError: |
|
2076 | 2086 | self.show_usage_error(value) |
|
2077 | 2087 | else: |
|
2078 | 2088 | if exception_only: |
|
2079 | 2089 | stb = ['An exception has occurred, use %tb to see ' |
|
2080 | 2090 | 'the full traceback.\n'] |
|
2081 | 2091 | stb.extend(self.InteractiveTB.get_exception_only(etype, |
|
2082 | 2092 | value)) |
|
2083 | 2093 | else: |
|
2084 | 2094 | try: |
|
2085 | 2095 | # Exception classes can customise their traceback - we |
|
2086 | 2096 | # use this in IPython.parallel for exceptions occurring |
|
2087 | 2097 | # in the engines. This should return a list of strings. |
|
2088 | 2098 | stb = value._render_traceback_() |
|
2089 | 2099 | except Exception: |
|
2090 | 2100 | stb = self.InteractiveTB.structured_traceback(etype, |
|
2091 | 2101 | value, tb, tb_offset=tb_offset) |
|
2092 | 2102 | |
|
2093 | 2103 | self._showtraceback(etype, value, stb) |
|
2094 | 2104 | if self.call_pdb: |
|
2095 | 2105 | # drop into debugger |
|
2096 | 2106 | self.debugger(force=True) |
|
2097 | 2107 | return |
|
2098 | 2108 | |
|
2099 | 2109 | # Actually show the traceback |
|
2100 | 2110 | self._showtraceback(etype, value, stb) |
|
2101 | 2111 | |
|
2102 | 2112 | except KeyboardInterrupt: |
|
2103 | 2113 | print('\n' + self.get_exception_only(), file=sys.stderr) |
|
2104 | 2114 | |
|
2105 | 2115 | def _showtraceback(self, etype, evalue, stb: str): |
|
2106 | 2116 | """Actually show a traceback. |
|
2107 | 2117 | |
|
2108 | 2118 | Subclasses may override this method to put the traceback on a different |
|
2109 | 2119 | place, like a side channel. |
|
2110 | 2120 | """ |
|
2111 | 2121 | val = self.InteractiveTB.stb2text(stb) |
|
2112 | 2122 | try: |
|
2113 | 2123 | print(val) |
|
2114 | 2124 | except UnicodeEncodeError: |
|
2115 | 2125 | print(val.encode("utf-8", "backslashreplace").decode()) |
|
2116 | 2126 | |
|
2117 | 2127 | def showsyntaxerror(self, filename=None, running_compiled_code=False): |
|
2118 | 2128 | """Display the syntax error that just occurred. |
|
2119 | 2129 | |
|
2120 | 2130 | This doesn't display a stack trace because there isn't one. |
|
2121 | 2131 | |
|
2122 | 2132 | If a filename is given, it is stuffed in the exception instead |
|
2123 | 2133 | of what was there before (because Python's parser always uses |
|
2124 | 2134 | "<string>" when reading from a string). |
|
2125 | 2135 | |
|
2126 | 2136 | If the syntax error occurred when running a compiled code (i.e. running_compile_code=True), |
|
2127 | 2137 | longer stack trace will be displayed. |
|
2128 | 2138 | """ |
|
2129 | 2139 | etype, value, last_traceback = self._get_exc_info() |
|
2130 | 2140 | |
|
2131 | 2141 | if filename and issubclass(etype, SyntaxError): |
|
2132 | 2142 | try: |
|
2133 | 2143 | value.filename = filename |
|
2134 | 2144 | except: |
|
2135 | 2145 | # Not the format we expect; leave it alone |
|
2136 | 2146 | pass |
|
2137 | 2147 | |
|
2138 | 2148 | # If the error occurred when executing compiled code, we should provide full stacktrace. |
|
2139 | 2149 | elist = traceback.extract_tb(last_traceback) if running_compiled_code else [] |
|
2140 | 2150 | stb = self.SyntaxTB.structured_traceback(etype, value, elist) |
|
2141 | 2151 | self._showtraceback(etype, value, stb) |
|
2142 | 2152 | |
|
2143 | 2153 | # This is overridden in TerminalInteractiveShell to show a message about |
|
2144 | 2154 | # the %paste magic. |
|
2145 | 2155 | def showindentationerror(self): |
|
2146 | 2156 | """Called by _run_cell when there's an IndentationError in code entered |
|
2147 | 2157 | at the prompt. |
|
2148 | 2158 | |
|
2149 | 2159 | This is overridden in TerminalInteractiveShell to show a message about |
|
2150 | 2160 | the %paste magic.""" |
|
2151 | 2161 | self.showsyntaxerror() |
|
2152 | 2162 | |
|
2153 | 2163 | #------------------------------------------------------------------------- |
|
2154 | 2164 | # Things related to readline |
|
2155 | 2165 | #------------------------------------------------------------------------- |
|
2156 | 2166 | |
|
2157 | 2167 | def init_readline(self): |
|
2158 | 2168 | """DEPRECATED |
|
2159 | 2169 | |
|
2160 | 2170 | Moved to terminal subclass, here only to simplify the init logic.""" |
|
2161 | 2171 | # Set a number of methods that depend on readline to be no-op |
|
2162 | 2172 | warnings.warn('`init_readline` is no-op since IPython 5.0 and is Deprecated', |
|
2163 | 2173 | DeprecationWarning, stacklevel=2) |
|
2164 | 2174 | self.set_custom_completer = no_op |
|
2165 | 2175 | |
|
2166 | 2176 | @skip_doctest |
|
2167 | 2177 | def set_next_input(self, s, replace=False): |
|
2168 | 2178 | """ Sets the 'default' input string for the next command line. |
|
2169 | 2179 | |
|
2170 | 2180 | Example:: |
|
2171 | 2181 | |
|
2172 | 2182 | In [1]: _ip.set_next_input("Hello Word") |
|
2173 | 2183 | In [2]: Hello Word_ # cursor is here |
|
2174 | 2184 | """ |
|
2175 | 2185 | self.rl_next_input = s |
|
2176 | 2186 | |
|
2177 | 2187 | def _indent_current_str(self): |
|
2178 | 2188 | """return the current level of indentation as a string""" |
|
2179 | 2189 | return self.input_splitter.get_indent_spaces() * ' ' |
|
2180 | 2190 | |
|
2181 | 2191 | #------------------------------------------------------------------------- |
|
2182 | 2192 | # Things related to text completion |
|
2183 | 2193 | #------------------------------------------------------------------------- |
|
2184 | 2194 | |
|
2185 | 2195 | def init_completer(self): |
|
2186 | 2196 | """Initialize the completion machinery. |
|
2187 | 2197 | |
|
2188 | 2198 | This creates completion machinery that can be used by client code, |
|
2189 | 2199 | either interactively in-process (typically triggered by the readline |
|
2190 | 2200 | library), programmatically (such as in test suites) or out-of-process |
|
2191 | 2201 | (typically over the network by remote frontends). |
|
2192 | 2202 | """ |
|
2193 | 2203 | from IPython.core.completer import IPCompleter |
|
2194 | 2204 | from IPython.core.completerlib import (module_completer, |
|
2195 | 2205 | magic_run_completer, cd_completer, reset_completer) |
|
2196 | 2206 | |
|
2197 | 2207 | self.Completer = IPCompleter(shell=self, |
|
2198 | 2208 | namespace=self.user_ns, |
|
2199 | 2209 | global_namespace=self.user_global_ns, |
|
2200 | 2210 | parent=self, |
|
2201 | 2211 | ) |
|
2202 | 2212 | self.configurables.append(self.Completer) |
|
2203 | 2213 | |
|
2204 | 2214 | # Add custom completers to the basic ones built into IPCompleter |
|
2205 | 2215 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) |
|
2206 | 2216 | self.strdispatchers['complete_command'] = sdisp |
|
2207 | 2217 | self.Completer.custom_completers = sdisp |
|
2208 | 2218 | |
|
2209 | 2219 | self.set_hook('complete_command', module_completer, str_key = 'import') |
|
2210 | 2220 | self.set_hook('complete_command', module_completer, str_key = 'from') |
|
2211 | 2221 | self.set_hook('complete_command', module_completer, str_key = '%aimport') |
|
2212 | 2222 | self.set_hook('complete_command', magic_run_completer, str_key = '%run') |
|
2213 | 2223 | self.set_hook('complete_command', cd_completer, str_key = '%cd') |
|
2214 | 2224 | self.set_hook('complete_command', reset_completer, str_key = '%reset') |
|
2215 | 2225 | |
|
2216 | 2226 | @skip_doctest |
|
2217 | 2227 | def complete(self, text, line=None, cursor_pos=None): |
|
2218 | 2228 | """Return the completed text and a list of completions. |
|
2219 | 2229 | |
|
2220 | 2230 | Parameters |
|
2221 | 2231 | ---------- |
|
2222 | 2232 | |
|
2223 | 2233 | text : string |
|
2224 | 2234 | A string of text to be completed on. It can be given as empty and |
|
2225 | 2235 | instead a line/position pair are given. In this case, the |
|
2226 | 2236 | completer itself will split the line like readline does. |
|
2227 | 2237 | |
|
2228 | 2238 | line : string, optional |
|
2229 | 2239 | The complete line that text is part of. |
|
2230 | 2240 | |
|
2231 | 2241 | cursor_pos : int, optional |
|
2232 | 2242 | The position of the cursor on the input line. |
|
2233 | 2243 | |
|
2234 | 2244 | Returns |
|
2235 | 2245 | ------- |
|
2236 | 2246 | text : string |
|
2237 | 2247 | The actual text that was completed. |
|
2238 | 2248 | |
|
2239 | 2249 | matches : list |
|
2240 | 2250 | A sorted list with all possible completions. |
|
2241 | 2251 | |
|
2242 | 2252 | The optional arguments allow the completion to take more context into |
|
2243 | 2253 | account, and are part of the low-level completion API. |
|
2244 | 2254 | |
|
2245 | 2255 | This is a wrapper around the completion mechanism, similar to what |
|
2246 | 2256 | readline does at the command line when the TAB key is hit. By |
|
2247 | 2257 | exposing it as a method, it can be used by other non-readline |
|
2248 | 2258 | environments (such as GUIs) for text completion. |
|
2249 | 2259 | |
|
2250 | 2260 | Simple usage example: |
|
2251 | 2261 | |
|
2252 | 2262 | In [1]: x = 'hello' |
|
2253 | 2263 | |
|
2254 | 2264 | In [2]: _ip.complete('x.l') |
|
2255 | 2265 | Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip']) |
|
2256 | 2266 | """ |
|
2257 | 2267 | |
|
2258 | 2268 | # Inject names into __builtin__ so we can complete on the added names. |
|
2259 | 2269 | with self.builtin_trap: |
|
2260 | 2270 | return self.Completer.complete(text, line, cursor_pos) |
|
2261 | 2271 | |
|
2262 | 2272 | def set_custom_completer(self, completer, pos=0) -> None: |
|
2263 | 2273 | """Adds a new custom completer function. |
|
2264 | 2274 | |
|
2265 | 2275 | The position argument (defaults to 0) is the index in the completers |
|
2266 | 2276 | list where you want the completer to be inserted. |
|
2267 | 2277 | |
|
2268 | 2278 | `completer` should have the following signature:: |
|
2269 | 2279 | |
|
2270 | 2280 | def completion(self: Completer, text: string) -> List[str]: |
|
2271 | 2281 | raise NotImplementedError |
|
2272 | 2282 | |
|
2273 | 2283 | It will be bound to the current Completer instance and pass some text |
|
2274 | 2284 | and return a list with current completions to suggest to the user. |
|
2275 | 2285 | """ |
|
2276 | 2286 | |
|
2277 | 2287 | newcomp = types.MethodType(completer, self.Completer) |
|
2278 | 2288 | self.Completer.custom_matchers.insert(pos,newcomp) |
|
2279 | 2289 | |
|
2280 | 2290 | def set_completer_frame(self, frame=None): |
|
2281 | 2291 | """Set the frame of the completer.""" |
|
2282 | 2292 | if frame: |
|
2283 | 2293 | self.Completer.namespace = frame.f_locals |
|
2284 | 2294 | self.Completer.global_namespace = frame.f_globals |
|
2285 | 2295 | else: |
|
2286 | 2296 | self.Completer.namespace = self.user_ns |
|
2287 | 2297 | self.Completer.global_namespace = self.user_global_ns |
|
2288 | 2298 | |
|
2289 | 2299 | #------------------------------------------------------------------------- |
|
2290 | 2300 | # Things related to magics |
|
2291 | 2301 | #------------------------------------------------------------------------- |
|
2292 | 2302 | |
|
2293 | 2303 | def init_magics(self): |
|
2294 | 2304 | from IPython.core import magics as m |
|
2295 | 2305 | self.magics_manager = magic.MagicsManager(shell=self, |
|
2296 | 2306 | parent=self, |
|
2297 | 2307 | user_magics=m.UserMagics(self)) |
|
2298 | 2308 | self.configurables.append(self.magics_manager) |
|
2299 | 2309 | |
|
2300 | 2310 | # Expose as public API from the magics manager |
|
2301 | 2311 | self.register_magics = self.magics_manager.register |
|
2302 | 2312 | |
|
2303 | 2313 | self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics, |
|
2304 | 2314 | m.ConfigMagics, m.DisplayMagics, m.ExecutionMagics, |
|
2305 | 2315 | m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics, |
|
2306 | 2316 | m.NamespaceMagics, m.OSMagics, m.PackagingMagics, |
|
2307 | 2317 | m.PylabMagics, m.ScriptMagics, |
|
2308 | 2318 | ) |
|
2309 | 2319 | self.register_magics(m.AsyncMagics) |
|
2310 | 2320 | |
|
2311 | 2321 | # Register Magic Aliases |
|
2312 | 2322 | mman = self.magics_manager |
|
2313 | 2323 | # FIXME: magic aliases should be defined by the Magics classes |
|
2314 | 2324 | # or in MagicsManager, not here |
|
2315 | 2325 | mman.register_alias('ed', 'edit') |
|
2316 | 2326 | mman.register_alias('hist', 'history') |
|
2317 | 2327 | mman.register_alias('rep', 'recall') |
|
2318 | 2328 | mman.register_alias('SVG', 'svg', 'cell') |
|
2319 | 2329 | mman.register_alias('HTML', 'html', 'cell') |
|
2320 | 2330 | mman.register_alias('file', 'writefile', 'cell') |
|
2321 | 2331 | |
|
2322 | 2332 | # FIXME: Move the color initialization to the DisplayHook, which |
|
2323 | 2333 | # should be split into a prompt manager and displayhook. We probably |
|
2324 | 2334 | # even need a centralize colors management object. |
|
2325 | 2335 | self.run_line_magic('colors', self.colors) |
|
2326 | 2336 | |
|
2327 | 2337 | # Defined here so that it's included in the documentation |
|
2328 | 2338 | @functools.wraps(magic.MagicsManager.register_function) |
|
2329 | 2339 | def register_magic_function(self, func, magic_kind='line', magic_name=None): |
|
2330 | 2340 | self.magics_manager.register_function( |
|
2331 | 2341 | func, magic_kind=magic_kind, magic_name=magic_name |
|
2332 | 2342 | ) |
|
2333 | 2343 | |
|
2334 | 2344 | def _find_with_lazy_load(self, type_, magic_name: str): |
|
2335 | 2345 | """ |
|
2336 | 2346 | Try to find a magic potentially lazy-loading it. |
|
2337 | 2347 | |
|
2338 | 2348 | Parameters |
|
2339 | 2349 | ---------- |
|
2340 | 2350 | |
|
2341 | 2351 | type_: "line"|"cell" |
|
2342 | 2352 | the type of magics we are trying to find/lazy load. |
|
2343 | 2353 | magic_name: str |
|
2344 | 2354 | The name of the magic we are trying to find/lazy load |
|
2345 | 2355 | |
|
2346 | 2356 | |
|
2347 | 2357 | Note that this may have any side effects |
|
2348 | 2358 | """ |
|
2349 | 2359 | finder = {"line": self.find_line_magic, "cell": self.find_cell_magic}[type_] |
|
2350 | 2360 | fn = finder(magic_name) |
|
2351 | 2361 | if fn is not None: |
|
2352 | 2362 | return fn |
|
2353 | 2363 | lazy = self.magics_manager.lazy_magics.get(magic_name) |
|
2354 | 2364 | if lazy is None: |
|
2355 | 2365 | return None |
|
2356 | 2366 | |
|
2357 | 2367 | self.run_line_magic("load_ext", lazy) |
|
2358 | 2368 | res = finder(magic_name) |
|
2359 | 2369 | return res |
|
2360 | 2370 | |
|
2361 | 2371 | def run_line_magic(self, magic_name: str, line, _stack_depth=1): |
|
2362 | 2372 | """Execute the given line magic. |
|
2363 | 2373 | |
|
2364 | 2374 | Parameters |
|
2365 | 2375 | ---------- |
|
2366 | 2376 | magic_name : str |
|
2367 | 2377 | Name of the desired magic function, without '%' prefix. |
|
2368 | 2378 | |
|
2369 | 2379 | line : str |
|
2370 | 2380 | The rest of the input line as a single string. |
|
2371 | 2381 | |
|
2372 | 2382 | _stack_depth : int |
|
2373 | 2383 | If run_line_magic() is called from magic() then _stack_depth=2. |
|
2374 | 2384 | This is added to ensure backward compatibility for use of 'get_ipython().magic()' |
|
2375 | 2385 | """ |
|
2376 | 2386 | fn = self._find_with_lazy_load("line", magic_name) |
|
2377 | 2387 | if fn is None: |
|
2378 | 2388 | lazy = self.magics_manager.lazy_magics.get(magic_name) |
|
2379 | 2389 | if lazy: |
|
2380 | 2390 | self.run_line_magic("load_ext", lazy) |
|
2381 | 2391 | fn = self.find_line_magic(magic_name) |
|
2382 | 2392 | if fn is None: |
|
2383 | 2393 | cm = self.find_cell_magic(magic_name) |
|
2384 | 2394 | etpl = "Line magic function `%%%s` not found%s." |
|
2385 | 2395 | extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, ' |
|
2386 | 2396 | 'did you mean that instead?)' % magic_name ) |
|
2387 | 2397 | raise UsageError(etpl % (magic_name, extra)) |
|
2388 | 2398 | else: |
|
2389 | 2399 | # Note: this is the distance in the stack to the user's frame. |
|
2390 | 2400 | # This will need to be updated if the internal calling logic gets |
|
2391 | 2401 | # refactored, or else we'll be expanding the wrong variables. |
|
2392 | 2402 | |
|
2393 | 2403 | # Determine stack_depth depending on where run_line_magic() has been called |
|
2394 | 2404 | stack_depth = _stack_depth |
|
2395 | 2405 | if getattr(fn, magic.MAGIC_NO_VAR_EXPAND_ATTR, False): |
|
2396 | 2406 | # magic has opted out of var_expand |
|
2397 | 2407 | magic_arg_s = line |
|
2398 | 2408 | else: |
|
2399 | 2409 | magic_arg_s = self.var_expand(line, stack_depth) |
|
2400 | 2410 | # Put magic args in a list so we can call with f(*a) syntax |
|
2401 | 2411 | args = [magic_arg_s] |
|
2402 | 2412 | kwargs = {} |
|
2403 | 2413 | # Grab local namespace if we need it: |
|
2404 | 2414 | if getattr(fn, "needs_local_scope", False): |
|
2405 | 2415 | kwargs['local_ns'] = self.get_local_scope(stack_depth) |
|
2406 | 2416 | with self.builtin_trap: |
|
2407 | 2417 | result = fn(*args, **kwargs) |
|
2408 | 2418 | return result |
|
2409 | 2419 | |
|
2410 | 2420 | def get_local_scope(self, stack_depth): |
|
2411 | 2421 | """Get local scope at given stack depth. |
|
2412 | 2422 | |
|
2413 | 2423 | Parameters |
|
2414 | 2424 | ---------- |
|
2415 | 2425 | stack_depth : int |
|
2416 | 2426 | Depth relative to calling frame |
|
2417 | 2427 | """ |
|
2418 | 2428 | return sys._getframe(stack_depth + 1).f_locals |
|
2419 | 2429 | |
|
2420 | 2430 | def run_cell_magic(self, magic_name, line, cell): |
|
2421 | 2431 | """Execute the given cell magic. |
|
2422 | 2432 | |
|
2423 | 2433 | Parameters |
|
2424 | 2434 | ---------- |
|
2425 | 2435 | magic_name : str |
|
2426 | 2436 | Name of the desired magic function, without '%' prefix. |
|
2427 | 2437 | |
|
2428 | 2438 | line : str |
|
2429 | 2439 | The rest of the first input line as a single string. |
|
2430 | 2440 | |
|
2431 | 2441 | cell : str |
|
2432 | 2442 | The body of the cell as a (possibly multiline) string. |
|
2433 | 2443 | """ |
|
2434 | 2444 | fn = self._find_with_lazy_load("cell", magic_name) |
|
2435 | 2445 | if fn is None: |
|
2436 | 2446 | lm = self.find_line_magic(magic_name) |
|
2437 | 2447 | etpl = "Cell magic `%%{0}` not found{1}." |
|
2438 | 2448 | extra = '' if lm is None else (' (But line magic `%{0}` exists, ' |
|
2439 | 2449 | 'did you mean that instead?)'.format(magic_name)) |
|
2440 | 2450 | raise UsageError(etpl.format(magic_name, extra)) |
|
2441 | 2451 | elif cell == '': |
|
2442 | 2452 | message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name) |
|
2443 | 2453 | if self.find_line_magic(magic_name) is not None: |
|
2444 | 2454 | message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name) |
|
2445 | 2455 | raise UsageError(message) |
|
2446 | 2456 | else: |
|
2447 | 2457 | # Note: this is the distance in the stack to the user's frame. |
|
2448 | 2458 | # This will need to be updated if the internal calling logic gets |
|
2449 | 2459 | # refactored, or else we'll be expanding the wrong variables. |
|
2450 | 2460 | stack_depth = 2 |
|
2451 | 2461 | if getattr(fn, magic.MAGIC_NO_VAR_EXPAND_ATTR, False): |
|
2452 | 2462 | # magic has opted out of var_expand |
|
2453 | 2463 | magic_arg_s = line |
|
2454 | 2464 | else: |
|
2455 | 2465 | magic_arg_s = self.var_expand(line, stack_depth) |
|
2456 | 2466 | kwargs = {} |
|
2457 | 2467 | if getattr(fn, "needs_local_scope", False): |
|
2458 | 2468 | kwargs['local_ns'] = self.user_ns |
|
2459 | 2469 | |
|
2460 | 2470 | with self.builtin_trap: |
|
2461 | 2471 | args = (magic_arg_s, cell) |
|
2462 | 2472 | result = fn(*args, **kwargs) |
|
2463 | 2473 | return result |
|
2464 | 2474 | |
|
2465 | 2475 | def find_line_magic(self, magic_name): |
|
2466 | 2476 | """Find and return a line magic by name. |
|
2467 | 2477 | |
|
2468 | 2478 | Returns None if the magic isn't found.""" |
|
2469 | 2479 | return self.magics_manager.magics['line'].get(magic_name) |
|
2470 | 2480 | |
|
2471 | 2481 | def find_cell_magic(self, magic_name): |
|
2472 | 2482 | """Find and return a cell magic by name. |
|
2473 | 2483 | |
|
2474 | 2484 | Returns None if the magic isn't found.""" |
|
2475 | 2485 | return self.magics_manager.magics['cell'].get(magic_name) |
|
2476 | 2486 | |
|
2477 | 2487 | def find_magic(self, magic_name, magic_kind='line'): |
|
2478 | 2488 | """Find and return a magic of the given type by name. |
|
2479 | 2489 | |
|
2480 | 2490 | Returns None if the magic isn't found.""" |
|
2481 | 2491 | return self.magics_manager.magics[magic_kind].get(magic_name) |
|
2482 | 2492 | |
|
2483 | 2493 | def magic(self, arg_s): |
|
2484 | 2494 | """DEPRECATED. Use run_line_magic() instead. |
|
2485 | 2495 | |
|
2486 | 2496 | Call a magic function by name. |
|
2487 | 2497 | |
|
2488 | 2498 | Input: a string containing the name of the magic function to call and |
|
2489 | 2499 | any additional arguments to be passed to the magic. |
|
2490 | 2500 | |
|
2491 | 2501 | magic('name -opt foo bar') is equivalent to typing at the ipython |
|
2492 | 2502 | prompt: |
|
2493 | 2503 | |
|
2494 | 2504 | In[1]: %name -opt foo bar |
|
2495 | 2505 | |
|
2496 | 2506 | To call a magic without arguments, simply use magic('name'). |
|
2497 | 2507 | |
|
2498 | 2508 | This provides a proper Python function to call IPython's magics in any |
|
2499 | 2509 | valid Python code you can type at the interpreter, including loops and |
|
2500 | 2510 | compound statements. |
|
2501 | 2511 | """ |
|
2502 | 2512 | # TODO: should we issue a loud deprecation warning here? |
|
2503 | 2513 | magic_name, _, magic_arg_s = arg_s.partition(' ') |
|
2504 | 2514 | magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) |
|
2505 | 2515 | return self.run_line_magic(magic_name, magic_arg_s, _stack_depth=2) |
|
2506 | 2516 | |
|
2507 | 2517 | #------------------------------------------------------------------------- |
|
2508 | 2518 | # Things related to macros |
|
2509 | 2519 | #------------------------------------------------------------------------- |
|
2510 | 2520 | |
|
2511 | 2521 | def define_macro(self, name, themacro): |
|
2512 | 2522 | """Define a new macro |
|
2513 | 2523 | |
|
2514 | 2524 | Parameters |
|
2515 | 2525 | ---------- |
|
2516 | 2526 | name : str |
|
2517 | 2527 | The name of the macro. |
|
2518 | 2528 | themacro : str or Macro |
|
2519 | 2529 | The action to do upon invoking the macro. If a string, a new |
|
2520 | 2530 | Macro object is created by passing the string to it. |
|
2521 | 2531 | """ |
|
2522 | 2532 | |
|
2523 | 2533 | from IPython.core import macro |
|
2524 | 2534 | |
|
2525 | 2535 | if isinstance(themacro, str): |
|
2526 | 2536 | themacro = macro.Macro(themacro) |
|
2527 | 2537 | if not isinstance(themacro, macro.Macro): |
|
2528 | 2538 | raise ValueError('A macro must be a string or a Macro instance.') |
|
2529 | 2539 | self.user_ns[name] = themacro |
|
2530 | 2540 | |
|
2531 | 2541 | #------------------------------------------------------------------------- |
|
2532 | 2542 | # Things related to the running of system commands |
|
2533 | 2543 | #------------------------------------------------------------------------- |
|
2534 | 2544 | |
|
2535 | 2545 | def system_piped(self, cmd): |
|
2536 | 2546 | """Call the given cmd in a subprocess, piping stdout/err |
|
2537 | 2547 | |
|
2538 | 2548 | Parameters |
|
2539 | 2549 | ---------- |
|
2540 | 2550 | cmd : str |
|
2541 | 2551 | Command to execute (can not end in '&', as background processes are |
|
2542 | 2552 | not supported. Should not be a command that expects input |
|
2543 | 2553 | other than simple text. |
|
2544 | 2554 | """ |
|
2545 | 2555 | if cmd.rstrip().endswith('&'): |
|
2546 | 2556 | # this is *far* from a rigorous test |
|
2547 | 2557 | # We do not support backgrounding processes because we either use |
|
2548 | 2558 | # pexpect or pipes to read from. Users can always just call |
|
2549 | 2559 | # os.system() or use ip.system=ip.system_raw |
|
2550 | 2560 | # if they really want a background process. |
|
2551 | 2561 | raise OSError("Background processes not supported.") |
|
2552 | 2562 | |
|
2553 | 2563 | # we explicitly do NOT return the subprocess status code, because |
|
2554 | 2564 | # a non-None value would trigger :func:`sys.displayhook` calls. |
|
2555 | 2565 | # Instead, we store the exit_code in user_ns. |
|
2556 | 2566 | self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1)) |
|
2557 | 2567 | |
|
2558 | 2568 | def system_raw(self, cmd): |
|
2559 | 2569 | """Call the given cmd in a subprocess using os.system on Windows or |
|
2560 | 2570 | subprocess.call using the system shell on other platforms. |
|
2561 | 2571 | |
|
2562 | 2572 | Parameters |
|
2563 | 2573 | ---------- |
|
2564 | 2574 | cmd : str |
|
2565 | 2575 | Command to execute. |
|
2566 | 2576 | """ |
|
2567 | 2577 | cmd = self.var_expand(cmd, depth=1) |
|
2568 | 2578 | # protect os.system from UNC paths on Windows, which it can't handle: |
|
2569 | 2579 | if sys.platform == 'win32': |
|
2570 | 2580 | from IPython.utils._process_win32 import AvoidUNCPath |
|
2571 | 2581 | with AvoidUNCPath() as path: |
|
2572 | 2582 | if path is not None: |
|
2573 | 2583 | cmd = '"pushd %s &&"%s' % (path, cmd) |
|
2574 | 2584 | try: |
|
2575 | 2585 | ec = os.system(cmd) |
|
2576 | 2586 | except KeyboardInterrupt: |
|
2577 | 2587 | print('\n' + self.get_exception_only(), file=sys.stderr) |
|
2578 | 2588 | ec = -2 |
|
2579 | 2589 | else: |
|
2580 | 2590 | # For posix the result of the subprocess.call() below is an exit |
|
2581 | 2591 | # code, which by convention is zero for success, positive for |
|
2582 | 2592 | # program failure. Exit codes above 128 are reserved for signals, |
|
2583 | 2593 | # and the formula for converting a signal to an exit code is usually |
|
2584 | 2594 | # signal_number+128. To more easily differentiate between exit |
|
2585 | 2595 | # codes and signals, ipython uses negative numbers. For instance |
|
2586 | 2596 | # since control-c is signal 2 but exit code 130, ipython's |
|
2587 | 2597 | # _exit_code variable will read -2. Note that some shells like |
|
2588 | 2598 | # csh and fish don't follow sh/bash conventions for exit codes. |
|
2589 | 2599 | executable = os.environ.get('SHELL', None) |
|
2590 | 2600 | try: |
|
2591 | 2601 | # Use env shell instead of default /bin/sh |
|
2592 | 2602 | ec = subprocess.call(cmd, shell=True, executable=executable) |
|
2593 | 2603 | except KeyboardInterrupt: |
|
2594 | 2604 | # intercept control-C; a long traceback is not useful here |
|
2595 | 2605 | print('\n' + self.get_exception_only(), file=sys.stderr) |
|
2596 | 2606 | ec = 130 |
|
2597 | 2607 | if ec > 128: |
|
2598 | 2608 | ec = -(ec - 128) |
|
2599 | 2609 | |
|
2600 | 2610 | # We explicitly do NOT return the subprocess status code, because |
|
2601 | 2611 | # a non-None value would trigger :func:`sys.displayhook` calls. |
|
2602 | 2612 | # Instead, we store the exit_code in user_ns. Note the semantics |
|
2603 | 2613 | # of _exit_code: for control-c, _exit_code == -signal.SIGNIT, |
|
2604 | 2614 | # but raising SystemExit(_exit_code) will give status 254! |
|
2605 | 2615 | self.user_ns['_exit_code'] = ec |
|
2606 | 2616 | |
|
2607 | 2617 | # use piped system by default, because it is better behaved |
|
2608 | 2618 | system = system_piped |
|
2609 | 2619 | |
|
2610 | 2620 | def getoutput(self, cmd, split=True, depth=0): |
|
2611 | 2621 | """Get output (possibly including stderr) from a subprocess. |
|
2612 | 2622 | |
|
2613 | 2623 | Parameters |
|
2614 | 2624 | ---------- |
|
2615 | 2625 | cmd : str |
|
2616 | 2626 | Command to execute (can not end in '&', as background processes are |
|
2617 | 2627 | not supported. |
|
2618 | 2628 | split : bool, optional |
|
2619 | 2629 | If True, split the output into an IPython SList. Otherwise, an |
|
2620 | 2630 | IPython LSString is returned. These are objects similar to normal |
|
2621 | 2631 | lists and strings, with a few convenience attributes for easier |
|
2622 | 2632 | manipulation of line-based output. You can use '?' on them for |
|
2623 | 2633 | details. |
|
2624 | 2634 | depth : int, optional |
|
2625 | 2635 | How many frames above the caller are the local variables which should |
|
2626 | 2636 | be expanded in the command string? The default (0) assumes that the |
|
2627 | 2637 | expansion variables are in the stack frame calling this function. |
|
2628 | 2638 | """ |
|
2629 | 2639 | if cmd.rstrip().endswith('&'): |
|
2630 | 2640 | # this is *far* from a rigorous test |
|
2631 | 2641 | raise OSError("Background processes not supported.") |
|
2632 | 2642 | out = getoutput(self.var_expand(cmd, depth=depth+1)) |
|
2633 | 2643 | if split: |
|
2634 | 2644 | out = SList(out.splitlines()) |
|
2635 | 2645 | else: |
|
2636 | 2646 | out = LSString(out) |
|
2637 | 2647 | return out |
|
2638 | 2648 | |
|
2639 | 2649 | #------------------------------------------------------------------------- |
|
2640 | 2650 | # Things related to aliases |
|
2641 | 2651 | #------------------------------------------------------------------------- |
|
2642 | 2652 | |
|
2643 | 2653 | def init_alias(self): |
|
2644 | 2654 | self.alias_manager = AliasManager(shell=self, parent=self) |
|
2645 | 2655 | self.configurables.append(self.alias_manager) |
|
2646 | 2656 | |
|
2647 | 2657 | #------------------------------------------------------------------------- |
|
2648 | 2658 | # Things related to extensions |
|
2649 | 2659 | #------------------------------------------------------------------------- |
|
2650 | 2660 | |
|
2651 | 2661 | def init_extension_manager(self): |
|
2652 | 2662 | self.extension_manager = ExtensionManager(shell=self, parent=self) |
|
2653 | 2663 | self.configurables.append(self.extension_manager) |
|
2654 | 2664 | |
|
2655 | 2665 | #------------------------------------------------------------------------- |
|
2656 | 2666 | # Things related to payloads |
|
2657 | 2667 | #------------------------------------------------------------------------- |
|
2658 | 2668 | |
|
2659 | 2669 | def init_payload(self): |
|
2660 | 2670 | self.payload_manager = PayloadManager(parent=self) |
|
2661 | 2671 | self.configurables.append(self.payload_manager) |
|
2662 | 2672 | |
|
2663 | 2673 | #------------------------------------------------------------------------- |
|
2664 | 2674 | # Things related to the prefilter |
|
2665 | 2675 | #------------------------------------------------------------------------- |
|
2666 | 2676 | |
|
2667 | 2677 | def init_prefilter(self): |
|
2668 | 2678 | self.prefilter_manager = PrefilterManager(shell=self, parent=self) |
|
2669 | 2679 | self.configurables.append(self.prefilter_manager) |
|
2670 | 2680 | # Ultimately this will be refactored in the new interpreter code, but |
|
2671 | 2681 | # for now, we should expose the main prefilter method (there's legacy |
|
2672 | 2682 | # code out there that may rely on this). |
|
2673 | 2683 | self.prefilter = self.prefilter_manager.prefilter_lines |
|
2674 | 2684 | |
|
2675 | 2685 | def auto_rewrite_input(self, cmd): |
|
2676 | 2686 | """Print to the screen the rewritten form of the user's command. |
|
2677 | 2687 | |
|
2678 | 2688 | This shows visual feedback by rewriting input lines that cause |
|
2679 | 2689 | automatic calling to kick in, like:: |
|
2680 | 2690 | |
|
2681 | 2691 | /f x |
|
2682 | 2692 | |
|
2683 | 2693 | into:: |
|
2684 | 2694 | |
|
2685 | 2695 | ------> f(x) |
|
2686 | 2696 | |
|
2687 | 2697 | after the user's input prompt. This helps the user understand that the |
|
2688 | 2698 | input line was transformed automatically by IPython. |
|
2689 | 2699 | """ |
|
2690 | 2700 | if not self.show_rewritten_input: |
|
2691 | 2701 | return |
|
2692 | 2702 | |
|
2693 | 2703 | # This is overridden in TerminalInteractiveShell to use fancy prompts |
|
2694 | 2704 | print("------> " + cmd) |
|
2695 | 2705 | |
|
2696 | 2706 | #------------------------------------------------------------------------- |
|
2697 | 2707 | # Things related to extracting values/expressions from kernel and user_ns |
|
2698 | 2708 | #------------------------------------------------------------------------- |
|
2699 | 2709 | |
|
2700 | 2710 | def _user_obj_error(self): |
|
2701 | 2711 | """return simple exception dict |
|
2702 | 2712 | |
|
2703 | 2713 | for use in user_expressions |
|
2704 | 2714 | """ |
|
2705 | 2715 | |
|
2706 | 2716 | etype, evalue, tb = self._get_exc_info() |
|
2707 | 2717 | stb = self.InteractiveTB.get_exception_only(etype, evalue) |
|
2708 | 2718 | |
|
2709 | 2719 | exc_info = { |
|
2710 | 2720 | u'status' : 'error', |
|
2711 | 2721 | u'traceback' : stb, |
|
2712 | 2722 | u'ename' : etype.__name__, |
|
2713 | 2723 | u'evalue' : py3compat.safe_unicode(evalue), |
|
2714 | 2724 | } |
|
2715 | 2725 | |
|
2716 | 2726 | return exc_info |
|
2717 | 2727 | |
|
2718 | 2728 | def _format_user_obj(self, obj): |
|
2719 | 2729 | """format a user object to display dict |
|
2720 | 2730 | |
|
2721 | 2731 | for use in user_expressions |
|
2722 | 2732 | """ |
|
2723 | 2733 | |
|
2724 | 2734 | data, md = self.display_formatter.format(obj) |
|
2725 | 2735 | value = { |
|
2726 | 2736 | 'status' : 'ok', |
|
2727 | 2737 | 'data' : data, |
|
2728 | 2738 | 'metadata' : md, |
|
2729 | 2739 | } |
|
2730 | 2740 | return value |
|
2731 | 2741 | |
|
2732 | 2742 | def user_expressions(self, expressions): |
|
2733 | 2743 | """Evaluate a dict of expressions in the user's namespace. |
|
2734 | 2744 | |
|
2735 | 2745 | Parameters |
|
2736 | 2746 | ---------- |
|
2737 | 2747 | expressions : dict |
|
2738 | 2748 | A dict with string keys and string values. The expression values |
|
2739 | 2749 | should be valid Python expressions, each of which will be evaluated |
|
2740 | 2750 | in the user namespace. |
|
2741 | 2751 | |
|
2742 | 2752 | Returns |
|
2743 | 2753 | ------- |
|
2744 | 2754 | A dict, keyed like the input expressions dict, with the rich mime-typed |
|
2745 | 2755 | display_data of each value. |
|
2746 | 2756 | """ |
|
2747 | 2757 | out = {} |
|
2748 | 2758 | user_ns = self.user_ns |
|
2749 | 2759 | global_ns = self.user_global_ns |
|
2750 | 2760 | |
|
2751 | 2761 | for key, expr in expressions.items(): |
|
2752 | 2762 | try: |
|
2753 | 2763 | value = self._format_user_obj(eval(expr, global_ns, user_ns)) |
|
2754 | 2764 | except: |
|
2755 | 2765 | value = self._user_obj_error() |
|
2756 | 2766 | out[key] = value |
|
2757 | 2767 | return out |
|
2758 | 2768 | |
|
2759 | 2769 | #------------------------------------------------------------------------- |
|
2760 | 2770 | # Things related to the running of code |
|
2761 | 2771 | #------------------------------------------------------------------------- |
|
2762 | 2772 | |
|
2763 | 2773 | def ex(self, cmd): |
|
2764 | 2774 | """Execute a normal python statement in user namespace.""" |
|
2765 | 2775 | with self.builtin_trap: |
|
2766 | 2776 | exec(cmd, self.user_global_ns, self.user_ns) |
|
2767 | 2777 | |
|
2768 | 2778 | def ev(self, expr): |
|
2769 | 2779 | """Evaluate python expression expr in user namespace. |
|
2770 | 2780 | |
|
2771 | 2781 | Returns the result of evaluation |
|
2772 | 2782 | """ |
|
2773 | 2783 | with self.builtin_trap: |
|
2774 | 2784 | return eval(expr, self.user_global_ns, self.user_ns) |
|
2775 | 2785 | |
|
2776 | 2786 | def safe_execfile(self, fname, *where, exit_ignore=False, raise_exceptions=False, shell_futures=False): |
|
2777 | 2787 | """A safe version of the builtin execfile(). |
|
2778 | 2788 | |
|
2779 | 2789 | This version will never throw an exception, but instead print |
|
2780 | 2790 | helpful error messages to the screen. This only works on pure |
|
2781 | 2791 | Python files with the .py extension. |
|
2782 | 2792 | |
|
2783 | 2793 | Parameters |
|
2784 | 2794 | ---------- |
|
2785 | 2795 | fname : string |
|
2786 | 2796 | The name of the file to be executed. |
|
2787 | 2797 | where : tuple |
|
2788 | 2798 | One or two namespaces, passed to execfile() as (globals,locals). |
|
2789 | 2799 | If only one is given, it is passed as both. |
|
2790 | 2800 | exit_ignore : bool (False) |
|
2791 | 2801 | If True, then silence SystemExit for non-zero status (it is always |
|
2792 | 2802 | silenced for zero status, as it is so common). |
|
2793 | 2803 | raise_exceptions : bool (False) |
|
2794 | 2804 | If True raise exceptions everywhere. Meant for testing. |
|
2795 | 2805 | shell_futures : bool (False) |
|
2796 | 2806 | If True, the code will share future statements with the interactive |
|
2797 | 2807 | shell. It will both be affected by previous __future__ imports, and |
|
2798 | 2808 | any __future__ imports in the code will affect the shell. If False, |
|
2799 | 2809 | __future__ imports are not shared in either direction. |
|
2800 | 2810 | |
|
2801 | 2811 | """ |
|
2802 | 2812 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
2803 | 2813 | |
|
2804 | 2814 | # Make sure we can open the file |
|
2805 | 2815 | try: |
|
2806 | 2816 | with open(fname): |
|
2807 | 2817 | pass |
|
2808 | 2818 | except: |
|
2809 | 2819 | warn('Could not open file <%s> for safe execution.' % fname) |
|
2810 | 2820 | return |
|
2811 | 2821 | |
|
2812 | 2822 | # Find things also in current directory. This is needed to mimic the |
|
2813 | 2823 | # behavior of running a script from the system command line, where |
|
2814 | 2824 | # Python inserts the script's directory into sys.path |
|
2815 | 2825 | dname = os.path.dirname(fname) |
|
2816 | 2826 | |
|
2817 | 2827 | with prepended_to_syspath(dname), self.builtin_trap: |
|
2818 | 2828 | try: |
|
2819 | 2829 | glob, loc = (where + (None, ))[:2] |
|
2820 | 2830 | py3compat.execfile( |
|
2821 | 2831 | fname, glob, loc, |
|
2822 | 2832 | self.compile if shell_futures else None) |
|
2823 | 2833 | except SystemExit as status: |
|
2824 | 2834 | # If the call was made with 0 or None exit status (sys.exit(0) |
|
2825 | 2835 | # or sys.exit() ), don't bother showing a traceback, as both of |
|
2826 | 2836 | # these are considered normal by the OS: |
|
2827 | 2837 | # > python -c'import sys;sys.exit(0)'; echo $? |
|
2828 | 2838 | # 0 |
|
2829 | 2839 | # > python -c'import sys;sys.exit()'; echo $? |
|
2830 | 2840 | # 0 |
|
2831 | 2841 | # For other exit status, we show the exception unless |
|
2832 | 2842 | # explicitly silenced, but only in short form. |
|
2833 | 2843 | if status.code: |
|
2834 | 2844 | if raise_exceptions: |
|
2835 | 2845 | raise |
|
2836 | 2846 | if not exit_ignore: |
|
2837 | 2847 | self.showtraceback(exception_only=True) |
|
2838 | 2848 | except: |
|
2839 | 2849 | if raise_exceptions: |
|
2840 | 2850 | raise |
|
2841 | 2851 | # tb offset is 2 because we wrap execfile |
|
2842 | 2852 | self.showtraceback(tb_offset=2) |
|
2843 | 2853 | |
|
2844 | 2854 | def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False): |
|
2845 | 2855 | """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax. |
|
2846 | 2856 | |
|
2847 | 2857 | Parameters |
|
2848 | 2858 | ---------- |
|
2849 | 2859 | fname : str |
|
2850 | 2860 | The name of the file to execute. The filename must have a |
|
2851 | 2861 | .ipy or .ipynb extension. |
|
2852 | 2862 | shell_futures : bool (False) |
|
2853 | 2863 | If True, the code will share future statements with the interactive |
|
2854 | 2864 | shell. It will both be affected by previous __future__ imports, and |
|
2855 | 2865 | any __future__ imports in the code will affect the shell. If False, |
|
2856 | 2866 | __future__ imports are not shared in either direction. |
|
2857 | 2867 | raise_exceptions : bool (False) |
|
2858 | 2868 | If True raise exceptions everywhere. Meant for testing. |
|
2859 | 2869 | """ |
|
2860 | 2870 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
2861 | 2871 | |
|
2862 | 2872 | # Make sure we can open the file |
|
2863 | 2873 | try: |
|
2864 | 2874 | with open(fname): |
|
2865 | 2875 | pass |
|
2866 | 2876 | except: |
|
2867 | 2877 | warn('Could not open file <%s> for safe execution.' % fname) |
|
2868 | 2878 | return |
|
2869 | 2879 | |
|
2870 | 2880 | # Find things also in current directory. This is needed to mimic the |
|
2871 | 2881 | # behavior of running a script from the system command line, where |
|
2872 | 2882 | # Python inserts the script's directory into sys.path |
|
2873 | 2883 | dname = os.path.dirname(fname) |
|
2874 | 2884 | |
|
2875 | 2885 | def get_cells(): |
|
2876 | 2886 | """generator for sequence of code blocks to run""" |
|
2877 | 2887 | if fname.endswith('.ipynb'): |
|
2878 | 2888 | from nbformat import read |
|
2879 | 2889 | nb = read(fname, as_version=4) |
|
2880 | 2890 | if not nb.cells: |
|
2881 | 2891 | return |
|
2882 | 2892 | for cell in nb.cells: |
|
2883 | 2893 | if cell.cell_type == 'code': |
|
2884 | 2894 | yield cell.source |
|
2885 | 2895 | else: |
|
2886 | 2896 | with open(fname) as f: |
|
2887 | 2897 | yield f.read() |
|
2888 | 2898 | |
|
2889 | 2899 | with prepended_to_syspath(dname): |
|
2890 | 2900 | try: |
|
2891 | 2901 | for cell in get_cells(): |
|
2892 | 2902 | result = self.run_cell(cell, silent=True, shell_futures=shell_futures) |
|
2893 | 2903 | if raise_exceptions: |
|
2894 | 2904 | result.raise_error() |
|
2895 | 2905 | elif not result.success: |
|
2896 | 2906 | break |
|
2897 | 2907 | except: |
|
2898 | 2908 | if raise_exceptions: |
|
2899 | 2909 | raise |
|
2900 | 2910 | self.showtraceback() |
|
2901 | 2911 | warn('Unknown failure executing file: <%s>' % fname) |
|
2902 | 2912 | |
|
2903 | 2913 | def safe_run_module(self, mod_name, where): |
|
2904 | 2914 | """A safe version of runpy.run_module(). |
|
2905 | 2915 | |
|
2906 | 2916 | This version will never throw an exception, but instead print |
|
2907 | 2917 | helpful error messages to the screen. |
|
2908 | 2918 | |
|
2909 | 2919 | `SystemExit` exceptions with status code 0 or None are ignored. |
|
2910 | 2920 | |
|
2911 | 2921 | Parameters |
|
2912 | 2922 | ---------- |
|
2913 | 2923 | mod_name : string |
|
2914 | 2924 | The name of the module to be executed. |
|
2915 | 2925 | where : dict |
|
2916 | 2926 | The globals namespace. |
|
2917 | 2927 | """ |
|
2918 | 2928 | try: |
|
2919 | 2929 | try: |
|
2920 | 2930 | where.update( |
|
2921 | 2931 | runpy.run_module(str(mod_name), run_name="__main__", |
|
2922 | 2932 | alter_sys=True) |
|
2923 | 2933 | ) |
|
2924 | 2934 | except SystemExit as status: |
|
2925 | 2935 | if status.code: |
|
2926 | 2936 | raise |
|
2927 | 2937 | except: |
|
2928 | 2938 | self.showtraceback() |
|
2929 | 2939 | warn('Unknown failure executing module: <%s>' % mod_name) |
|
2930 | 2940 | |
|
2931 | def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True): | |
|
2941 | def run_cell( | |
|
2942 | self, | |
|
2943 | raw_cell, | |
|
2944 | store_history=False, | |
|
2945 | silent=False, | |
|
2946 | shell_futures=True, | |
|
2947 | cell_id=None, | |
|
2948 | ): | |
|
2932 | 2949 | """Run a complete IPython cell. |
|
2933 | 2950 | |
|
2934 | 2951 | Parameters |
|
2935 | 2952 | ---------- |
|
2936 | 2953 | raw_cell : str |
|
2937 | 2954 | The code (including IPython code such as %magic functions) to run. |
|
2938 | 2955 | store_history : bool |
|
2939 | 2956 | If True, the raw and translated cell will be stored in IPython's |
|
2940 | 2957 | history. For user code calling back into IPython's machinery, this |
|
2941 | 2958 | should be set to False. |
|
2942 | 2959 | silent : bool |
|
2943 | 2960 | If True, avoid side-effects, such as implicit displayhooks and |
|
2944 | 2961 | and logging. silent=True forces store_history=False. |
|
2945 | 2962 | shell_futures : bool |
|
2946 | 2963 | If True, the code will share future statements with the interactive |
|
2947 | 2964 | shell. It will both be affected by previous __future__ imports, and |
|
2948 | 2965 | any __future__ imports in the code will affect the shell. If False, |
|
2949 | 2966 | __future__ imports are not shared in either direction. |
|
2950 | 2967 | |
|
2951 | 2968 | Returns |
|
2952 | 2969 | ------- |
|
2953 | 2970 | result : :class:`ExecutionResult` |
|
2954 | 2971 | """ |
|
2955 | 2972 | result = None |
|
2956 | 2973 | try: |
|
2957 | 2974 | result = self._run_cell( |
|
2958 |
raw_cell, store_history, silent, shell_futures |
|
|
2975 | raw_cell, store_history, silent, shell_futures, cell_id | |
|
2976 | ) | |
|
2959 | 2977 | finally: |
|
2960 | 2978 | self.events.trigger('post_execute') |
|
2961 | 2979 | if not silent: |
|
2962 | 2980 | self.events.trigger('post_run_cell', result) |
|
2963 | 2981 | return result |
|
2964 | 2982 | |
|
2965 | def _run_cell(self, raw_cell:str, store_history:bool, silent:bool, shell_futures:bool): | |
|
2983 | def _run_cell( | |
|
2984 | self, | |
|
2985 | raw_cell: str, | |
|
2986 | store_history: bool, | |
|
2987 | silent: bool, | |
|
2988 | shell_futures: bool, | |
|
2989 | cell_id: str, | |
|
2990 | ) -> ExecutionResult: | |
|
2966 | 2991 | """Internal method to run a complete IPython cell.""" |
|
2967 | 2992 | |
|
2968 | 2993 | # we need to avoid calling self.transform_cell multiple time on the same thing |
|
2969 | 2994 | # so we need to store some results: |
|
2970 | 2995 | preprocessing_exc_tuple = None |
|
2971 | 2996 | try: |
|
2972 | 2997 | transformed_cell = self.transform_cell(raw_cell) |
|
2973 | 2998 | except Exception: |
|
2974 | 2999 | transformed_cell = raw_cell |
|
2975 | 3000 | preprocessing_exc_tuple = sys.exc_info() |
|
2976 | 3001 | |
|
2977 | 3002 | assert transformed_cell is not None |
|
2978 | 3003 | coro = self.run_cell_async( |
|
2979 | 3004 | raw_cell, |
|
2980 | 3005 | store_history=store_history, |
|
2981 | 3006 | silent=silent, |
|
2982 | 3007 | shell_futures=shell_futures, |
|
2983 | 3008 | transformed_cell=transformed_cell, |
|
2984 | 3009 | preprocessing_exc_tuple=preprocessing_exc_tuple, |
|
3010 | cell_id=cell_id, | |
|
2985 | 3011 | ) |
|
2986 | 3012 | |
|
2987 | 3013 | # run_cell_async is async, but may not actually need an eventloop. |
|
2988 | 3014 | # when this is the case, we want to run it using the pseudo_sync_runner |
|
2989 | 3015 | # so that code can invoke eventloops (for example via the %run , and |
|
2990 | 3016 | # `%paste` magic. |
|
2991 | 3017 | if self.trio_runner: |
|
2992 | 3018 | runner = self.trio_runner |
|
2993 | 3019 | elif self.should_run_async( |
|
2994 | 3020 | raw_cell, |
|
2995 | 3021 | transformed_cell=transformed_cell, |
|
2996 | 3022 | preprocessing_exc_tuple=preprocessing_exc_tuple, |
|
2997 | 3023 | ): |
|
2998 | 3024 | runner = self.loop_runner |
|
2999 | 3025 | else: |
|
3000 | 3026 | runner = _pseudo_sync_runner |
|
3001 | 3027 | |
|
3002 | 3028 | try: |
|
3003 | 3029 | return runner(coro) |
|
3004 | 3030 | except BaseException as e: |
|
3005 | info = ExecutionInfo(raw_cell, store_history, silent, shell_futures) | |
|
3031 | info = ExecutionInfo( | |
|
3032 | raw_cell, store_history, silent, shell_futures, cell_id | |
|
3033 | ) | |
|
3006 | 3034 | result = ExecutionResult(info) |
|
3007 | 3035 | result.error_in_exec = e |
|
3008 | 3036 | self.showtraceback(running_compiled_code=True) |
|
3009 | 3037 | return result |
|
3010 | 3038 | return |
|
3011 | 3039 | |
|
3012 | 3040 | def should_run_async( |
|
3013 | 3041 | self, raw_cell: str, *, transformed_cell=None, preprocessing_exc_tuple=None |
|
3014 | 3042 | ) -> bool: |
|
3015 | 3043 | """Return whether a cell should be run asynchronously via a coroutine runner |
|
3016 | 3044 | |
|
3017 | 3045 | Parameters |
|
3018 | 3046 | ---------- |
|
3019 | 3047 | raw_cell: str |
|
3020 | 3048 | The code to be executed |
|
3021 | 3049 | |
|
3022 | 3050 | Returns |
|
3023 | 3051 | ------- |
|
3024 | 3052 | result: bool |
|
3025 | 3053 | Whether the code needs to be run with a coroutine runner or not |
|
3026 | 3054 | |
|
3027 | 3055 | .. versionadded:: 7.0 |
|
3028 | 3056 | """ |
|
3029 | 3057 | if not self.autoawait: |
|
3030 | 3058 | return False |
|
3031 | 3059 | if preprocessing_exc_tuple is not None: |
|
3032 | 3060 | return False |
|
3033 | 3061 | assert preprocessing_exc_tuple is None |
|
3034 | 3062 | if transformed_cell is None: |
|
3035 | 3063 | warnings.warn( |
|
3036 | 3064 | "`should_run_async` will not call `transform_cell`" |
|
3037 | 3065 | " automatically in the future. Please pass the result to" |
|
3038 | 3066 | " `transformed_cell` argument and any exception that happen" |
|
3039 | 3067 | " during the" |
|
3040 | 3068 | "transform in `preprocessing_exc_tuple` in" |
|
3041 | 3069 | " IPython 7.17 and above.", |
|
3042 | 3070 | DeprecationWarning, |
|
3043 | 3071 | stacklevel=2, |
|
3044 | 3072 | ) |
|
3045 | 3073 | try: |
|
3046 | 3074 | cell = self.transform_cell(raw_cell) |
|
3047 | 3075 | except Exception: |
|
3048 | 3076 | # any exception during transform will be raised |
|
3049 | 3077 | # prior to execution |
|
3050 | 3078 | return False |
|
3051 | 3079 | else: |
|
3052 | 3080 | cell = transformed_cell |
|
3053 | 3081 | return _should_be_async(cell) |
|
3054 | 3082 | |
|
3055 | 3083 | async def run_cell_async( |
|
3056 | 3084 | self, |
|
3057 | 3085 | raw_cell: str, |
|
3058 | 3086 | store_history=False, |
|
3059 | 3087 | silent=False, |
|
3060 | 3088 | shell_futures=True, |
|
3061 | 3089 | *, |
|
3062 | 3090 | transformed_cell: Optional[str] = None, |
|
3063 | preprocessing_exc_tuple: Optional[Any] = None | |
|
3091 | preprocessing_exc_tuple: Optional[Any] = None, | |
|
3092 | cell_id=None, | |
|
3064 | 3093 | ) -> ExecutionResult: |
|
3065 | 3094 | """Run a complete IPython cell asynchronously. |
|
3066 | 3095 | |
|
3067 | 3096 | Parameters |
|
3068 | 3097 | ---------- |
|
3069 | 3098 | raw_cell : str |
|
3070 | 3099 | The code (including IPython code such as %magic functions) to run. |
|
3071 | 3100 | store_history : bool |
|
3072 | 3101 | If True, the raw and translated cell will be stored in IPython's |
|
3073 | 3102 | history. For user code calling back into IPython's machinery, this |
|
3074 | 3103 | should be set to False. |
|
3075 | 3104 | silent : bool |
|
3076 | 3105 | If True, avoid side-effects, such as implicit displayhooks and |
|
3077 | 3106 | and logging. silent=True forces store_history=False. |
|
3078 | 3107 | shell_futures : bool |
|
3079 | 3108 | If True, the code will share future statements with the interactive |
|
3080 | 3109 | shell. It will both be affected by previous __future__ imports, and |
|
3081 | 3110 | any __future__ imports in the code will affect the shell. If False, |
|
3082 | 3111 | __future__ imports are not shared in either direction. |
|
3083 | 3112 | transformed_cell: str |
|
3084 | 3113 | cell that was passed through transformers |
|
3085 | 3114 | preprocessing_exc_tuple: |
|
3086 | 3115 | trace if the transformation failed. |
|
3087 | 3116 | |
|
3088 | 3117 | Returns |
|
3089 | 3118 | ------- |
|
3090 | 3119 | result : :class:`ExecutionResult` |
|
3091 | 3120 | |
|
3092 | 3121 | .. versionadded:: 7.0 |
|
3093 | 3122 | """ |
|
3094 | info = ExecutionInfo( | |
|
3095 | raw_cell, store_history, silent, shell_futures) | |
|
3123 | info = ExecutionInfo(raw_cell, store_history, silent, shell_futures, cell_id) | |
|
3096 | 3124 | result = ExecutionResult(info) |
|
3097 | 3125 | |
|
3098 | 3126 | if (not raw_cell) or raw_cell.isspace(): |
|
3099 | 3127 | self.last_execution_succeeded = True |
|
3100 | 3128 | self.last_execution_result = result |
|
3101 | 3129 | return result |
|
3102 | 3130 | |
|
3103 | 3131 | if silent: |
|
3104 | 3132 | store_history = False |
|
3105 | 3133 | |
|
3106 | 3134 | if store_history: |
|
3107 | 3135 | result.execution_count = self.execution_count |
|
3108 | 3136 | |
|
3109 | 3137 | def error_before_exec(value): |
|
3110 | 3138 | if store_history: |
|
3111 | 3139 | self.execution_count += 1 |
|
3112 | 3140 | result.error_before_exec = value |
|
3113 | 3141 | self.last_execution_succeeded = False |
|
3114 | 3142 | self.last_execution_result = result |
|
3115 | 3143 | return result |
|
3116 | 3144 | |
|
3117 | 3145 | self.events.trigger('pre_execute') |
|
3118 | 3146 | if not silent: |
|
3119 | 3147 | self.events.trigger('pre_run_cell', info) |
|
3120 | 3148 | |
|
3121 | 3149 | if transformed_cell is None: |
|
3122 | 3150 | warnings.warn( |
|
3123 | 3151 | "`run_cell_async` will not call `transform_cell`" |
|
3124 | 3152 | " automatically in the future. Please pass the result to" |
|
3125 | 3153 | " `transformed_cell` argument and any exception that happen" |
|
3126 | 3154 | " during the" |
|
3127 | 3155 | "transform in `preprocessing_exc_tuple` in" |
|
3128 | 3156 | " IPython 7.17 and above.", |
|
3129 | 3157 | DeprecationWarning, |
|
3130 | 3158 | stacklevel=2, |
|
3131 | 3159 | ) |
|
3132 | 3160 | # If any of our input transformation (input_transformer_manager or |
|
3133 | 3161 | # prefilter_manager) raises an exception, we store it in this variable |
|
3134 | 3162 | # so that we can display the error after logging the input and storing |
|
3135 | 3163 | # it in the history. |
|
3136 | 3164 | try: |
|
3137 | 3165 | cell = self.transform_cell(raw_cell) |
|
3138 | 3166 | except Exception: |
|
3139 | 3167 | preprocessing_exc_tuple = sys.exc_info() |
|
3140 | 3168 | cell = raw_cell # cell has to exist so it can be stored/logged |
|
3141 | 3169 | else: |
|
3142 | 3170 | preprocessing_exc_tuple = None |
|
3143 | 3171 | else: |
|
3144 | 3172 | if preprocessing_exc_tuple is None: |
|
3145 | 3173 | cell = transformed_cell |
|
3146 | 3174 | else: |
|
3147 | 3175 | cell = raw_cell |
|
3148 | 3176 | |
|
3149 | 3177 | # Store raw and processed history |
|
3150 | 3178 | if store_history: |
|
3151 | 3179 | self.history_manager.store_inputs(self.execution_count, |
|
3152 | 3180 | cell, raw_cell) |
|
3153 | 3181 | if not silent: |
|
3154 | 3182 | self.logger.log(cell, raw_cell) |
|
3155 | 3183 | |
|
3156 | 3184 | # Display the exception if input processing failed. |
|
3157 | 3185 | if preprocessing_exc_tuple is not None: |
|
3158 | 3186 | self.showtraceback(preprocessing_exc_tuple) |
|
3159 | 3187 | if store_history: |
|
3160 | 3188 | self.execution_count += 1 |
|
3161 | 3189 | return error_before_exec(preprocessing_exc_tuple[1]) |
|
3162 | 3190 | |
|
3163 | 3191 | # Our own compiler remembers the __future__ environment. If we want to |
|
3164 | 3192 | # run code with a separate __future__ environment, use the default |
|
3165 | 3193 | # compiler |
|
3166 | 3194 | compiler = self.compile if shell_futures else self.compiler_class() |
|
3167 | 3195 | |
|
3168 | 3196 | _run_async = False |
|
3169 | 3197 | |
|
3170 | 3198 | with self.builtin_trap: |
|
3171 | 3199 | cell_name = self.compile.cache( |
|
3172 | 3200 | cell, self.execution_count, raw_code=raw_cell |
|
3173 | 3201 | ) |
|
3174 | 3202 | |
|
3175 | 3203 | with self.display_trap: |
|
3176 | 3204 | # Compile to bytecode |
|
3177 | 3205 | try: |
|
3178 | 3206 | if sys.version_info < (3,8) and self.autoawait: |
|
3179 | 3207 | if _should_be_async(cell): |
|
3180 | 3208 | # the code AST below will not be user code: we wrap it |
|
3181 | 3209 | # in an `async def`. This will likely make some AST |
|
3182 | 3210 | # transformer below miss some transform opportunity and |
|
3183 | 3211 | # introduce a small coupling to run_code (in which we |
|
3184 | 3212 | # bake some assumptions of what _ast_asyncify returns. |
|
3185 | 3213 | # they are ways around (like grafting part of the ast |
|
3186 | 3214 | # later: |
|
3187 | 3215 | # - Here, return code_ast.body[0].body[1:-1], as well |
|
3188 | 3216 | # as last expression in return statement which is |
|
3189 | 3217 | # the user code part. |
|
3190 | 3218 | # - Let it go through the AST transformers, and graft |
|
3191 | 3219 | # - it back after the AST transform |
|
3192 | 3220 | # But that seem unreasonable, at least while we |
|
3193 | 3221 | # do not need it. |
|
3194 | 3222 | code_ast = _ast_asyncify(cell, 'async-def-wrapper') |
|
3195 | 3223 | _run_async = True |
|
3196 | 3224 | else: |
|
3197 | 3225 | code_ast = compiler.ast_parse(cell, filename=cell_name) |
|
3198 | 3226 | else: |
|
3199 | 3227 | code_ast = compiler.ast_parse(cell, filename=cell_name) |
|
3200 | 3228 | except self.custom_exceptions as e: |
|
3201 | 3229 | etype, value, tb = sys.exc_info() |
|
3202 | 3230 | self.CustomTB(etype, value, tb) |
|
3203 | 3231 | return error_before_exec(e) |
|
3204 | 3232 | except IndentationError as e: |
|
3205 | 3233 | self.showindentationerror() |
|
3206 | 3234 | return error_before_exec(e) |
|
3207 | 3235 | except (OverflowError, SyntaxError, ValueError, TypeError, |
|
3208 | 3236 | MemoryError) as e: |
|
3209 | 3237 | self.showsyntaxerror() |
|
3210 | 3238 | return error_before_exec(e) |
|
3211 | 3239 | |
|
3212 | 3240 | # Apply AST transformations |
|
3213 | 3241 | try: |
|
3214 | 3242 | code_ast = self.transform_ast(code_ast) |
|
3215 | 3243 | except InputRejected as e: |
|
3216 | 3244 | self.showtraceback() |
|
3217 | 3245 | return error_before_exec(e) |
|
3218 | 3246 | |
|
3219 | 3247 | # Give the displayhook a reference to our ExecutionResult so it |
|
3220 | 3248 | # can fill in the output value. |
|
3221 | 3249 | self.displayhook.exec_result = result |
|
3222 | 3250 | |
|
3223 | 3251 | # Execute the user code |
|
3224 | 3252 | interactivity = "none" if silent else self.ast_node_interactivity |
|
3225 | 3253 | if _run_async: |
|
3226 | 3254 | interactivity = 'async' |
|
3227 | 3255 | |
|
3228 | 3256 | has_raised = await self.run_ast_nodes(code_ast.body, cell_name, |
|
3229 | 3257 | interactivity=interactivity, compiler=compiler, result=result) |
|
3230 | 3258 | |
|
3231 | 3259 | self.last_execution_succeeded = not has_raised |
|
3232 | 3260 | self.last_execution_result = result |
|
3233 | 3261 | |
|
3234 | 3262 | # Reset this so later displayed values do not modify the |
|
3235 | 3263 | # ExecutionResult |
|
3236 | 3264 | self.displayhook.exec_result = None |
|
3237 | 3265 | |
|
3238 | 3266 | if store_history: |
|
3239 | 3267 | # Write output to the database. Does nothing unless |
|
3240 | 3268 | # history output logging is enabled. |
|
3241 | 3269 | self.history_manager.store_output(self.execution_count) |
|
3242 | 3270 | # Each cell is a *single* input, regardless of how many lines it has |
|
3243 | 3271 | self.execution_count += 1 |
|
3244 | 3272 | |
|
3245 | 3273 | return result |
|
3246 | 3274 | |
|
3247 | 3275 | def transform_cell(self, raw_cell): |
|
3248 | 3276 | """Transform an input cell before parsing it. |
|
3249 | 3277 | |
|
3250 | 3278 | Static transformations, implemented in IPython.core.inputtransformer2, |
|
3251 | 3279 | deal with things like ``%magic`` and ``!system`` commands. |
|
3252 | 3280 | These run on all input. |
|
3253 | 3281 | Dynamic transformations, for things like unescaped magics and the exit |
|
3254 | 3282 | autocall, depend on the state of the interpreter. |
|
3255 | 3283 | These only apply to single line inputs. |
|
3256 | 3284 | |
|
3257 | 3285 | These string-based transformations are followed by AST transformations; |
|
3258 | 3286 | see :meth:`transform_ast`. |
|
3259 | 3287 | """ |
|
3260 | 3288 | # Static input transformations |
|
3261 | 3289 | cell = self.input_transformer_manager.transform_cell(raw_cell) |
|
3262 | 3290 | |
|
3263 | 3291 | if len(cell.splitlines()) == 1: |
|
3264 | 3292 | # Dynamic transformations - only applied for single line commands |
|
3265 | 3293 | with self.builtin_trap: |
|
3266 | 3294 | # use prefilter_lines to handle trailing newlines |
|
3267 | 3295 | # restore trailing newline for ast.parse |
|
3268 | 3296 | cell = self.prefilter_manager.prefilter_lines(cell) + '\n' |
|
3269 | 3297 | |
|
3270 | 3298 | lines = cell.splitlines(keepends=True) |
|
3271 | 3299 | for transform in self.input_transformers_post: |
|
3272 | 3300 | lines = transform(lines) |
|
3273 | 3301 | cell = ''.join(lines) |
|
3274 | 3302 | |
|
3275 | 3303 | return cell |
|
3276 | 3304 | |
|
3277 | 3305 | def transform_ast(self, node): |
|
3278 | 3306 | """Apply the AST transformations from self.ast_transformers |
|
3279 | 3307 | |
|
3280 | 3308 | Parameters |
|
3281 | 3309 | ---------- |
|
3282 | 3310 | node : ast.Node |
|
3283 | 3311 | The root node to be transformed. Typically called with the ast.Module |
|
3284 | 3312 | produced by parsing user input. |
|
3285 | 3313 | |
|
3286 | 3314 | Returns |
|
3287 | 3315 | ------- |
|
3288 | 3316 | An ast.Node corresponding to the node it was called with. Note that it |
|
3289 | 3317 | may also modify the passed object, so don't rely on references to the |
|
3290 | 3318 | original AST. |
|
3291 | 3319 | """ |
|
3292 | 3320 | for transformer in self.ast_transformers: |
|
3293 | 3321 | try: |
|
3294 | 3322 | node = transformer.visit(node) |
|
3295 | 3323 | except InputRejected: |
|
3296 | 3324 | # User-supplied AST transformers can reject an input by raising |
|
3297 | 3325 | # an InputRejected. Short-circuit in this case so that we |
|
3298 | 3326 | # don't unregister the transform. |
|
3299 | 3327 | raise |
|
3300 | 3328 | except Exception: |
|
3301 | 3329 | warn("AST transformer %r threw an error. It will be unregistered." % transformer) |
|
3302 | 3330 | self.ast_transformers.remove(transformer) |
|
3303 | 3331 | |
|
3304 | 3332 | if self.ast_transformers: |
|
3305 | 3333 | ast.fix_missing_locations(node) |
|
3306 | 3334 | return node |
|
3307 | 3335 | |
|
3308 | 3336 | def _update_code_co_name(self, code): |
|
3309 | 3337 | """Python 3.10 changed the behaviour so that whenever a code object |
|
3310 | 3338 | is assembled in the compile(ast) the co_firstlineno would be == 1. |
|
3311 | 3339 | |
|
3312 | 3340 | This makes pydevd/debugpy think that all cells invoked are the same |
|
3313 | 3341 | since it caches information based on (co_firstlineno, co_name, co_filename). |
|
3314 | 3342 | |
|
3315 | 3343 | Given that, this function changes the code 'co_name' to be unique |
|
3316 | 3344 | based on the first real lineno of the code (which also has a nice |
|
3317 | 3345 | side effect of customizing the name so that it's not always <module>). |
|
3318 | 3346 | |
|
3319 | 3347 | See: https://github.com/ipython/ipykernel/issues/841 |
|
3320 | 3348 | """ |
|
3321 | 3349 | if not hasattr(code, "replace"): |
|
3322 | 3350 | # It may not be available on older versions of Python (only |
|
3323 | 3351 | # available for 3.8 onwards). |
|
3324 | 3352 | return code |
|
3325 | 3353 | try: |
|
3326 | 3354 | first_real_line = next(dis.findlinestarts(code))[1] |
|
3327 | 3355 | except StopIteration: |
|
3328 | 3356 | return code |
|
3329 | 3357 | return code.replace(co_name="<cell line: %s>" % (first_real_line,)) |
|
3330 | 3358 | |
|
3331 | 3359 | async def run_ast_nodes(self, nodelist:ListType[AST], cell_name:str, interactivity='last_expr', |
|
3332 | 3360 | compiler=compile, result=None): |
|
3333 | 3361 | """Run a sequence of AST nodes. The execution mode depends on the |
|
3334 | 3362 | interactivity parameter. |
|
3335 | 3363 | |
|
3336 | 3364 | Parameters |
|
3337 | 3365 | ---------- |
|
3338 | 3366 | nodelist : list |
|
3339 | 3367 | A sequence of AST nodes to run. |
|
3340 | 3368 | cell_name : str |
|
3341 | 3369 | Will be passed to the compiler as the filename of the cell. Typically |
|
3342 | 3370 | the value returned by ip.compile.cache(cell). |
|
3343 | 3371 | interactivity : str |
|
3344 | 3372 | 'all', 'last', 'last_expr' , 'last_expr_or_assign' or 'none', |
|
3345 | 3373 | specifying which nodes should be run interactively (displaying output |
|
3346 | 3374 | from expressions). 'last_expr' will run the last node interactively |
|
3347 | 3375 | only if it is an expression (i.e. expressions in loops or other blocks |
|
3348 | 3376 | are not displayed) 'last_expr_or_assign' will run the last expression |
|
3349 | 3377 | or the last assignment. Other values for this parameter will raise a |
|
3350 | 3378 | ValueError. |
|
3351 | 3379 | |
|
3352 | 3380 | Experimental value: 'async' Will try to run top level interactive |
|
3353 | 3381 | async/await code in default runner, this will not respect the |
|
3354 | 3382 | interactivity setting and will only run the last node if it is an |
|
3355 | 3383 | expression. |
|
3356 | 3384 | |
|
3357 | 3385 | compiler : callable |
|
3358 | 3386 | A function with the same interface as the built-in compile(), to turn |
|
3359 | 3387 | the AST nodes into code objects. Default is the built-in compile(). |
|
3360 | 3388 | result : ExecutionResult, optional |
|
3361 | 3389 | An object to store exceptions that occur during execution. |
|
3362 | 3390 | |
|
3363 | 3391 | Returns |
|
3364 | 3392 | ------- |
|
3365 | 3393 | True if an exception occurred while running code, False if it finished |
|
3366 | 3394 | running. |
|
3367 | 3395 | """ |
|
3368 | 3396 | if not nodelist: |
|
3369 | 3397 | return |
|
3370 | 3398 | |
|
3371 | 3399 | if interactivity == 'last_expr_or_assign': |
|
3372 | 3400 | if isinstance(nodelist[-1], _assign_nodes): |
|
3373 | 3401 | asg = nodelist[-1] |
|
3374 | 3402 | if isinstance(asg, ast.Assign) and len(asg.targets) == 1: |
|
3375 | 3403 | target = asg.targets[0] |
|
3376 | 3404 | elif isinstance(asg, _single_targets_nodes): |
|
3377 | 3405 | target = asg.target |
|
3378 | 3406 | else: |
|
3379 | 3407 | target = None |
|
3380 | 3408 | if isinstance(target, ast.Name): |
|
3381 | 3409 | nnode = ast.Expr(ast.Name(target.id, ast.Load())) |
|
3382 | 3410 | ast.fix_missing_locations(nnode) |
|
3383 | 3411 | nodelist.append(nnode) |
|
3384 | 3412 | interactivity = 'last_expr' |
|
3385 | 3413 | |
|
3386 | 3414 | _async = False |
|
3387 | 3415 | if interactivity == 'last_expr': |
|
3388 | 3416 | if isinstance(nodelist[-1], ast.Expr): |
|
3389 | 3417 | interactivity = "last" |
|
3390 | 3418 | else: |
|
3391 | 3419 | interactivity = "none" |
|
3392 | 3420 | |
|
3393 | 3421 | if interactivity == 'none': |
|
3394 | 3422 | to_run_exec, to_run_interactive = nodelist, [] |
|
3395 | 3423 | elif interactivity == 'last': |
|
3396 | 3424 | to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:] |
|
3397 | 3425 | elif interactivity == 'all': |
|
3398 | 3426 | to_run_exec, to_run_interactive = [], nodelist |
|
3399 | 3427 | elif interactivity == 'async': |
|
3400 | 3428 | to_run_exec, to_run_interactive = [], nodelist |
|
3401 | 3429 | _async = True |
|
3402 | 3430 | else: |
|
3403 | 3431 | raise ValueError("Interactivity was %r" % interactivity) |
|
3404 | 3432 | |
|
3405 | 3433 | try: |
|
3406 | 3434 | if _async and sys.version_info > (3,8): |
|
3407 | 3435 | raise ValueError("This branch should never happen on Python 3.8 and above, " |
|
3408 | 3436 | "please try to upgrade IPython and open a bug report with your case.") |
|
3409 | 3437 | if _async: |
|
3410 | 3438 | # If interactivity is async the semantics of run_code are |
|
3411 | 3439 | # completely different Skip usual machinery. |
|
3412 | 3440 | mod = Module(nodelist, []) |
|
3413 | 3441 | async_wrapper_code = compiler(mod, cell_name, 'exec') |
|
3414 | 3442 | exec(async_wrapper_code, self.user_global_ns, self.user_ns) |
|
3415 | 3443 | async_code = removed_co_newlocals(self.user_ns.pop('async-def-wrapper')).__code__ |
|
3416 | 3444 | if (await self.run_code(async_code, result, async_=True)): |
|
3417 | 3445 | return True |
|
3418 | 3446 | else: |
|
3419 | 3447 | if sys.version_info > (3, 8): |
|
3420 | 3448 | def compare(code): |
|
3421 | 3449 | is_async = (inspect.CO_COROUTINE & code.co_flags == inspect.CO_COROUTINE) |
|
3422 | 3450 | return is_async |
|
3423 | 3451 | else: |
|
3424 | 3452 | def compare(code): |
|
3425 | 3453 | return _async |
|
3426 | 3454 | |
|
3427 | 3455 | # refactor that to just change the mod constructor. |
|
3428 | 3456 | to_run = [] |
|
3429 | 3457 | for node in to_run_exec: |
|
3430 | 3458 | to_run.append((node, 'exec')) |
|
3431 | 3459 | |
|
3432 | 3460 | for node in to_run_interactive: |
|
3433 | 3461 | to_run.append((node, 'single')) |
|
3434 | 3462 | |
|
3435 | 3463 | for node,mode in to_run: |
|
3436 | 3464 | if mode == 'exec': |
|
3437 | 3465 | mod = Module([node], []) |
|
3438 | 3466 | elif mode == 'single': |
|
3439 | 3467 | mod = ast.Interactive([node]) |
|
3440 | 3468 | with compiler.extra_flags(getattr(ast, 'PyCF_ALLOW_TOP_LEVEL_AWAIT', 0x0) if self.autoawait else 0x0): |
|
3441 | 3469 | code = compiler(mod, cell_name, mode) |
|
3442 | 3470 | code = self._update_code_co_name(code) |
|
3443 | 3471 | asy = compare(code) |
|
3444 | 3472 | if (await self.run_code(code, result, async_=asy)): |
|
3445 | 3473 | return True |
|
3446 | 3474 | |
|
3447 | 3475 | # Flush softspace |
|
3448 | 3476 | if softspace(sys.stdout, 0): |
|
3449 | 3477 | print() |
|
3450 | 3478 | |
|
3451 | 3479 | except: |
|
3452 | 3480 | # It's possible to have exceptions raised here, typically by |
|
3453 | 3481 | # compilation of odd code (such as a naked 'return' outside a |
|
3454 | 3482 | # function) that did parse but isn't valid. Typically the exception |
|
3455 | 3483 | # is a SyntaxError, but it's safest just to catch anything and show |
|
3456 | 3484 | # the user a traceback. |
|
3457 | 3485 | |
|
3458 | 3486 | # We do only one try/except outside the loop to minimize the impact |
|
3459 | 3487 | # on runtime, and also because if any node in the node list is |
|
3460 | 3488 | # broken, we should stop execution completely. |
|
3461 | 3489 | if result: |
|
3462 | 3490 | result.error_before_exec = sys.exc_info()[1] |
|
3463 | 3491 | self.showtraceback() |
|
3464 | 3492 | return True |
|
3465 | 3493 | |
|
3466 | 3494 | return False |
|
3467 | 3495 | |
|
3468 | 3496 | def _async_exec(self, code_obj: types.CodeType, user_ns: dict): |
|
3469 | 3497 | """ |
|
3470 | 3498 | Evaluate an asynchronous code object using a code runner |
|
3471 | 3499 | |
|
3472 | 3500 | Fake asynchronous execution of code_object in a namespace via a proxy namespace. |
|
3473 | 3501 | |
|
3474 | 3502 | Returns coroutine object, which can be executed via async loop runner |
|
3475 | 3503 | |
|
3476 | 3504 | WARNING: The semantics of `async_exec` are quite different from `exec`, |
|
3477 | 3505 | in particular you can only pass a single namespace. It also return a |
|
3478 | 3506 | handle to the value of the last things returned by code_object. |
|
3479 | 3507 | """ |
|
3480 | 3508 | |
|
3481 | 3509 | return eval(code_obj, user_ns) |
|
3482 | 3510 | |
|
3483 | 3511 | async def run_code(self, code_obj, result=None, *, async_=False): |
|
3484 | 3512 | """Execute a code object. |
|
3485 | 3513 | |
|
3486 | 3514 | When an exception occurs, self.showtraceback() is called to display a |
|
3487 | 3515 | traceback. |
|
3488 | 3516 | |
|
3489 | 3517 | Parameters |
|
3490 | 3518 | ---------- |
|
3491 | 3519 | code_obj : code object |
|
3492 | 3520 | A compiled code object, to be executed |
|
3493 | 3521 | result : ExecutionResult, optional |
|
3494 | 3522 | An object to store exceptions that occur during execution. |
|
3495 | 3523 | async_ : Bool (Experimental) |
|
3496 | 3524 | Attempt to run top-level asynchronous code in a default loop. |
|
3497 | 3525 | |
|
3498 | 3526 | Returns |
|
3499 | 3527 | ------- |
|
3500 | 3528 | False : successful execution. |
|
3501 | 3529 | True : an error occurred. |
|
3502 | 3530 | """ |
|
3503 | 3531 | # special value to say that anything above is IPython and should be |
|
3504 | 3532 | # hidden. |
|
3505 | 3533 | __tracebackhide__ = "__ipython_bottom__" |
|
3506 | 3534 | # Set our own excepthook in case the user code tries to call it |
|
3507 | 3535 | # directly, so that the IPython crash handler doesn't get triggered |
|
3508 | 3536 | old_excepthook, sys.excepthook = sys.excepthook, self.excepthook |
|
3509 | 3537 | |
|
3510 | 3538 | # we save the original sys.excepthook in the instance, in case config |
|
3511 | 3539 | # code (such as magics) needs access to it. |
|
3512 | 3540 | self.sys_excepthook = old_excepthook |
|
3513 | 3541 | outflag = True # happens in more places, so it's easier as default |
|
3514 | 3542 | try: |
|
3515 | 3543 | try: |
|
3516 | 3544 | self.hooks.pre_run_code_hook() |
|
3517 | 3545 | if async_ and sys.version_info < (3,8): |
|
3518 | 3546 | last_expr = (await self._async_exec(code_obj, self.user_ns)) |
|
3519 | 3547 | code = compile('last_expr', 'fake', "single") |
|
3520 | 3548 | exec(code, {'last_expr': last_expr}) |
|
3521 | 3549 | elif async_ : |
|
3522 | 3550 | await eval(code_obj, self.user_global_ns, self.user_ns) |
|
3523 | 3551 | else: |
|
3524 | 3552 | exec(code_obj, self.user_global_ns, self.user_ns) |
|
3525 | 3553 | finally: |
|
3526 | 3554 | # Reset our crash handler in place |
|
3527 | 3555 | sys.excepthook = old_excepthook |
|
3528 | 3556 | except SystemExit as e: |
|
3529 | 3557 | if result is not None: |
|
3530 | 3558 | result.error_in_exec = e |
|
3531 | 3559 | self.showtraceback(exception_only=True) |
|
3532 | 3560 | warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1) |
|
3533 | 3561 | except self.custom_exceptions: |
|
3534 | 3562 | etype, value, tb = sys.exc_info() |
|
3535 | 3563 | if result is not None: |
|
3536 | 3564 | result.error_in_exec = value |
|
3537 | 3565 | self.CustomTB(etype, value, tb) |
|
3538 | 3566 | except: |
|
3539 | 3567 | if result is not None: |
|
3540 | 3568 | result.error_in_exec = sys.exc_info()[1] |
|
3541 | 3569 | self.showtraceback(running_compiled_code=True) |
|
3542 | 3570 | else: |
|
3543 | 3571 | outflag = False |
|
3544 | 3572 | return outflag |
|
3545 | 3573 | |
|
3546 | 3574 | # For backwards compatibility |
|
3547 | 3575 | runcode = run_code |
|
3548 | 3576 | |
|
3549 | 3577 | def check_complete(self, code: str) -> Tuple[str, str]: |
|
3550 | 3578 | """Return whether a block of code is ready to execute, or should be continued |
|
3551 | 3579 | |
|
3552 | 3580 | Parameters |
|
3553 | 3581 | ---------- |
|
3554 | 3582 | source : string |
|
3555 | 3583 | Python input code, which can be multiline. |
|
3556 | 3584 | |
|
3557 | 3585 | Returns |
|
3558 | 3586 | ------- |
|
3559 | 3587 | status : str |
|
3560 | 3588 | One of 'complete', 'incomplete', or 'invalid' if source is not a |
|
3561 | 3589 | prefix of valid code. |
|
3562 | 3590 | indent : str |
|
3563 | 3591 | When status is 'incomplete', this is some whitespace to insert on |
|
3564 | 3592 | the next line of the prompt. |
|
3565 | 3593 | """ |
|
3566 | 3594 | status, nspaces = self.input_transformer_manager.check_complete(code) |
|
3567 | 3595 | return status, ' ' * (nspaces or 0) |
|
3568 | 3596 | |
|
3569 | 3597 | #------------------------------------------------------------------------- |
|
3570 | 3598 | # Things related to GUI support and pylab |
|
3571 | 3599 | #------------------------------------------------------------------------- |
|
3572 | 3600 | |
|
3573 | 3601 | active_eventloop = None |
|
3574 | 3602 | |
|
3575 | 3603 | def enable_gui(self, gui=None): |
|
3576 | 3604 | raise NotImplementedError('Implement enable_gui in a subclass') |
|
3577 | 3605 | |
|
3578 | 3606 | def enable_matplotlib(self, gui=None): |
|
3579 | 3607 | """Enable interactive matplotlib and inline figure support. |
|
3580 | 3608 | |
|
3581 | 3609 | This takes the following steps: |
|
3582 | 3610 | |
|
3583 | 3611 | 1. select the appropriate eventloop and matplotlib backend |
|
3584 | 3612 | 2. set up matplotlib for interactive use with that backend |
|
3585 | 3613 | 3. configure formatters for inline figure display |
|
3586 | 3614 | 4. enable the selected gui eventloop |
|
3587 | 3615 | |
|
3588 | 3616 | Parameters |
|
3589 | 3617 | ---------- |
|
3590 | 3618 | gui : optional, string |
|
3591 | 3619 | If given, dictates the choice of matplotlib GUI backend to use |
|
3592 | 3620 | (should be one of IPython's supported backends, 'qt', 'osx', 'tk', |
|
3593 | 3621 | 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by |
|
3594 | 3622 | matplotlib (as dictated by the matplotlib build-time options plus the |
|
3595 | 3623 | user's matplotlibrc configuration file). Note that not all backends |
|
3596 | 3624 | make sense in all contexts, for example a terminal ipython can't |
|
3597 | 3625 | display figures inline. |
|
3598 | 3626 | """ |
|
3599 | 3627 | from IPython.core import pylabtools as pt |
|
3600 | 3628 | from matplotlib_inline.backend_inline import configure_inline_support |
|
3601 | 3629 | gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select) |
|
3602 | 3630 | |
|
3603 | 3631 | if gui != 'inline': |
|
3604 | 3632 | # If we have our first gui selection, store it |
|
3605 | 3633 | if self.pylab_gui_select is None: |
|
3606 | 3634 | self.pylab_gui_select = gui |
|
3607 | 3635 | # Otherwise if they are different |
|
3608 | 3636 | elif gui != self.pylab_gui_select: |
|
3609 | 3637 | print('Warning: Cannot change to a different GUI toolkit: %s.' |
|
3610 | 3638 | ' Using %s instead.' % (gui, self.pylab_gui_select)) |
|
3611 | 3639 | gui, backend = pt.find_gui_and_backend(self.pylab_gui_select) |
|
3612 | 3640 | |
|
3613 | 3641 | pt.activate_matplotlib(backend) |
|
3614 | 3642 | configure_inline_support(self, backend) |
|
3615 | 3643 | |
|
3616 | 3644 | # Now we must activate the gui pylab wants to use, and fix %run to take |
|
3617 | 3645 | # plot updates into account |
|
3618 | 3646 | self.enable_gui(gui) |
|
3619 | 3647 | self.magics_manager.registry['ExecutionMagics'].default_runner = \ |
|
3620 | 3648 | pt.mpl_runner(self.safe_execfile) |
|
3621 | 3649 | |
|
3622 | 3650 | return gui, backend |
|
3623 | 3651 | |
|
3624 | 3652 | def enable_pylab(self, gui=None, import_all=True, welcome_message=False): |
|
3625 | 3653 | """Activate pylab support at runtime. |
|
3626 | 3654 | |
|
3627 | 3655 | This turns on support for matplotlib, preloads into the interactive |
|
3628 | 3656 | namespace all of numpy and pylab, and configures IPython to correctly |
|
3629 | 3657 | interact with the GUI event loop. The GUI backend to be used can be |
|
3630 | 3658 | optionally selected with the optional ``gui`` argument. |
|
3631 | 3659 | |
|
3632 | 3660 | This method only adds preloading the namespace to InteractiveShell.enable_matplotlib. |
|
3633 | 3661 | |
|
3634 | 3662 | Parameters |
|
3635 | 3663 | ---------- |
|
3636 | 3664 | gui : optional, string |
|
3637 | 3665 | If given, dictates the choice of matplotlib GUI backend to use |
|
3638 | 3666 | (should be one of IPython's supported backends, 'qt', 'osx', 'tk', |
|
3639 | 3667 | 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by |
|
3640 | 3668 | matplotlib (as dictated by the matplotlib build-time options plus the |
|
3641 | 3669 | user's matplotlibrc configuration file). Note that not all backends |
|
3642 | 3670 | make sense in all contexts, for example a terminal ipython can't |
|
3643 | 3671 | display figures inline. |
|
3644 | 3672 | import_all : optional, bool, default: True |
|
3645 | 3673 | Whether to do `from numpy import *` and `from pylab import *` |
|
3646 | 3674 | in addition to module imports. |
|
3647 | 3675 | welcome_message : deprecated |
|
3648 | 3676 | This argument is ignored, no welcome message will be displayed. |
|
3649 | 3677 | """ |
|
3650 | 3678 | from IPython.core.pylabtools import import_pylab |
|
3651 | 3679 | |
|
3652 | 3680 | gui, backend = self.enable_matplotlib(gui) |
|
3653 | 3681 | |
|
3654 | 3682 | # We want to prevent the loading of pylab to pollute the user's |
|
3655 | 3683 | # namespace as shown by the %who* magics, so we execute the activation |
|
3656 | 3684 | # code in an empty namespace, and we update *both* user_ns and |
|
3657 | 3685 | # user_ns_hidden with this information. |
|
3658 | 3686 | ns = {} |
|
3659 | 3687 | import_pylab(ns, import_all) |
|
3660 | 3688 | # warn about clobbered names |
|
3661 | 3689 | ignored = {"__builtins__"} |
|
3662 | 3690 | both = set(ns).intersection(self.user_ns).difference(ignored) |
|
3663 | 3691 | clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ] |
|
3664 | 3692 | self.user_ns.update(ns) |
|
3665 | 3693 | self.user_ns_hidden.update(ns) |
|
3666 | 3694 | return gui, backend, clobbered |
|
3667 | 3695 | |
|
3668 | 3696 | #------------------------------------------------------------------------- |
|
3669 | 3697 | # Utilities |
|
3670 | 3698 | #------------------------------------------------------------------------- |
|
3671 | 3699 | |
|
3672 | 3700 | def var_expand(self, cmd, depth=0, formatter=DollarFormatter()): |
|
3673 | 3701 | """Expand python variables in a string. |
|
3674 | 3702 | |
|
3675 | 3703 | The depth argument indicates how many frames above the caller should |
|
3676 | 3704 | be walked to look for the local namespace where to expand variables. |
|
3677 | 3705 | |
|
3678 | 3706 | The global namespace for expansion is always the user's interactive |
|
3679 | 3707 | namespace. |
|
3680 | 3708 | """ |
|
3681 | 3709 | ns = self.user_ns.copy() |
|
3682 | 3710 | try: |
|
3683 | 3711 | frame = sys._getframe(depth+1) |
|
3684 | 3712 | except ValueError: |
|
3685 | 3713 | # This is thrown if there aren't that many frames on the stack, |
|
3686 | 3714 | # e.g. if a script called run_line_magic() directly. |
|
3687 | 3715 | pass |
|
3688 | 3716 | else: |
|
3689 | 3717 | ns.update(frame.f_locals) |
|
3690 | 3718 | |
|
3691 | 3719 | try: |
|
3692 | 3720 | # We have to use .vformat() here, because 'self' is a valid and common |
|
3693 | 3721 | # name, and expanding **ns for .format() would make it collide with |
|
3694 | 3722 | # the 'self' argument of the method. |
|
3695 | 3723 | cmd = formatter.vformat(cmd, args=[], kwargs=ns) |
|
3696 | 3724 | except Exception: |
|
3697 | 3725 | # if formatter couldn't format, just let it go untransformed |
|
3698 | 3726 | pass |
|
3699 | 3727 | return cmd |
|
3700 | 3728 | |
|
3701 | 3729 | def mktempfile(self, data=None, prefix='ipython_edit_'): |
|
3702 | 3730 | """Make a new tempfile and return its filename. |
|
3703 | 3731 | |
|
3704 | 3732 | This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp), |
|
3705 | 3733 | but it registers the created filename internally so ipython cleans it up |
|
3706 | 3734 | at exit time. |
|
3707 | 3735 | |
|
3708 | 3736 | Optional inputs: |
|
3709 | 3737 | |
|
3710 | 3738 | - data(None): if data is given, it gets written out to the temp file |
|
3711 | 3739 | immediately, and the file is closed again.""" |
|
3712 | 3740 | |
|
3713 | 3741 | dirname = tempfile.mkdtemp(prefix=prefix) |
|
3714 | 3742 | self.tempdirs.append(dirname) |
|
3715 | 3743 | |
|
3716 | 3744 | handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname) |
|
3717 | 3745 | os.close(handle) # On Windows, there can only be one open handle on a file |
|
3718 | 3746 | self.tempfiles.append(filename) |
|
3719 | 3747 | |
|
3720 | 3748 | if data: |
|
3721 | 3749 | with open(filename, 'w') as tmp_file: |
|
3722 | 3750 | tmp_file.write(data) |
|
3723 | 3751 | return filename |
|
3724 | 3752 | |
|
3725 | 3753 | @undoc |
|
3726 | 3754 | def write(self,data): |
|
3727 | 3755 | """DEPRECATED: Write a string to the default output""" |
|
3728 | 3756 | warn('InteractiveShell.write() is deprecated, use sys.stdout instead', |
|
3729 | 3757 | DeprecationWarning, stacklevel=2) |
|
3730 | 3758 | sys.stdout.write(data) |
|
3731 | 3759 | |
|
3732 | 3760 | @undoc |
|
3733 | 3761 | def write_err(self,data): |
|
3734 | 3762 | """DEPRECATED: Write a string to the default error output""" |
|
3735 | 3763 | warn('InteractiveShell.write_err() is deprecated, use sys.stderr instead', |
|
3736 | 3764 | DeprecationWarning, stacklevel=2) |
|
3737 | 3765 | sys.stderr.write(data) |
|
3738 | 3766 | |
|
3739 | 3767 | def ask_yes_no(self, prompt, default=None, interrupt=None): |
|
3740 | 3768 | if self.quiet: |
|
3741 | 3769 | return True |
|
3742 | 3770 | return ask_yes_no(prompt,default,interrupt) |
|
3743 | 3771 | |
|
3744 | 3772 | def show_usage(self): |
|
3745 | 3773 | """Show a usage message""" |
|
3746 | 3774 | page.page(IPython.core.usage.interactive_usage) |
|
3747 | 3775 | |
|
3748 | 3776 | def extract_input_lines(self, range_str, raw=False): |
|
3749 | 3777 | """Return as a string a set of input history slices. |
|
3750 | 3778 | |
|
3751 | 3779 | Parameters |
|
3752 | 3780 | ---------- |
|
3753 | 3781 | range_str : string |
|
3754 | 3782 | The set of slices is given as a string, like "~5/6-~4/2 4:8 9", |
|
3755 | 3783 | since this function is for use by magic functions which get their |
|
3756 | 3784 | arguments as strings. The number before the / is the session |
|
3757 | 3785 | number: ~n goes n back from the current session. |
|
3758 | 3786 | |
|
3759 | 3787 | raw : bool, optional |
|
3760 | 3788 | By default, the processed input is used. If this is true, the raw |
|
3761 | 3789 | input history is used instead. |
|
3762 | 3790 | |
|
3763 | 3791 | Notes |
|
3764 | 3792 | ----- |
|
3765 | 3793 | |
|
3766 | 3794 | Slices can be described with two notations: |
|
3767 | 3795 | |
|
3768 | 3796 | * ``N:M`` -> standard python form, means including items N...(M-1). |
|
3769 | 3797 | * ``N-M`` -> include items N..M (closed endpoint). |
|
3770 | 3798 | """ |
|
3771 | 3799 | lines = self.history_manager.get_range_by_str(range_str, raw=raw) |
|
3772 | 3800 | return "\n".join(x for _, _, x in lines) |
|
3773 | 3801 | |
|
3774 | 3802 | def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False): |
|
3775 | 3803 | """Get a code string from history, file, url, or a string or macro. |
|
3776 | 3804 | |
|
3777 | 3805 | This is mainly used by magic functions. |
|
3778 | 3806 | |
|
3779 | 3807 | Parameters |
|
3780 | 3808 | ---------- |
|
3781 | 3809 | |
|
3782 | 3810 | target : str |
|
3783 | 3811 | |
|
3784 | 3812 | A string specifying code to retrieve. This will be tried respectively |
|
3785 | 3813 | as: ranges of input history (see %history for syntax), url, |
|
3786 | 3814 | corresponding .py file, filename, or an expression evaluating to a |
|
3787 | 3815 | string or Macro in the user namespace. |
|
3788 | 3816 | |
|
3789 | 3817 | raw : bool |
|
3790 | 3818 | If true (default), retrieve raw history. Has no effect on the other |
|
3791 | 3819 | retrieval mechanisms. |
|
3792 | 3820 | |
|
3793 | 3821 | py_only : bool (default False) |
|
3794 | 3822 | Only try to fetch python code, do not try alternative methods to decode file |
|
3795 | 3823 | if unicode fails. |
|
3796 | 3824 | |
|
3797 | 3825 | Returns |
|
3798 | 3826 | ------- |
|
3799 | 3827 | A string of code. |
|
3800 | 3828 | |
|
3801 | 3829 | ValueError is raised if nothing is found, and TypeError if it evaluates |
|
3802 | 3830 | to an object of another type. In each case, .args[0] is a printable |
|
3803 | 3831 | message. |
|
3804 | 3832 | """ |
|
3805 | 3833 | code = self.extract_input_lines(target, raw=raw) # Grab history |
|
3806 | 3834 | if code: |
|
3807 | 3835 | return code |
|
3808 | 3836 | try: |
|
3809 | 3837 | if target.startswith(('http://', 'https://')): |
|
3810 | 3838 | return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie) |
|
3811 | 3839 | except UnicodeDecodeError: |
|
3812 | 3840 | if not py_only : |
|
3813 | 3841 | # Deferred import |
|
3814 | 3842 | from urllib.request import urlopen |
|
3815 | 3843 | response = urlopen(target) |
|
3816 | 3844 | return response.read().decode('latin1') |
|
3817 | 3845 | raise ValueError(("'%s' seem to be unreadable.") % target) |
|
3818 | 3846 | |
|
3819 | 3847 | potential_target = [target] |
|
3820 | 3848 | try : |
|
3821 | 3849 | potential_target.insert(0,get_py_filename(target)) |
|
3822 | 3850 | except IOError: |
|
3823 | 3851 | pass |
|
3824 | 3852 | |
|
3825 | 3853 | for tgt in potential_target : |
|
3826 | 3854 | if os.path.isfile(tgt): # Read file |
|
3827 | 3855 | try : |
|
3828 | 3856 | return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie) |
|
3829 | 3857 | except UnicodeDecodeError : |
|
3830 | 3858 | if not py_only : |
|
3831 | 3859 | with io_open(tgt,'r', encoding='latin1') as f : |
|
3832 | 3860 | return f.read() |
|
3833 | 3861 | raise ValueError(("'%s' seem to be unreadable.") % target) |
|
3834 | 3862 | elif os.path.isdir(os.path.expanduser(tgt)): |
|
3835 | 3863 | raise ValueError("'%s' is a directory, not a regular file." % target) |
|
3836 | 3864 | |
|
3837 | 3865 | if search_ns: |
|
3838 | 3866 | # Inspect namespace to load object source |
|
3839 | 3867 | object_info = self.object_inspect(target, detail_level=1) |
|
3840 | 3868 | if object_info['found'] and object_info['source']: |
|
3841 | 3869 | return object_info['source'] |
|
3842 | 3870 | |
|
3843 | 3871 | try: # User namespace |
|
3844 | 3872 | codeobj = eval(target, self.user_ns) |
|
3845 | 3873 | except Exception: |
|
3846 | 3874 | raise ValueError(("'%s' was not found in history, as a file, url, " |
|
3847 | 3875 | "nor in the user namespace.") % target) |
|
3848 | 3876 | |
|
3849 | 3877 | if isinstance(codeobj, str): |
|
3850 | 3878 | return codeobj |
|
3851 | 3879 | elif isinstance(codeobj, Macro): |
|
3852 | 3880 | return codeobj.value |
|
3853 | 3881 | |
|
3854 | 3882 | raise TypeError("%s is neither a string nor a macro." % target, |
|
3855 | 3883 | codeobj) |
|
3856 | 3884 | |
|
3857 | 3885 | #------------------------------------------------------------------------- |
|
3858 | 3886 | # Things related to IPython exiting |
|
3859 | 3887 | #------------------------------------------------------------------------- |
|
3860 | 3888 | def atexit_operations(self): |
|
3861 | 3889 | """This will be executed at the time of exit. |
|
3862 | 3890 | |
|
3863 | 3891 | Cleanup operations and saving of persistent data that is done |
|
3864 | 3892 | unconditionally by IPython should be performed here. |
|
3865 | 3893 | |
|
3866 | 3894 | For things that may depend on startup flags or platform specifics (such |
|
3867 | 3895 | as having readline or not), register a separate atexit function in the |
|
3868 | 3896 | code that has the appropriate information, rather than trying to |
|
3869 | 3897 | clutter |
|
3870 | 3898 | """ |
|
3871 | 3899 | # Close the history session (this stores the end time and line count) |
|
3872 | 3900 | # this must be *before* the tempfile cleanup, in case of temporary |
|
3873 | 3901 | # history db |
|
3874 | 3902 | self.history_manager.end_session() |
|
3875 | 3903 | |
|
3876 | 3904 | # Cleanup all tempfiles and folders left around |
|
3877 | 3905 | for tfile in self.tempfiles: |
|
3878 | 3906 | try: |
|
3879 | 3907 | os.unlink(tfile) |
|
3880 | 3908 | except OSError: |
|
3881 | 3909 | pass |
|
3882 | 3910 | |
|
3883 | 3911 | for tdir in self.tempdirs: |
|
3884 | 3912 | try: |
|
3885 | 3913 | os.rmdir(tdir) |
|
3886 | 3914 | except OSError: |
|
3887 | 3915 | pass |
|
3888 | 3916 | |
|
3889 | 3917 | # Clear all user namespaces to release all references cleanly. |
|
3890 | 3918 | self.reset(new_session=False) |
|
3891 | 3919 | |
|
3892 | 3920 | # Run user hooks |
|
3893 | 3921 | self.hooks.shutdown_hook() |
|
3894 | 3922 | |
|
3895 | 3923 | def cleanup(self): |
|
3896 | 3924 | self.restore_sys_module_state() |
|
3897 | 3925 | |
|
3898 | 3926 | |
|
3899 | 3927 | # Overridden in terminal subclass to change prompts |
|
3900 | 3928 | def switch_doctest_mode(self, mode): |
|
3901 | 3929 | pass |
|
3902 | 3930 | |
|
3903 | 3931 | |
|
3904 | 3932 | class InteractiveShellABC(metaclass=abc.ABCMeta): |
|
3905 | 3933 | """An abstract base class for InteractiveShell.""" |
|
3906 | 3934 | |
|
3907 | 3935 | InteractiveShellABC.register(InteractiveShell) |
@@ -1,382 +1,382 b'' | |||
|
1 | 1 | #!/usr/bin/env python |
|
2 | 2 | # encoding: utf-8 |
|
3 | 3 | """ |
|
4 |
The :class:`~ |
|
|
4 | The :class:`~traitlets.config.application.Application` object for the command | |
|
5 | 5 | line :command:`ipython` program. |
|
6 | 6 | """ |
|
7 | 7 | |
|
8 | 8 | # Copyright (c) IPython Development Team. |
|
9 | 9 | # Distributed under the terms of the Modified BSD License. |
|
10 | 10 | |
|
11 | 11 | |
|
12 | 12 | import logging |
|
13 | 13 | import os |
|
14 | 14 | import sys |
|
15 | 15 | import warnings |
|
16 | 16 | |
|
17 | 17 | from traitlets.config.loader import Config |
|
18 | 18 | from traitlets.config.application import boolean_flag, catch_config_error |
|
19 | 19 | from IPython.core import release |
|
20 | 20 | from IPython.core import usage |
|
21 | 21 | from IPython.core.completer import IPCompleter |
|
22 | 22 | from IPython.core.crashhandler import CrashHandler |
|
23 | 23 | from IPython.core.formatters import PlainTextFormatter |
|
24 | 24 | from IPython.core.history import HistoryManager |
|
25 | 25 | from IPython.core.application import ( |
|
26 | 26 | ProfileDir, BaseIPythonApplication, base_flags, base_aliases |
|
27 | 27 | ) |
|
28 | 28 | from IPython.core.magic import MagicsManager |
|
29 | 29 | from IPython.core.magics import ( |
|
30 | 30 | ScriptMagics, LoggingMagics |
|
31 | 31 | ) |
|
32 | 32 | from IPython.core.shellapp import ( |
|
33 | 33 | InteractiveShellApp, shell_flags, shell_aliases |
|
34 | 34 | ) |
|
35 | 35 | from IPython.extensions.storemagic import StoreMagics |
|
36 | 36 | from .interactiveshell import TerminalInteractiveShell |
|
37 | 37 | from IPython.paths import get_ipython_dir |
|
38 | 38 | from traitlets import ( |
|
39 | 39 | Bool, List, default, observe, Type |
|
40 | 40 | ) |
|
41 | 41 | |
|
42 | 42 | #----------------------------------------------------------------------------- |
|
43 | 43 | # Globals, utilities and helpers |
|
44 | 44 | #----------------------------------------------------------------------------- |
|
45 | 45 | |
|
46 | 46 | _examples = """ |
|
47 | 47 | ipython --matplotlib # enable matplotlib integration |
|
48 | 48 | ipython --matplotlib=qt # enable matplotlib integration with qt4 backend |
|
49 | 49 | |
|
50 | 50 | ipython --log-level=DEBUG # set logging to DEBUG |
|
51 | 51 | ipython --profile=foo # start with profile foo |
|
52 | 52 | |
|
53 | 53 | ipython profile create foo # create profile foo w/ default config files |
|
54 | 54 | ipython help profile # show the help for the profile subcmd |
|
55 | 55 | |
|
56 | 56 | ipython locate # print the path to the IPython directory |
|
57 | 57 | ipython locate profile foo # print the path to the directory for profile `foo` |
|
58 | 58 | """ |
|
59 | 59 | |
|
60 | 60 | #----------------------------------------------------------------------------- |
|
61 | 61 | # Crash handler for this application |
|
62 | 62 | #----------------------------------------------------------------------------- |
|
63 | 63 | |
|
64 | 64 | class IPAppCrashHandler(CrashHandler): |
|
65 | 65 | """sys.excepthook for IPython itself, leaves a detailed report on disk.""" |
|
66 | 66 | |
|
67 | 67 | def __init__(self, app): |
|
68 | 68 | contact_name = release.author |
|
69 | 69 | contact_email = release.author_email |
|
70 | 70 | bug_tracker = 'https://github.com/ipython/ipython/issues' |
|
71 | 71 | super(IPAppCrashHandler,self).__init__( |
|
72 | 72 | app, contact_name, contact_email, bug_tracker |
|
73 | 73 | ) |
|
74 | 74 | |
|
75 | 75 | def make_report(self,traceback): |
|
76 | 76 | """Return a string containing a crash report.""" |
|
77 | 77 | |
|
78 | 78 | sec_sep = self.section_sep |
|
79 | 79 | # Start with parent report |
|
80 | 80 | report = [super(IPAppCrashHandler, self).make_report(traceback)] |
|
81 | 81 | # Add interactive-specific info we may have |
|
82 | 82 | rpt_add = report.append |
|
83 | 83 | try: |
|
84 | 84 | rpt_add(sec_sep+"History of session input:") |
|
85 | 85 | for line in self.app.shell.user_ns['_ih']: |
|
86 | 86 | rpt_add(line) |
|
87 | 87 | rpt_add('\n*** Last line of input (may not be in above history):\n') |
|
88 | 88 | rpt_add(self.app.shell._last_input_line+'\n') |
|
89 | 89 | except: |
|
90 | 90 | pass |
|
91 | 91 | |
|
92 | 92 | return ''.join(report) |
|
93 | 93 | |
|
94 | 94 | #----------------------------------------------------------------------------- |
|
95 | 95 | # Aliases and Flags |
|
96 | 96 | #----------------------------------------------------------------------------- |
|
97 | 97 | flags = dict(base_flags) |
|
98 | 98 | flags.update(shell_flags) |
|
99 | 99 | frontend_flags = {} |
|
100 | 100 | addflag = lambda *args: frontend_flags.update(boolean_flag(*args)) |
|
101 | 101 | addflag('autoedit-syntax', 'TerminalInteractiveShell.autoedit_syntax', |
|
102 | 102 | 'Turn on auto editing of files with syntax errors.', |
|
103 | 103 | 'Turn off auto editing of files with syntax errors.' |
|
104 | 104 | ) |
|
105 | 105 | addflag('simple-prompt', 'TerminalInteractiveShell.simple_prompt', |
|
106 | 106 | "Force simple minimal prompt using `raw_input`", |
|
107 | 107 | "Use a rich interactive prompt with prompt_toolkit", |
|
108 | 108 | ) |
|
109 | 109 | |
|
110 | 110 | addflag('banner', 'TerminalIPythonApp.display_banner', |
|
111 | 111 | "Display a banner upon starting IPython.", |
|
112 | 112 | "Don't display a banner upon starting IPython." |
|
113 | 113 | ) |
|
114 | 114 | addflag('confirm-exit', 'TerminalInteractiveShell.confirm_exit', |
|
115 | 115 | """Set to confirm when you try to exit IPython with an EOF (Control-D |
|
116 | 116 | in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit', |
|
117 | 117 | you can force a direct exit without any confirmation.""", |
|
118 | 118 | "Don't prompt the user when exiting." |
|
119 | 119 | ) |
|
120 | 120 | addflag('term-title', 'TerminalInteractiveShell.term_title', |
|
121 | 121 | "Enable auto setting the terminal title.", |
|
122 | 122 | "Disable auto setting the terminal title." |
|
123 | 123 | ) |
|
124 | 124 | classic_config = Config() |
|
125 | 125 | classic_config.InteractiveShell.cache_size = 0 |
|
126 | 126 | classic_config.PlainTextFormatter.pprint = False |
|
127 | 127 | classic_config.TerminalInteractiveShell.prompts_class='IPython.terminal.prompts.ClassicPrompts' |
|
128 | 128 | classic_config.InteractiveShell.separate_in = '' |
|
129 | 129 | classic_config.InteractiveShell.separate_out = '' |
|
130 | 130 | classic_config.InteractiveShell.separate_out2 = '' |
|
131 | 131 | classic_config.InteractiveShell.colors = 'NoColor' |
|
132 | 132 | classic_config.InteractiveShell.xmode = 'Plain' |
|
133 | 133 | |
|
134 | 134 | frontend_flags['classic']=( |
|
135 | 135 | classic_config, |
|
136 | 136 | "Gives IPython a similar feel to the classic Python prompt." |
|
137 | 137 | ) |
|
138 | 138 | # # log doesn't make so much sense this way anymore |
|
139 | 139 | # paa('--log','-l', |
|
140 | 140 | # action='store_true', dest='InteractiveShell.logstart', |
|
141 | 141 | # help="Start logging to the default log file (./ipython_log.py).") |
|
142 | 142 | # |
|
143 | 143 | # # quick is harder to implement |
|
144 | 144 | frontend_flags['quick']=( |
|
145 | 145 | {'TerminalIPythonApp' : {'quick' : True}}, |
|
146 | 146 | "Enable quick startup with no config files." |
|
147 | 147 | ) |
|
148 | 148 | |
|
149 | 149 | frontend_flags['i'] = ( |
|
150 | 150 | {'TerminalIPythonApp' : {'force_interact' : True}}, |
|
151 | 151 | """If running code from the command line, become interactive afterwards. |
|
152 | 152 | It is often useful to follow this with `--` to treat remaining flags as |
|
153 | 153 | script arguments. |
|
154 | 154 | """ |
|
155 | 155 | ) |
|
156 | 156 | flags.update(frontend_flags) |
|
157 | 157 | |
|
158 | 158 | aliases = dict(base_aliases) |
|
159 | 159 | aliases.update(shell_aliases) |
|
160 | 160 | |
|
161 | 161 | #----------------------------------------------------------------------------- |
|
162 | 162 | # Main classes and functions |
|
163 | 163 | #----------------------------------------------------------------------------- |
|
164 | 164 | |
|
165 | 165 | |
|
166 | 166 | class LocateIPythonApp(BaseIPythonApplication): |
|
167 | 167 | description = """print the path to the IPython dir""" |
|
168 | 168 | subcommands = dict( |
|
169 | 169 | profile=('IPython.core.profileapp.ProfileLocate', |
|
170 | 170 | "print the path to an IPython profile directory", |
|
171 | 171 | ), |
|
172 | 172 | ) |
|
173 | 173 | def start(self): |
|
174 | 174 | if self.subapp is not None: |
|
175 | 175 | return self.subapp.start() |
|
176 | 176 | else: |
|
177 | 177 | print(self.ipython_dir) |
|
178 | 178 | |
|
179 | 179 | |
|
180 | 180 | class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp): |
|
181 | 181 | name = u'ipython' |
|
182 | 182 | description = usage.cl_usage |
|
183 | 183 | crash_handler_class = IPAppCrashHandler |
|
184 | 184 | examples = _examples |
|
185 | 185 | |
|
186 | 186 | flags = flags |
|
187 | 187 | aliases = aliases |
|
188 | 188 | classes = List() |
|
189 | 189 | |
|
190 | 190 | interactive_shell_class = Type( |
|
191 | 191 | klass=object, # use default_value otherwise which only allow subclasses. |
|
192 | 192 | default_value=TerminalInteractiveShell, |
|
193 | 193 | help="Class to use to instantiate the TerminalInteractiveShell object. Useful for custom Frontends" |
|
194 | 194 | ).tag(config=True) |
|
195 | 195 | |
|
196 | 196 | @default('classes') |
|
197 | 197 | def _classes_default(self): |
|
198 | 198 | """This has to be in a method, for TerminalIPythonApp to be available.""" |
|
199 | 199 | return [ |
|
200 | 200 | InteractiveShellApp, # ShellApp comes before TerminalApp, because |
|
201 | 201 | self.__class__, # it will also affect subclasses (e.g. QtConsole) |
|
202 | 202 | TerminalInteractiveShell, |
|
203 | 203 | HistoryManager, |
|
204 | 204 | MagicsManager, |
|
205 | 205 | ProfileDir, |
|
206 | 206 | PlainTextFormatter, |
|
207 | 207 | IPCompleter, |
|
208 | 208 | ScriptMagics, |
|
209 | 209 | LoggingMagics, |
|
210 | 210 | StoreMagics, |
|
211 | 211 | ] |
|
212 | 212 | |
|
213 | 213 | deprecated_subcommands = dict( |
|
214 | 214 | qtconsole=('qtconsole.qtconsoleapp.JupyterQtConsoleApp', |
|
215 | 215 | """DEPRECATED, Will be removed in IPython 6.0 : Launch the Jupyter Qt Console.""" |
|
216 | 216 | ), |
|
217 | 217 | notebook=('notebook.notebookapp.NotebookApp', |
|
218 | 218 | """DEPRECATED, Will be removed in IPython 6.0 : Launch the Jupyter HTML Notebook Server.""" |
|
219 | 219 | ), |
|
220 | 220 | console=('jupyter_console.app.ZMQTerminalIPythonApp', |
|
221 | 221 | """DEPRECATED, Will be removed in IPython 6.0 : Launch the Jupyter terminal-based Console.""" |
|
222 | 222 | ), |
|
223 | 223 | nbconvert=('nbconvert.nbconvertapp.NbConvertApp', |
|
224 | 224 | "DEPRECATED, Will be removed in IPython 6.0 : Convert notebooks to/from other formats." |
|
225 | 225 | ), |
|
226 | 226 | trust=('nbformat.sign.TrustNotebookApp', |
|
227 | 227 | "DEPRECATED, Will be removed in IPython 6.0 : Sign notebooks to trust their potentially unsafe contents at load." |
|
228 | 228 | ), |
|
229 | 229 | kernelspec=('jupyter_client.kernelspecapp.KernelSpecApp', |
|
230 | 230 | "DEPRECATED, Will be removed in IPython 6.0 : Manage Jupyter kernel specifications." |
|
231 | 231 | ), |
|
232 | 232 | ) |
|
233 | 233 | subcommands = dict( |
|
234 | 234 | profile = ("IPython.core.profileapp.ProfileApp", |
|
235 | 235 | "Create and manage IPython profiles." |
|
236 | 236 | ), |
|
237 | 237 | kernel = ("ipykernel.kernelapp.IPKernelApp", |
|
238 | 238 | "Start a kernel without an attached frontend." |
|
239 | 239 | ), |
|
240 | 240 | locate=('IPython.terminal.ipapp.LocateIPythonApp', |
|
241 | 241 | LocateIPythonApp.description |
|
242 | 242 | ), |
|
243 | 243 | history=('IPython.core.historyapp.HistoryApp', |
|
244 | 244 | "Manage the IPython history database." |
|
245 | 245 | ), |
|
246 | 246 | ) |
|
247 | 247 | deprecated_subcommands['install-nbextension'] = ( |
|
248 | 248 | "notebook.nbextensions.InstallNBExtensionApp", |
|
249 | 249 | "DEPRECATED, Will be removed in IPython 6.0 : Install Jupyter notebook extension files" |
|
250 | 250 | ) |
|
251 | 251 | subcommands.update(deprecated_subcommands) |
|
252 | 252 | |
|
253 | 253 | # *do* autocreate requested profile, but don't create the config file. |
|
254 | 254 | auto_create=Bool(True) |
|
255 | 255 | # configurables |
|
256 | 256 | quick = Bool(False, |
|
257 | 257 | help="""Start IPython quickly by skipping the loading of config files.""" |
|
258 | 258 | ).tag(config=True) |
|
259 | 259 | @observe('quick') |
|
260 | 260 | def _quick_changed(self, change): |
|
261 | 261 | if change['new']: |
|
262 | 262 | self.load_config_file = lambda *a, **kw: None |
|
263 | 263 | |
|
264 | 264 | display_banner = Bool(True, |
|
265 | 265 | help="Whether to display a banner upon starting IPython." |
|
266 | 266 | ).tag(config=True) |
|
267 | 267 | |
|
268 | 268 | # if there is code of files to run from the cmd line, don't interact |
|
269 | 269 | # unless the --i flag (App.force_interact) is true. |
|
270 | 270 | force_interact = Bool(False, |
|
271 | 271 | help="""If a command or file is given via the command-line, |
|
272 | 272 | e.g. 'ipython foo.py', start an interactive shell after executing the |
|
273 | 273 | file or command.""" |
|
274 | 274 | ).tag(config=True) |
|
275 | 275 | @observe('force_interact') |
|
276 | 276 | def _force_interact_changed(self, change): |
|
277 | 277 | if change['new']: |
|
278 | 278 | self.interact = True |
|
279 | 279 | |
|
280 | 280 | @observe('file_to_run', 'code_to_run', 'module_to_run') |
|
281 | 281 | def _file_to_run_changed(self, change): |
|
282 | 282 | new = change['new'] |
|
283 | 283 | if new: |
|
284 | 284 | self.something_to_run = True |
|
285 | 285 | if new and not self.force_interact: |
|
286 | 286 | self.interact = False |
|
287 | 287 | |
|
288 | 288 | # internal, not-configurable |
|
289 | 289 | something_to_run=Bool(False) |
|
290 | 290 | |
|
291 | 291 | def parse_command_line(self, argv=None): |
|
292 | 292 | """override to allow old '-pylab' flag with deprecation warning""" |
|
293 | 293 | |
|
294 | 294 | argv = sys.argv[1:] if argv is None else argv |
|
295 | 295 | |
|
296 | 296 | if '-pylab' in argv: |
|
297 | 297 | # deprecated `-pylab` given, |
|
298 | 298 | # warn and transform into current syntax |
|
299 | 299 | argv = argv[:] # copy, don't clobber |
|
300 | 300 | idx = argv.index('-pylab') |
|
301 | 301 | warnings.warn("`-pylab` flag has been deprecated.\n" |
|
302 | 302 | " Use `--matplotlib <backend>` and import pylab manually.") |
|
303 | 303 | argv[idx] = '--pylab' |
|
304 | 304 | |
|
305 | 305 | return super(TerminalIPythonApp, self).parse_command_line(argv) |
|
306 | 306 | |
|
307 | 307 | @catch_config_error |
|
308 | 308 | def initialize(self, argv=None): |
|
309 | 309 | """Do actions after construct, but before starting the app.""" |
|
310 | 310 | super(TerminalIPythonApp, self).initialize(argv) |
|
311 | 311 | if self.subapp is not None: |
|
312 | 312 | # don't bother initializing further, starting subapp |
|
313 | 313 | return |
|
314 | 314 | # print self.extra_args |
|
315 | 315 | if self.extra_args and not self.something_to_run: |
|
316 | 316 | self.file_to_run = self.extra_args[0] |
|
317 | 317 | self.init_path() |
|
318 | 318 | # create the shell |
|
319 | 319 | self.init_shell() |
|
320 | 320 | # and draw the banner |
|
321 | 321 | self.init_banner() |
|
322 | 322 | # Now a variety of things that happen after the banner is printed. |
|
323 | 323 | self.init_gui_pylab() |
|
324 | 324 | self.init_extensions() |
|
325 | 325 | self.init_code() |
|
326 | 326 | |
|
327 | 327 | def init_shell(self): |
|
328 | 328 | """initialize the InteractiveShell instance""" |
|
329 | 329 | # Create an InteractiveShell instance. |
|
330 | 330 | # shell.display_banner should always be False for the terminal |
|
331 | 331 | # based app, because we call shell.show_banner() by hand below |
|
332 | 332 | # so the banner shows *before* all extension loading stuff. |
|
333 | 333 | self.shell = self.interactive_shell_class.instance(parent=self, |
|
334 | 334 | profile_dir=self.profile_dir, |
|
335 | 335 | ipython_dir=self.ipython_dir, user_ns=self.user_ns) |
|
336 | 336 | self.shell.configurables.append(self) |
|
337 | 337 | |
|
338 | 338 | def init_banner(self): |
|
339 | 339 | """optionally display the banner""" |
|
340 | 340 | if self.display_banner and self.interact: |
|
341 | 341 | self.shell.show_banner() |
|
342 | 342 | # Make sure there is a space below the banner. |
|
343 | 343 | if self.log_level <= logging.INFO: print() |
|
344 | 344 | |
|
345 | 345 | def _pylab_changed(self, name, old, new): |
|
346 | 346 | """Replace --pylab='inline' with --pylab='auto'""" |
|
347 | 347 | if new == 'inline': |
|
348 | 348 | warnings.warn("'inline' not available as pylab backend, " |
|
349 | 349 | "using 'auto' instead.") |
|
350 | 350 | self.pylab = 'auto' |
|
351 | 351 | |
|
352 | 352 | def start(self): |
|
353 | 353 | if self.subapp is not None: |
|
354 | 354 | return self.subapp.start() |
|
355 | 355 | # perform any prexec steps: |
|
356 | 356 | if self.interact: |
|
357 | 357 | self.log.debug("Starting IPython's mainloop...") |
|
358 | 358 | self.shell.mainloop() |
|
359 | 359 | else: |
|
360 | 360 | self.log.debug("IPython not interactive...") |
|
361 | 361 | if not self.shell.last_execution_succeeded: |
|
362 | 362 | sys.exit(1) |
|
363 | 363 | |
|
364 | 364 | def load_default_config(ipython_dir=None): |
|
365 | 365 | """Load the default config file from the default ipython_dir. |
|
366 | 366 | |
|
367 | 367 | This is useful for embedded shells. |
|
368 | 368 | """ |
|
369 | 369 | if ipython_dir is None: |
|
370 | 370 | ipython_dir = get_ipython_dir() |
|
371 | 371 | |
|
372 | 372 | profile_dir = os.path.join(ipython_dir, 'profile_default') |
|
373 | 373 | app = TerminalIPythonApp() |
|
374 | 374 | app.config_file_paths.append(profile_dir) |
|
375 | 375 | app.load_config_file() |
|
376 | 376 | return app.config |
|
377 | 377 | |
|
378 | 378 | launch_new_instance = TerminalIPythonApp.launch_instance |
|
379 | 379 | |
|
380 | 380 | |
|
381 | 381 | if __name__ == '__main__': |
|
382 | 382 | launch_new_instance() |
@@ -1,99 +1,113 b'' | |||
|
1 | 1 | .. _events: |
|
2 | 2 | .. _callbacks: |
|
3 | 3 | |
|
4 | 4 | ============== |
|
5 | 5 | IPython Events |
|
6 | 6 | ============== |
|
7 | 7 | |
|
8 | 8 | Extension code can register callbacks functions which will be called on specific |
|
9 | 9 | events within the IPython code. You can see the current list of available |
|
10 | 10 | callbacks, and the parameters that will be passed with each, in the callback |
|
11 | 11 | prototype functions defined in :mod:`IPython.core.events`. |
|
12 | 12 | |
|
13 | 13 | To register callbacks, use :meth:`IPython.core.events.EventManager.register`. |
|
14 | 14 | For example:: |
|
15 | 15 | |
|
16 | 16 | class VarWatcher(object): |
|
17 | 17 | def __init__(self, ip): |
|
18 | 18 | self.shell = ip |
|
19 | 19 | self.last_x = None |
|
20 | 20 | |
|
21 | 21 | def pre_execute(self): |
|
22 | 22 | self.last_x = self.shell.user_ns.get('x', None) |
|
23 | 23 | |
|
24 | 24 | def pre_run_cell(self, info): |
|
25 |
print(' |
|
|
25 | print('info.raw_cell =', info.raw_cell) | |
|
26 | print('info.store_history =', info.store_history) | |
|
27 | print('info.silent =', info.silent) | |
|
28 | print('info.shell_futures =', info.shell_futures) | |
|
29 | print('info.cell_id =', info.cell_id) | |
|
30 | print(dir(info)) | |
|
26 | 31 | |
|
27 | 32 | def post_execute(self): |
|
28 | 33 | if self.shell.user_ns.get('x', None) != self.last_x: |
|
29 | 34 | print("x changed!") |
|
30 | 35 | |
|
31 | 36 | def post_run_cell(self, result): |
|
32 | print('Cell code: "%s"' % result.info.raw_cell) | |
|
33 |
if result.error_before_exec |
|
|
34 |
|
|
|
37 | print('result.execution_count = ', result.execution_count) | |
|
38 | print('result.error_before_exec = ', result.error_before_exec) | |
|
39 | print('result.error_in_exec = ', result.error_in_exec) | |
|
40 | print('result.info = ', result.info) | |
|
41 | print('result.result = ', result.result) | |
|
35 | 42 | |
|
36 | 43 | def load_ipython_extension(ip): |
|
37 | 44 | vw = VarWatcher(ip) |
|
38 | 45 | ip.events.register('pre_execute', vw.pre_execute) |
|
39 | 46 | ip.events.register('pre_run_cell', vw.pre_run_cell) |
|
40 | 47 | ip.events.register('post_execute', vw.post_execute) |
|
41 | 48 | ip.events.register('post_run_cell', vw.post_run_cell) |
|
42 | 49 | |
|
50 | .. versionadded:: 8.3 | |
|
51 | ||
|
52 | Since IPython 8.3 and ipykernel 6.12.1, the ``info`` objects in the callback | |
|
53 | now have a the ``cell_id`` that will be set to the value sent by the | |
|
54 | frontened, when those send it. | |
|
55 | ||
|
56 | ||
|
43 | 57 | |
|
44 | 58 | Events |
|
45 | 59 | ====== |
|
46 | 60 | |
|
47 | 61 | These are the events IPython will emit. Callbacks will be passed no arguments, unless otherwise specified. |
|
48 | 62 | |
|
49 | 63 | shell_initialized |
|
50 | 64 | ----------------- |
|
51 | 65 | |
|
52 | 66 | .. code-block:: python |
|
53 | 67 | |
|
54 | 68 | def shell_initialized(ipython): |
|
55 | 69 | ... |
|
56 | 70 | |
|
57 | 71 | This event is triggered only once, at the end of setting up IPython. |
|
58 | 72 | Extensions registered to load by default as part of configuration can use this to execute code to finalize setup. |
|
59 | 73 | Callbacks will be passed the InteractiveShell instance. |
|
60 | 74 | |
|
61 | 75 | pre_run_cell |
|
62 | 76 | ------------ |
|
63 | 77 | |
|
64 | 78 | ``pre_run_cell`` fires prior to interactive execution (e.g. a cell in a notebook). |
|
65 | 79 | It can be used to note the state prior to execution, and keep track of changes. |
|
66 | 80 | An object containing information used for the code execution is provided as an argument. |
|
67 | 81 | |
|
68 | 82 | pre_execute |
|
69 | 83 | ----------- |
|
70 | 84 | |
|
71 | 85 | ``pre_execute`` is like ``pre_run_cell``, but is triggered prior to *any* execution. |
|
72 | 86 | Sometimes code can be executed by libraries, etc. which |
|
73 | 87 | skipping the history/display mechanisms, in which cases ``pre_run_cell`` will not fire. |
|
74 | 88 | |
|
75 | 89 | post_run_cell |
|
76 | 90 | ------------- |
|
77 | 91 | |
|
78 | 92 | ``post_run_cell`` runs after interactive execution (e.g. a cell in a notebook). |
|
79 | 93 | It can be used to cleanup or notify or perform operations on any side effects produced during execution. |
|
80 | 94 | For instance, the inline matplotlib backend uses this event to display any figures created but not explicitly displayed during the course of the cell. |
|
81 | 95 | The object which will be returned as the execution result is provided as an |
|
82 | 96 | argument. |
|
83 | 97 | |
|
84 | 98 | post_execute |
|
85 | 99 | ------------ |
|
86 | 100 | |
|
87 | 101 | The same as ``pre_execute``, ``post_execute`` is like ``post_run_cell``, |
|
88 | 102 | but fires for *all* executions, not just interactive ones. |
|
89 | 103 | |
|
90 | 104 | |
|
91 | 105 | .. seealso:: |
|
92 | 106 | |
|
93 | 107 | Module :mod:`IPython.core.hooks` |
|
94 | 108 | The older 'hooks' system allows end users to customise some parts of |
|
95 | 109 | IPython's behaviour. |
|
96 | 110 | |
|
97 | 111 | :doc:`inputtransforms` |
|
98 | 112 | By registering input transformers that don't change code, you can monitor |
|
99 | 113 | what is being executed. |
General Comments 0
You need to be logged in to leave comments.
Login now