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