##// END OF EJS Templates
Remove unused IPython.utils.rlineimpl readline module...
Thomas Kluyver -
Show More
@@ -1,1243 +1,1239 b''
1 1 # encoding: utf-8
2 2 """Word completion for IPython.
3 3
4 4 This module started as fork of the rlcompleter module in the Python standard
5 5 library. The original enhancements made to rlcompleter have been sent
6 6 upstream and were accepted as of Python 2.3,
7 7
8 8 """
9 9
10 10 # Copyright (c) IPython Development Team.
11 11 # Distributed under the terms of the Modified BSD License.
12 12 #
13 13 # Some of this code originated from rlcompleter in the Python standard library
14 14 # Copyright (C) 2001 Python Software Foundation, www.python.org
15 15
16 16 from __future__ import print_function
17 17
18 18 import __main__
19 19 import glob
20 20 import inspect
21 21 import itertools
22 22 import keyword
23 23 import os
24 24 import re
25 25 import sys
26 26 import unicodedata
27 27 import string
28 import warnings
28 29
29 30 from traitlets.config.configurable import Configurable
30 31 from IPython.core.error import TryNext
31 32 from IPython.core.inputsplitter import ESC_MAGIC
32 33 from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol
33 34 from IPython.utils import generics
34 35 from IPython.utils.decorators import undoc
35 36 from IPython.utils.dir2 import dir2, get_real_method
36 37 from IPython.utils.process import arg_split
37 38 from IPython.utils.py3compat import builtin_mod, string_types, PY3, cast_unicode_py2
38 39 from traitlets import Bool, Enum, observe
39 40
40 41 from functools import wraps
41 42
42 43 #-----------------------------------------------------------------------------
43 44 # Globals
44 45 #-----------------------------------------------------------------------------
45 46
46 47 # Public API
47 48 __all__ = ['Completer','IPCompleter']
48 49
49 50 if sys.platform == 'win32':
50 51 PROTECTABLES = ' '
51 52 else:
52 53 PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&'
53 54
54 55
55 56 #-----------------------------------------------------------------------------
56 57 # Work around BUG decorators.
57 58 #-----------------------------------------------------------------------------
58 59
59 60 def _strip_single_trailing_space(complete):
60 61 """
61 62 This is a workaround for a weird IPython/Prompt_toolkit behavior,
62 63 that can be removed once we rely on a slightly more recent prompt_toolkit
63 64 version (likely > 1.0.3). So this can likely be removed in IPython 6.0
64 65
65 66 cf https://github.com/ipython/ipython/issues/9658
66 67 and https://github.com/jonathanslenders/python-prompt-toolkit/pull/328
67 68
68 69 The bug is due to the fact that in PTK the completer will reinvoke itself
69 70 after trying to completer to the longuest common prefix of all the
70 71 completions, unless only one completion is available.
71 72
72 73 This logic is faulty if the completion ends with space, which can happen in
73 74 case like::
74 75
75 76 from foo import im<ta>
76 77
77 78 which only matching completion is `import `. Note the leading space at the
78 79 end. So leaving a space at the end is a reasonable request, but for now
79 80 we'll strip it.
80 81 """
81 82
82 83 @wraps(complete)
83 84 def comp(*args, **kwargs):
84 85 text, matches = complete(*args, **kwargs)
85 86 if len(matches) == 1:
86 87 return text, [matches[0].rstrip()]
87 88 return text, matches
88 89
89 90 return comp
90 91
91 92
92 93
93 94 #-----------------------------------------------------------------------------
94 95 # Main functions and classes
95 96 #-----------------------------------------------------------------------------
96 97
97 98 def has_open_quotes(s):
98 99 """Return whether a string has open quotes.
99 100
100 101 This simply counts whether the number of quote characters of either type in
101 102 the string is odd.
102 103
103 104 Returns
104 105 -------
105 106 If there is an open quote, the quote character is returned. Else, return
106 107 False.
107 108 """
108 109 # We check " first, then ', so complex cases with nested quotes will get
109 110 # the " to take precedence.
110 111 if s.count('"') % 2:
111 112 return '"'
112 113 elif s.count("'") % 2:
113 114 return "'"
114 115 else:
115 116 return False
116 117
117 118
118 119 def protect_filename(s):
119 120 """Escape a string to protect certain characters."""
120 121 if set(s) & set(PROTECTABLES):
121 122 if sys.platform == "win32":
122 123 return '"' + s + '"'
123 124 else:
124 125 return "".join(("\\" + c if c in PROTECTABLES else c) for c in s)
125 126 else:
126 127 return s
127 128
128 129
129 130 def expand_user(path):
130 131 """Expand '~'-style usernames in strings.
131 132
132 133 This is similar to :func:`os.path.expanduser`, but it computes and returns
133 134 extra information that will be useful if the input was being used in
134 135 computing completions, and you wish to return the completions with the
135 136 original '~' instead of its expanded value.
136 137
137 138 Parameters
138 139 ----------
139 140 path : str
140 141 String to be expanded. If no ~ is present, the output is the same as the
141 142 input.
142 143
143 144 Returns
144 145 -------
145 146 newpath : str
146 147 Result of ~ expansion in the input path.
147 148 tilde_expand : bool
148 149 Whether any expansion was performed or not.
149 150 tilde_val : str
150 151 The value that ~ was replaced with.
151 152 """
152 153 # Default values
153 154 tilde_expand = False
154 155 tilde_val = ''
155 156 newpath = path
156 157
157 158 if path.startswith('~'):
158 159 tilde_expand = True
159 160 rest = len(path)-1
160 161 newpath = os.path.expanduser(path)
161 162 if rest:
162 163 tilde_val = newpath[:-rest]
163 164 else:
164 165 tilde_val = newpath
165 166
166 167 return newpath, tilde_expand, tilde_val
167 168
168 169
169 170 def compress_user(path, tilde_expand, tilde_val):
170 171 """Does the opposite of expand_user, with its outputs.
171 172 """
172 173 if tilde_expand:
173 174 return path.replace(tilde_val, '~')
174 175 else:
175 176 return path
176 177
177 178
178 179 def completions_sorting_key(word):
179 180 """key for sorting completions
180 181
181 182 This does several things:
182 183
183 184 - Lowercase all completions, so they are sorted alphabetically with
184 185 upper and lower case words mingled
185 186 - Demote any completions starting with underscores to the end
186 187 - Insert any %magic and %%cellmagic completions in the alphabetical order
187 188 by their name
188 189 """
189 190 # Case insensitive sort
190 191 word = word.lower()
191 192
192 193 prio1, prio2 = 0, 0
193 194
194 195 if word.startswith('__'):
195 196 prio1 = 2
196 197 elif word.startswith('_'):
197 198 prio1 = 1
198 199
199 200 if word.endswith('='):
200 201 prio1 = -1
201 202
202 203 if word.startswith('%%'):
203 204 # If there's another % in there, this is something else, so leave it alone
204 205 if not "%" in word[2:]:
205 206 word = word[2:]
206 207 prio2 = 2
207 208 elif word.startswith('%'):
208 209 if not "%" in word[1:]:
209 210 word = word[1:]
210 211 prio2 = 1
211 212
212 213 return prio1, word, prio2
213 214
214 215
215 216 @undoc
216 217 class Bunch(object): pass
217 218
218 219
219 220 if sys.platform == 'win32':
220 221 DELIMS = ' \t\n`!@#$^&*()=+[{]}|;\'",<>?'
221 222 else:
222 223 DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
223 224
224 225 GREEDY_DELIMS = ' =\r\n'
225 226
226 227
227 228 class CompletionSplitter(object):
228 229 """An object to split an input line in a manner similar to readline.
229 230
230 231 By having our own implementation, we can expose readline-like completion in
231 232 a uniform manner to all frontends. This object only needs to be given the
232 233 line of text to be split and the cursor position on said line, and it
233 234 returns the 'word' to be completed on at the cursor after splitting the
234 235 entire line.
235 236
236 237 What characters are used as splitting delimiters can be controlled by
237 238 setting the `delims` attribute (this is a property that internally
238 239 automatically builds the necessary regular expression)"""
239 240
240 241 # Private interface
241 242
242 243 # A string of delimiter characters. The default value makes sense for
243 244 # IPython's most typical usage patterns.
244 245 _delims = DELIMS
245 246
246 247 # The expression (a normal string) to be compiled into a regular expression
247 248 # for actual splitting. We store it as an attribute mostly for ease of
248 249 # debugging, since this type of code can be so tricky to debug.
249 250 _delim_expr = None
250 251
251 252 # The regular expression that does the actual splitting
252 253 _delim_re = None
253 254
254 255 def __init__(self, delims=None):
255 256 delims = CompletionSplitter._delims if delims is None else delims
256 257 self.delims = delims
257 258
258 259 @property
259 260 def delims(self):
260 261 """Return the string of delimiter characters."""
261 262 return self._delims
262 263
263 264 @delims.setter
264 265 def delims(self, delims):
265 266 """Set the delimiters for line splitting."""
266 267 expr = '[' + ''.join('\\'+ c for c in delims) + ']'
267 268 self._delim_re = re.compile(expr)
268 269 self._delims = delims
269 270 self._delim_expr = expr
270 271
271 272 def split_line(self, line, cursor_pos=None):
272 273 """Split a line of text with a cursor at the given position.
273 274 """
274 275 l = line if cursor_pos is None else line[:cursor_pos]
275 276 return self._delim_re.split(l)[-1]
276 277
277 278
278 279 class Completer(Configurable):
279 280
280 281 greedy = Bool(False,
281 282 help="""Activate greedy completion
282 283 PENDING DEPRECTION. this is now mostly taken care of with Jedi.
283 284
284 285 This will enable completion on elements of lists, results of function calls, etc.,
285 286 but can be unsafe because the code is actually evaluated on TAB.
286 287 """
287 288 ).tag(config=True)
288 289
289 290
290 291 def __init__(self, namespace=None, global_namespace=None, **kwargs):
291 292 """Create a new completer for the command line.
292 293
293 294 Completer(namespace=ns, global_namespace=ns2) -> completer instance.
294 295
295 296 If unspecified, the default namespace where completions are performed
296 297 is __main__ (technically, __main__.__dict__). Namespaces should be
297 298 given as dictionaries.
298 299
299 300 An optional second namespace can be given. This allows the completer
300 301 to handle cases where both the local and global scopes need to be
301 302 distinguished.
302 303
303 304 Completer instances should be used as the completion mechanism of
304 305 readline via the set_completer() call:
305 306
306 307 readline.set_completer(Completer(my_namespace).complete)
307 308 """
308 309
309 310 # Don't bind to namespace quite yet, but flag whether the user wants a
310 311 # specific namespace or to use __main__.__dict__. This will allow us
311 312 # to bind to __main__.__dict__ at completion time, not now.
312 313 if namespace is None:
313 314 self.use_main_ns = 1
314 315 else:
315 316 self.use_main_ns = 0
316 317 self.namespace = namespace
317 318
318 319 # The global namespace, if given, can be bound directly
319 320 if global_namespace is None:
320 321 self.global_namespace = {}
321 322 else:
322 323 self.global_namespace = global_namespace
323 324
324 325 super(Completer, self).__init__(**kwargs)
325 326
326 327 def complete(self, text, state):
327 328 """Return the next possible completion for 'text'.
328 329
329 330 This is called successively with state == 0, 1, 2, ... until it
330 331 returns None. The completion should begin with 'text'.
331 332
332 333 """
333 334 if self.use_main_ns:
334 335 self.namespace = __main__.__dict__
335 336
336 337 if state == 0:
337 338 if "." in text:
338 339 self.matches = self.attr_matches(text)
339 340 else:
340 341 self.matches = self.global_matches(text)
341 342 try:
342 343 return self.matches[state]
343 344 except IndexError:
344 345 return None
345 346
346 347 def global_matches(self, text):
347 348 """Compute matches when text is a simple name.
348 349
349 350 Return a list of all keywords, built-in functions and names currently
350 351 defined in self.namespace or self.global_namespace that match.
351 352
352 353 """
353 354 matches = []
354 355 match_append = matches.append
355 356 n = len(text)
356 357 for lst in [keyword.kwlist,
357 358 builtin_mod.__dict__.keys(),
358 359 self.namespace.keys(),
359 360 self.global_namespace.keys()]:
360 361 for word in lst:
361 362 if word[:n] == text and word != "__builtins__":
362 363 match_append(word)
363 364 return [cast_unicode_py2(m) for m in matches]
364 365
365 366 def attr_matches(self, text):
366 367 """Compute matches when text contains a dot.
367 368
368 369 Assuming the text is of the form NAME.NAME....[NAME], and is
369 370 evaluatable in self.namespace or self.global_namespace, it will be
370 371 evaluated and its attributes (as revealed by dir()) are used as
371 372 possible completions. (For class instances, class members are are
372 373 also considered.)
373 374
374 375 WARNING: this can still invoke arbitrary C code, if an object
375 376 with a __getattr__ hook is evaluated.
376 377
377 378 """
378 379
379 380 # Another option, seems to work great. Catches things like ''.<tab>
380 381 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
381 382
382 383 if m:
383 384 expr, attr = m.group(1, 3)
384 385 elif self.greedy:
385 386 m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer)
386 387 if not m2:
387 388 return []
388 389 expr, attr = m2.group(1,2)
389 390 else:
390 391 return []
391 392
392 393 try:
393 394 obj = eval(expr, self.namespace)
394 395 except:
395 396 try:
396 397 obj = eval(expr, self.global_namespace)
397 398 except:
398 399 return []
399 400
400 401 if self.limit_to__all__ and hasattr(obj, '__all__'):
401 402 words = get__all__entries(obj)
402 403 else:
403 404 words = dir2(obj)
404 405
405 406 try:
406 407 words = generics.complete_object(obj, words)
407 408 except TryNext:
408 409 pass
409 410 except Exception:
410 411 # Silence errors from completion function
411 412 #raise # dbg
412 413 pass
413 414 # Build match list to return
414 415 n = len(attr)
415 416 return [u"%s.%s" % (expr, w) for w in words if w[:n] == attr ]
416 417
417 418
418 419 def get__all__entries(obj):
419 420 """returns the strings in the __all__ attribute"""
420 421 try:
421 422 words = getattr(obj, '__all__')
422 423 except:
423 424 return []
424 425
425 426 return [cast_unicode_py2(w) for w in words if isinstance(w, string_types)]
426 427
427 428
428 429 def match_dict_keys(keys, prefix, delims):
429 430 """Used by dict_key_matches, matching the prefix to a list of keys"""
430 431 if not prefix:
431 432 return None, 0, [repr(k) for k in keys
432 433 if isinstance(k, (string_types, bytes))]
433 434 quote_match = re.search('["\']', prefix)
434 435 quote = quote_match.group()
435 436 try:
436 437 prefix_str = eval(prefix + quote, {})
437 438 except Exception:
438 439 return None, 0, []
439 440
440 441 pattern = '[^' + ''.join('\\' + c for c in delims) + ']*$'
441 442 token_match = re.search(pattern, prefix, re.UNICODE)
442 443 token_start = token_match.start()
443 444 token_prefix = token_match.group()
444 445
445 446 # TODO: support bytes in Py3k
446 447 matched = []
447 448 for key in keys:
448 449 try:
449 450 if not key.startswith(prefix_str):
450 451 continue
451 452 except (AttributeError, TypeError, UnicodeError):
452 453 # Python 3+ TypeError on b'a'.startswith('a') or vice-versa
453 454 continue
454 455
455 456 # reformat remainder of key to begin with prefix
456 457 rem = key[len(prefix_str):]
457 458 # force repr wrapped in '
458 459 rem_repr = repr(rem + '"')
459 460 if rem_repr.startswith('u') and prefix[0] not in 'uU':
460 461 # Found key is unicode, but prefix is Py2 string.
461 462 # Therefore attempt to interpret key as string.
462 463 try:
463 464 rem_repr = repr(rem.encode('ascii') + '"')
464 465 except UnicodeEncodeError:
465 466 continue
466 467
467 468 rem_repr = rem_repr[1 + rem_repr.index("'"):-2]
468 469 if quote == '"':
469 470 # The entered prefix is quoted with ",
470 471 # but the match is quoted with '.
471 472 # A contained " hence needs escaping for comparison:
472 473 rem_repr = rem_repr.replace('"', '\\"')
473 474
474 475 # then reinsert prefix from start of token
475 476 matched.append('%s%s' % (token_prefix, rem_repr))
476 477 return quote, token_start, matched
477 478
478 479
479 480 def _safe_isinstance(obj, module, class_name):
480 481 """Checks if obj is an instance of module.class_name if loaded
481 482 """
482 483 return (module in sys.modules and
483 484 isinstance(obj, getattr(__import__(module), class_name)))
484 485
485 486
486 487 def back_unicode_name_matches(text):
487 488 u"""Match unicode characters back to unicode name
488 489
489 490 This does ☃ -> \\snowman
490 491
491 492 Note that snowman is not a valid python3 combining character but will be expanded.
492 493 Though it will not recombine back to the snowman character by the completion machinery.
493 494
494 495 This will not either back-complete standard sequences like \\n, \\b ...
495 496
496 497 Used on Python 3 only.
497 498 """
498 499 if len(text)<2:
499 500 return u'', ()
500 501 maybe_slash = text[-2]
501 502 if maybe_slash != '\\':
502 503 return u'', ()
503 504
504 505 char = text[-1]
505 506 # no expand on quote for completion in strings.
506 507 # nor backcomplete standard ascii keys
507 508 if char in string.ascii_letters or char in ['"',"'"]:
508 509 return u'', ()
509 510 try :
510 511 unic = unicodedata.name(char)
511 512 return '\\'+char,['\\'+unic]
512 513 except KeyError:
513 514 pass
514 515 return u'', ()
515 516
516 517 def back_latex_name_matches(text):
517 518 u"""Match latex characters back to unicode name
518 519
519 520 This does ->\\sqrt
520 521
521 522 Used on Python 3 only.
522 523 """
523 524 if len(text)<2:
524 525 return u'', ()
525 526 maybe_slash = text[-2]
526 527 if maybe_slash != '\\':
527 528 return u'', ()
528 529
529 530
530 531 char = text[-1]
531 532 # no expand on quote for completion in strings.
532 533 # nor backcomplete standard ascii keys
533 534 if char in string.ascii_letters or char in ['"',"'"]:
534 535 return u'', ()
535 536 try :
536 537 latex = reverse_latex_symbol[char]
537 538 # '\\' replace the \ as well
538 539 return '\\'+char,[latex]
539 540 except KeyError:
540 541 pass
541 542 return u'', ()
542 543
543 544
544 545 class IPCompleter(Completer):
545 546 """Extension of the completer class with IPython-specific features"""
546 547
547 548 @observe('greedy')
548 549 def _greedy_changed(self, change):
549 550 """update the splitter and readline delims when greedy is changed"""
550 551 if change['new']:
551 552 self.splitter.delims = GREEDY_DELIMS
552 553 else:
553 554 self.splitter.delims = DELIMS
554 555
555 556 if self.readline:
556 557 self.readline.set_completer_delims(self.splitter.delims)
557 558
558 559 merge_completions = Bool(True,
559 560 help="""Whether to merge completion results into a single list
560 561
561 562 If False, only the completion results from the first non-empty
562 563 completer will be returned.
563 564 """
564 565 ).tag(config=True)
565 566 omit__names = Enum((0,1,2), default_value=2,
566 567 help="""Instruct the completer to omit private method names
567 568
568 569 Specifically, when completing on ``object.<tab>``.
569 570
570 571 When 2 [default]: all names that start with '_' will be excluded.
571 572
572 573 When 1: all 'magic' names (``__foo__``) will be excluded.
573 574
574 575 When 0: nothing will be excluded.
575 576 """
576 577 ).tag(config=True)
577 578 limit_to__all__ = Bool(False,
578 579 help="""
579 580 DEPRECATED as of version 5.0.
580 581
581 582 Instruct the completer to use __all__ for the completion
582 583
583 584 Specifically, when completing on ``object.<tab>``.
584 585
585 586 When True: only those names in obj.__all__ will be included.
586 587
587 588 When False [default]: the __all__ attribute is ignored
588 589 """,
589 590 ).tag(config=True)
590 591
591 592 def __init__(self, shell=None, namespace=None, global_namespace=None,
592 use_readline=True, config=None, **kwargs):
593 use_readline=False, config=None, **kwargs):
593 594 """IPCompleter() -> completer
594 595
595 596 Return a completer object suitable for use by the readline library
596 597 via readline.set_completer().
597 598
598 599 Inputs:
599 600
600 601 - shell: a pointer to the ipython shell itself. This is needed
601 602 because this completer knows about magic functions, and those can
602 603 only be accessed via the ipython instance.
603 604
604 605 - namespace: an optional dict where completions are performed.
605 606
606 607 - global_namespace: secondary optional dict for completions, to
607 608 handle cases (such as IPython embedded inside functions) where
608 609 both Python scopes are visible.
609 610
610 611 use_readline : bool, optional
611 If true, use the readline library. This completer can still function
612 without readline, though in that case callers must provide some extra
613 information on each call about the current line."""
612 DEPRECATED, ignored.
613 """
614 614
615 615 self.magic_escape = ESC_MAGIC
616 616 self.splitter = CompletionSplitter()
617 617
618 # Readline configuration, only used by the rlcompleter method.
619 618 if use_readline:
620 # We store the right version of readline so that later code
621 import IPython.utils.rlineimpl as readline
622 self.readline = readline
623 else:
624 self.readline = None
619 warnings.warn('The use_readline parameter is deprecated since IPython 6.0.',
620 DeprecationWarning, stacklevel=2)
625 621
626 622 # _greedy_changed() depends on splitter and readline being defined:
627 623 Completer.__init__(self, namespace=namespace, global_namespace=global_namespace,
628 624 config=config, **kwargs)
629 625
630 626 # List where completion matches will be stored
631 627 self.matches = []
632 628 self.shell = shell
633 629 # Regexp to split filenames with spaces in them
634 630 self.space_name_re = re.compile(r'([^\\] )')
635 631 # Hold a local ref. to glob.glob for speed
636 632 self.glob = glob.glob
637 633
638 634 # Determine if we are running on 'dumb' terminals, like (X)Emacs
639 635 # buffers, to avoid completion problems.
640 636 term = os.environ.get('TERM','xterm')
641 637 self.dumb_terminal = term in ['dumb','emacs']
642 638
643 639 # Special handling of backslashes needed in win32 platforms
644 640 if sys.platform == "win32":
645 641 self.clean_glob = self._clean_glob_win32
646 642 else:
647 643 self.clean_glob = self._clean_glob
648 644
649 645 #regexp to parse docstring for function signature
650 646 self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
651 647 self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
652 648 #use this if positional argument name is also needed
653 649 #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)')
654 650
655 651 # All active matcher routines for completion
656 652 self.matchers = [
657 653 self.python_matches,
658 654 self.file_matches,
659 655 self.magic_matches,
660 656 self.python_func_kw_matches,
661 657 self.dict_key_matches,
662 658 ]
663 659
664 660 # This is set externally by InteractiveShell
665 661 self.custom_completers = None
666 662
667 663 def all_completions(self, text):
668 664 """
669 665 Wrapper around the complete method for the benefit of emacs.
670 666 """
671 667 return self.complete(text)[1]
672 668
673 669 def _clean_glob(self, text):
674 670 return self.glob("%s*" % text)
675 671
676 672 def _clean_glob_win32(self,text):
677 673 return [f.replace("\\","/")
678 674 for f in self.glob("%s*" % text)]
679 675
680 676 def file_matches(self, text):
681 677 """Match filenames, expanding ~USER type strings.
682 678
683 679 Most of the seemingly convoluted logic in this completer is an
684 680 attempt to handle filenames with spaces in them. And yet it's not
685 681 quite perfect, because Python's readline doesn't expose all of the
686 682 GNU readline details needed for this to be done correctly.
687 683
688 684 For a filename with a space in it, the printed completions will be
689 685 only the parts after what's already been typed (instead of the
690 686 full completions, as is normally done). I don't think with the
691 687 current (as of Python 2.3) Python readline it's possible to do
692 688 better."""
693 689
694 690 # chars that require escaping with backslash - i.e. chars
695 691 # that readline treats incorrectly as delimiters, but we
696 692 # don't want to treat as delimiters in filename matching
697 693 # when escaped with backslash
698 694 if text.startswith('!'):
699 695 text = text[1:]
700 696 text_prefix = u'!'
701 697 else:
702 698 text_prefix = u''
703 699
704 700 text_until_cursor = self.text_until_cursor
705 701 # track strings with open quotes
706 702 open_quotes = has_open_quotes(text_until_cursor)
707 703
708 704 if '(' in text_until_cursor or '[' in text_until_cursor:
709 705 lsplit = text
710 706 else:
711 707 try:
712 708 # arg_split ~ shlex.split, but with unicode bugs fixed by us
713 709 lsplit = arg_split(text_until_cursor)[-1]
714 710 except ValueError:
715 711 # typically an unmatched ", or backslash without escaped char.
716 712 if open_quotes:
717 713 lsplit = text_until_cursor.split(open_quotes)[-1]
718 714 else:
719 715 return []
720 716 except IndexError:
721 717 # tab pressed on empty line
722 718 lsplit = ""
723 719
724 720 if not open_quotes and lsplit != protect_filename(lsplit):
725 721 # if protectables are found, do matching on the whole escaped name
726 722 has_protectables = True
727 723 text0,text = text,lsplit
728 724 else:
729 725 has_protectables = False
730 726 text = os.path.expanduser(text)
731 727
732 728 if text == "":
733 729 return [text_prefix + cast_unicode_py2(protect_filename(f)) for f in self.glob("*")]
734 730
735 731 # Compute the matches from the filesystem
736 732 if sys.platform == 'win32':
737 733 m0 = self.clean_glob(text)
738 734 else:
739 735 m0 = self.clean_glob(text.replace('\\', ''))
740 736
741 737 if has_protectables:
742 738 # If we had protectables, we need to revert our changes to the
743 739 # beginning of filename so that we don't double-write the part
744 740 # of the filename we have so far
745 741 len_lsplit = len(lsplit)
746 742 matches = [text_prefix + text0 +
747 743 protect_filename(f[len_lsplit:]) for f in m0]
748 744 else:
749 745 if open_quotes:
750 746 # if we have a string with an open quote, we don't need to
751 747 # protect the names at all (and we _shouldn't_, as it
752 748 # would cause bugs when the filesystem call is made).
753 749 matches = m0
754 750 else:
755 751 matches = [text_prefix +
756 752 protect_filename(f) for f in m0]
757 753
758 754 # Mark directories in input list by appending '/' to their names.
759 755 return [cast_unicode_py2(x+'/') if os.path.isdir(x) else x for x in matches]
760 756
761 757 def magic_matches(self, text):
762 758 """Match magics"""
763 759 # Get all shell magics now rather than statically, so magics loaded at
764 760 # runtime show up too.
765 761 lsm = self.shell.magics_manager.lsmagic()
766 762 line_magics = lsm['line']
767 763 cell_magics = lsm['cell']
768 764 pre = self.magic_escape
769 765 pre2 = pre+pre
770 766
771 767 # Completion logic:
772 768 # - user gives %%: only do cell magics
773 769 # - user gives %: do both line and cell magics
774 770 # - no prefix: do both
775 771 # In other words, line magics are skipped if the user gives %% explicitly
776 772 bare_text = text.lstrip(pre)
777 773 comp = [ pre2+m for m in cell_magics if m.startswith(bare_text)]
778 774 if not text.startswith(pre2):
779 775 comp += [ pre+m for m in line_magics if m.startswith(bare_text)]
780 776 return [cast_unicode_py2(c) for c in comp]
781 777
782 778
783 779 def python_matches(self, text):
784 780 """Match attributes or global python names"""
785 781 if "." in text:
786 782 try:
787 783 matches = self.attr_matches(text)
788 784 if text.endswith('.') and self.omit__names:
789 785 if self.omit__names == 1:
790 786 # true if txt is _not_ a __ name, false otherwise:
791 787 no__name = (lambda txt:
792 788 re.match(r'.*\.__.*?__',txt) is None)
793 789 else:
794 790 # true if txt is _not_ a _ name, false otherwise:
795 791 no__name = (lambda txt:
796 792 re.match(r'\._.*?',txt[txt.rindex('.'):]) is None)
797 793 matches = filter(no__name, matches)
798 794 except NameError:
799 795 # catches <undefined attributes>.<tab>
800 796 matches = []
801 797 else:
802 798 matches = self.global_matches(text)
803 799 return matches
804 800
805 801 def _default_arguments_from_docstring(self, doc):
806 802 """Parse the first line of docstring for call signature.
807 803
808 804 Docstring should be of the form 'min(iterable[, key=func])\n'.
809 805 It can also parse cython docstring of the form
810 806 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'.
811 807 """
812 808 if doc is None:
813 809 return []
814 810
815 811 #care only the firstline
816 812 line = doc.lstrip().splitlines()[0]
817 813
818 814 #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
819 815 #'min(iterable[, key=func])\n' -> 'iterable[, key=func]'
820 816 sig = self.docstring_sig_re.search(line)
821 817 if sig is None:
822 818 return []
823 819 # iterable[, key=func]' -> ['iterable[' ,' key=func]']
824 820 sig = sig.groups()[0].split(',')
825 821 ret = []
826 822 for s in sig:
827 823 #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
828 824 ret += self.docstring_kwd_re.findall(s)
829 825 return ret
830 826
831 827 def _default_arguments(self, obj):
832 828 """Return the list of default arguments of obj if it is callable,
833 829 or empty list otherwise."""
834 830 call_obj = obj
835 831 ret = []
836 832 if inspect.isbuiltin(obj):
837 833 pass
838 834 elif not (inspect.isfunction(obj) or inspect.ismethod(obj)):
839 835 if inspect.isclass(obj):
840 836 #for cython embededsignature=True the constructor docstring
841 837 #belongs to the object itself not __init__
842 838 ret += self._default_arguments_from_docstring(
843 839 getattr(obj, '__doc__', ''))
844 840 # for classes, check for __init__,__new__
845 841 call_obj = (getattr(obj, '__init__', None) or
846 842 getattr(obj, '__new__', None))
847 843 # for all others, check if they are __call__able
848 844 elif hasattr(obj, '__call__'):
849 845 call_obj = obj.__call__
850 846 ret += self._default_arguments_from_docstring(
851 847 getattr(call_obj, '__doc__', ''))
852 848
853 849 if PY3:
854 850 _keeps = (inspect.Parameter.KEYWORD_ONLY,
855 851 inspect.Parameter.POSITIONAL_OR_KEYWORD)
856 852 signature = inspect.signature
857 853 else:
858 854 import IPython.utils.signatures
859 855 _keeps = (IPython.utils.signatures.Parameter.KEYWORD_ONLY,
860 856 IPython.utils.signatures.Parameter.POSITIONAL_OR_KEYWORD)
861 857 signature = IPython.utils.signatures.signature
862 858
863 859 try:
864 860 sig = signature(call_obj)
865 861 ret.extend(k for k, v in sig.parameters.items() if
866 862 v.kind in _keeps)
867 863 except ValueError:
868 864 pass
869 865
870 866 return list(set(ret))
871 867
872 868 def python_func_kw_matches(self,text):
873 869 """Match named parameters (kwargs) of the last open function"""
874 870
875 871 if "." in text: # a parameter cannot be dotted
876 872 return []
877 873 try: regexp = self.__funcParamsRegex
878 874 except AttributeError:
879 875 regexp = self.__funcParamsRegex = re.compile(r'''
880 876 '.*?(?<!\\)' | # single quoted strings or
881 877 ".*?(?<!\\)" | # double quoted strings or
882 878 \w+ | # identifier
883 879 \S # other characters
884 880 ''', re.VERBOSE | re.DOTALL)
885 881 # 1. find the nearest identifier that comes before an unclosed
886 882 # parenthesis before the cursor
887 883 # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo"
888 884 tokens = regexp.findall(self.text_until_cursor)
889 885 iterTokens = reversed(tokens); openPar = 0
890 886
891 887 for token in iterTokens:
892 888 if token == ')':
893 889 openPar -= 1
894 890 elif token == '(':
895 891 openPar += 1
896 892 if openPar > 0:
897 893 # found the last unclosed parenthesis
898 894 break
899 895 else:
900 896 return []
901 897 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
902 898 ids = []
903 899 isId = re.compile(r'\w+$').match
904 900
905 901 while True:
906 902 try:
907 903 ids.append(next(iterTokens))
908 904 if not isId(ids[-1]):
909 905 ids.pop(); break
910 906 if not next(iterTokens) == '.':
911 907 break
912 908 except StopIteration:
913 909 break
914 910
915 911 # Find all named arguments already assigned to, as to avoid suggesting
916 912 # them again
917 913 usedNamedArgs = set()
918 914 par_level = -1
919 915 for token, next_token in zip(tokens, tokens[1:]):
920 916 if token == '(':
921 917 par_level += 1
922 918 elif token == ')':
923 919 par_level -= 1
924 920
925 921 if par_level != 0:
926 922 continue
927 923
928 924 if next_token != '=':
929 925 continue
930 926
931 927 usedNamedArgs.add(token)
932 928
933 929 # lookup the candidate callable matches either using global_matches
934 930 # or attr_matches for dotted names
935 931 if len(ids) == 1:
936 932 callableMatches = self.global_matches(ids[0])
937 933 else:
938 934 callableMatches = self.attr_matches('.'.join(ids[::-1]))
939 935 argMatches = []
940 936 for callableMatch in callableMatches:
941 937 try:
942 938 namedArgs = self._default_arguments(eval(callableMatch,
943 939 self.namespace))
944 940 except:
945 941 continue
946 942
947 943 # Remove used named arguments from the list, no need to show twice
948 944 for namedArg in set(namedArgs) - usedNamedArgs:
949 945 if namedArg.startswith(text):
950 946 argMatches.append(u"%s=" %namedArg)
951 947 return argMatches
952 948
953 949 def dict_key_matches(self, text):
954 950 "Match string keys in a dictionary, after e.g. 'foo[' "
955 951 def get_keys(obj):
956 952 # Objects can define their own completions by defining an
957 953 # _ipy_key_completions_() method.
958 954 method = get_real_method(obj, '_ipython_key_completions_')
959 955 if method is not None:
960 956 return method()
961 957
962 958 # Special case some common in-memory dict-like types
963 959 if isinstance(obj, dict) or\
964 960 _safe_isinstance(obj, 'pandas', 'DataFrame'):
965 961 try:
966 962 return list(obj.keys())
967 963 except Exception:
968 964 return []
969 965 elif _safe_isinstance(obj, 'numpy', 'ndarray') or\
970 966 _safe_isinstance(obj, 'numpy', 'void'):
971 967 return obj.dtype.names or []
972 968 return []
973 969
974 970 try:
975 971 regexps = self.__dict_key_regexps
976 972 except AttributeError:
977 973 dict_key_re_fmt = r'''(?x)
978 974 ( # match dict-referring expression wrt greedy setting
979 975 %s
980 976 )
981 977 \[ # open bracket
982 978 \s* # and optional whitespace
983 979 ([uUbB]? # string prefix (r not handled)
984 980 (?: # unclosed string
985 981 '(?:[^']|(?<!\\)\\')*
986 982 |
987 983 "(?:[^"]|(?<!\\)\\")*
988 984 )
989 985 )?
990 986 $
991 987 '''
992 988 regexps = self.__dict_key_regexps = {
993 989 False: re.compile(dict_key_re_fmt % '''
994 990 # identifiers separated by .
995 991 (?!\d)\w+
996 992 (?:\.(?!\d)\w+)*
997 993 '''),
998 994 True: re.compile(dict_key_re_fmt % '''
999 995 .+
1000 996 ''')
1001 997 }
1002 998
1003 999 match = regexps[self.greedy].search(self.text_until_cursor)
1004 1000 if match is None:
1005 1001 return []
1006 1002
1007 1003 expr, prefix = match.groups()
1008 1004 try:
1009 1005 obj = eval(expr, self.namespace)
1010 1006 except Exception:
1011 1007 try:
1012 1008 obj = eval(expr, self.global_namespace)
1013 1009 except Exception:
1014 1010 return []
1015 1011
1016 1012 keys = get_keys(obj)
1017 1013 if not keys:
1018 1014 return keys
1019 1015 closing_quote, token_offset, matches = match_dict_keys(keys, prefix, self.splitter.delims)
1020 1016 if not matches:
1021 1017 return matches
1022 1018
1023 1019 # get the cursor position of
1024 1020 # - the text being completed
1025 1021 # - the start of the key text
1026 1022 # - the start of the completion
1027 1023 text_start = len(self.text_until_cursor) - len(text)
1028 1024 if prefix:
1029 1025 key_start = match.start(2)
1030 1026 completion_start = key_start + token_offset
1031 1027 else:
1032 1028 key_start = completion_start = match.end()
1033 1029
1034 1030 # grab the leading prefix, to make sure all completions start with `text`
1035 1031 if text_start > key_start:
1036 1032 leading = ''
1037 1033 else:
1038 1034 leading = text[text_start:completion_start]
1039 1035
1040 1036 # the index of the `[` character
1041 1037 bracket_idx = match.end(1)
1042 1038
1043 1039 # append closing quote and bracket as appropriate
1044 1040 # this is *not* appropriate if the opening quote or bracket is outside
1045 1041 # the text given to this method
1046 1042 suf = ''
1047 1043 continuation = self.line_buffer[len(self.text_until_cursor):]
1048 1044 if key_start > text_start and closing_quote:
1049 1045 # quotes were opened inside text, maybe close them
1050 1046 if continuation.startswith(closing_quote):
1051 1047 continuation = continuation[len(closing_quote):]
1052 1048 else:
1053 1049 suf += closing_quote
1054 1050 if bracket_idx > text_start:
1055 1051 # brackets were opened inside text, maybe close them
1056 1052 if not continuation.startswith(']'):
1057 1053 suf += ']'
1058 1054
1059 1055 return [leading + k + suf for k in matches]
1060 1056
1061 1057 def unicode_name_matches(self, text):
1062 1058 u"""Match Latex-like syntax for unicode characters base
1063 1059 on the name of the character.
1064 1060
1065 1061 This does \\GREEK SMALL LETTER ETA -> η
1066 1062
1067 1063 Works only on valid python 3 identifier, or on combining characters that
1068 1064 will combine to form a valid identifier.
1069 1065
1070 1066 Used on Python 3 only.
1071 1067 """
1072 1068 slashpos = text.rfind('\\')
1073 1069 if slashpos > -1:
1074 1070 s = text[slashpos+1:]
1075 1071 try :
1076 1072 unic = unicodedata.lookup(s)
1077 1073 # allow combining chars
1078 1074 if ('a'+unic).isidentifier():
1079 1075 return '\\'+s,[unic]
1080 1076 except KeyError:
1081 1077 pass
1082 1078 return u'', []
1083 1079
1084 1080
1085 1081
1086 1082
1087 1083 def latex_matches(self, text):
1088 1084 u"""Match Latex syntax for unicode characters.
1089 1085
1090 1086 This does both \\alp -> \\alpha and \\alpha -> α
1091 1087
1092 1088 Used on Python 3 only.
1093 1089 """
1094 1090 slashpos = text.rfind('\\')
1095 1091 if slashpos > -1:
1096 1092 s = text[slashpos:]
1097 1093 if s in latex_symbols:
1098 1094 # Try to complete a full latex symbol to unicode
1099 1095 # \\alpha -> α
1100 1096 return s, [latex_symbols[s]]
1101 1097 else:
1102 1098 # If a user has partially typed a latex symbol, give them
1103 1099 # a full list of options \al -> [\aleph, \alpha]
1104 1100 matches = [k for k in latex_symbols if k.startswith(s)]
1105 1101 return s, matches
1106 1102 return u'', []
1107 1103
1108 1104 def dispatch_custom_completer(self, text):
1109 1105 if not self.custom_completers:
1110 1106 return
1111 1107
1112 1108 line = self.line_buffer
1113 1109 if not line.strip():
1114 1110 return None
1115 1111
1116 1112 # Create a little structure to pass all the relevant information about
1117 1113 # the current completion to any custom completer.
1118 1114 event = Bunch()
1119 1115 event.line = line
1120 1116 event.symbol = text
1121 1117 cmd = line.split(None,1)[0]
1122 1118 event.command = cmd
1123 1119 event.text_until_cursor = self.text_until_cursor
1124 1120
1125 1121 # for foo etc, try also to find completer for %foo
1126 1122 if not cmd.startswith(self.magic_escape):
1127 1123 try_magic = self.custom_completers.s_matches(
1128 1124 self.magic_escape + cmd)
1129 1125 else:
1130 1126 try_magic = []
1131 1127
1132 1128 for c in itertools.chain(self.custom_completers.s_matches(cmd),
1133 1129 try_magic,
1134 1130 self.custom_completers.flat_matches(self.text_until_cursor)):
1135 1131 try:
1136 1132 res = c(event)
1137 1133 if res:
1138 1134 # first, try case sensitive match
1139 1135 withcase = [cast_unicode_py2(r) for r in res if r.startswith(text)]
1140 1136 if withcase:
1141 1137 return withcase
1142 1138 # if none, then case insensitive ones are ok too
1143 1139 text_low = text.lower()
1144 1140 return [cast_unicode_py2(r) for r in res if r.lower().startswith(text_low)]
1145 1141 except TryNext:
1146 1142 pass
1147 1143
1148 1144 return None
1149 1145
1150 1146 @_strip_single_trailing_space
1151 1147 def complete(self, text=None, line_buffer=None, cursor_pos=None):
1152 1148 """Find completions for the given text and line context.
1153 1149
1154 1150 Note that both the text and the line_buffer are optional, but at least
1155 1151 one of them must be given.
1156 1152
1157 1153 Parameters
1158 1154 ----------
1159 1155 text : string, optional
1160 1156 Text to perform the completion on. If not given, the line buffer
1161 1157 is split using the instance's CompletionSplitter object.
1162 1158
1163 1159 line_buffer : string, optional
1164 1160 If not given, the completer attempts to obtain the current line
1165 1161 buffer via readline. This keyword allows clients which are
1166 1162 requesting for text completions in non-readline contexts to inform
1167 1163 the completer of the entire text.
1168 1164
1169 1165 cursor_pos : int, optional
1170 1166 Index of the cursor in the full line buffer. Should be provided by
1171 1167 remote frontends where kernel has no access to frontend state.
1172 1168
1173 1169 Returns
1174 1170 -------
1175 1171 text : str
1176 1172 Text that was actually used in the completion.
1177 1173
1178 1174 matches : list
1179 1175 A list of completion matches.
1180 1176 """
1181 1177 # if the cursor position isn't given, the only sane assumption we can
1182 1178 # make is that it's at the end of the line (the common case)
1183 1179 if cursor_pos is None:
1184 1180 cursor_pos = len(line_buffer) if text is None else len(text)
1185 1181
1186 1182 if self.use_main_ns:
1187 1183 self.namespace = __main__.__dict__
1188 1184
1189 1185 if PY3:
1190 1186
1191 1187 base_text = text if not line_buffer else line_buffer[:cursor_pos]
1192 1188 latex_text, latex_matches = self.latex_matches(base_text)
1193 1189 if latex_matches:
1194 1190 return latex_text, latex_matches
1195 1191 name_text = ''
1196 1192 name_matches = []
1197 1193 for meth in (self.unicode_name_matches, back_latex_name_matches, back_unicode_name_matches):
1198 1194 name_text, name_matches = meth(base_text)
1199 1195 if name_text:
1200 1196 return name_text, name_matches
1201 1197
1202 1198 # if text is either None or an empty string, rely on the line buffer
1203 1199 if not text:
1204 1200 text = self.splitter.split_line(line_buffer, cursor_pos)
1205 1201
1206 1202 # If no line buffer is given, assume the input text is all there was
1207 1203 if line_buffer is None:
1208 1204 line_buffer = text
1209 1205
1210 1206 self.line_buffer = line_buffer
1211 1207 self.text_until_cursor = self.line_buffer[:cursor_pos]
1212 1208
1213 1209 # Start with a clean slate of completions
1214 1210 self.matches[:] = []
1215 1211 custom_res = self.dispatch_custom_completer(text)
1216 1212 if custom_res is not None:
1217 1213 # did custom completers produce something?
1218 1214 self.matches = custom_res
1219 1215 else:
1220 1216 # Extend the list of completions with the results of each
1221 1217 # matcher, so we return results to the user from all
1222 1218 # namespaces.
1223 1219 if self.merge_completions:
1224 1220 self.matches = []
1225 1221 for matcher in self.matchers:
1226 1222 try:
1227 1223 self.matches.extend(matcher(text))
1228 1224 except:
1229 1225 # Show the ugly traceback if the matcher causes an
1230 1226 # exception, but do NOT crash the kernel!
1231 1227 sys.excepthook(*sys.exc_info())
1232 1228 else:
1233 1229 for matcher in self.matchers:
1234 1230 self.matches = matcher(text)
1235 1231 if self.matches:
1236 1232 break
1237 1233 # FIXME: we should extend our api to return a dict with completions for
1238 1234 # different types of objects. The rlcomplete() method could then
1239 1235 # simply collapse the dict into a list for readline, but we'd have
1240 1236 # richer completion semantics in other evironments.
1241 1237 self.matches = sorted(set(self.matches), key=completions_sorting_key)
1242 1238
1243 1239 return text, self.matches
@@ -1,3229 +1,3228 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 from __future__ import absolute_import, print_function
14 14
15 15 import __future__
16 16 import abc
17 17 import ast
18 18 import atexit
19 19 import functools
20 20 import os
21 21 import re
22 22 import runpy
23 23 import sys
24 24 import tempfile
25 25 import traceback
26 26 import types
27 27 import subprocess
28 28 import warnings
29 29 from io import open as io_open
30 30
31 31 from pickleshare import PickleShareDB
32 32
33 33 from traitlets.config.configurable import SingletonConfigurable
34 34 from IPython.core import oinspect
35 35 from IPython.core import magic
36 36 from IPython.core import page
37 37 from IPython.core import prefilter
38 38 from IPython.core import shadowns
39 39 from IPython.core import ultratb
40 40 from IPython.core.alias import Alias, AliasManager
41 41 from IPython.core.autocall import ExitAutocall
42 42 from IPython.core.builtin_trap import BuiltinTrap
43 43 from IPython.core.events import EventManager, available_events
44 44 from IPython.core.compilerop import CachingCompiler, check_linecache_ipython
45 45 from IPython.core.debugger import Pdb
46 46 from IPython.core.display_trap import DisplayTrap
47 47 from IPython.core.displayhook import DisplayHook
48 48 from IPython.core.displaypub import DisplayPublisher
49 49 from IPython.core.error import InputRejected, UsageError
50 50 from IPython.core.extensions import ExtensionManager
51 51 from IPython.core.formatters import DisplayFormatter
52 52 from IPython.core.history import HistoryManager
53 53 from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2
54 54 from IPython.core.logger import Logger
55 55 from IPython.core.macro import Macro
56 56 from IPython.core.payload import PayloadManager
57 57 from IPython.core.prefilter import PrefilterManager
58 58 from IPython.core.profiledir import ProfileDir
59 59 from IPython.core.usage import default_banner
60 60 from IPython.testing.skipdoctest import skip_doctest_py2, skip_doctest
61 61 from IPython.utils import PyColorize
62 62 from IPython.utils import io
63 63 from IPython.utils import py3compat
64 64 from IPython.utils import openpy
65 65 from IPython.utils.decorators import undoc
66 66 from IPython.utils.io import ask_yes_no
67 67 from IPython.utils.ipstruct import Struct
68 68 from IPython.paths import get_ipython_dir
69 69 from IPython.utils.path import get_home_dir, get_py_filename, ensure_dir_exists
70 70 from IPython.utils.process import system, getoutput
71 71 from IPython.utils.py3compat import (builtin_mod, unicode_type, string_types,
72 72 with_metaclass, iteritems)
73 73 from IPython.utils.strdispatch import StrDispatch
74 74 from IPython.utils.syspathcontext import prepended_to_syspath
75 75 from IPython.utils.text import format_screen, LSString, SList, DollarFormatter
76 76 from IPython.utils.tempdir import TemporaryDirectory
77 77 from traitlets import (
78 78 Integer, Bool, CaselessStrEnum, Enum, List, Dict, Unicode, Instance, Type,
79 79 observe, default,
80 80 )
81 81 from warnings import warn
82 82 from logging import error
83 83 import IPython.core.hooks
84 84
85 85 # NoOpContext is deprecated, but ipykernel imports it from here.
86 86 # See https://github.com/ipython/ipykernel/issues/157
87 87 from IPython.utils.contexts import NoOpContext
88 88
89 89 try:
90 90 import docrepr.sphinxify as sphx
91 91
92 92 def sphinxify(doc):
93 93 with TemporaryDirectory() as dirname:
94 94 return {
95 95 'text/html': sphx.sphinxify(doc, dirname),
96 96 'text/plain': doc
97 97 }
98 98 except ImportError:
99 99 sphinxify = None
100 100
101 101
102 102 class ProvisionalWarning(DeprecationWarning):
103 103 """
104 104 Warning class for unstable features
105 105 """
106 106 pass
107 107
108 108 #-----------------------------------------------------------------------------
109 109 # Globals
110 110 #-----------------------------------------------------------------------------
111 111
112 112 # compiled regexps for autoindent management
113 113 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
114 114
115 115 #-----------------------------------------------------------------------------
116 116 # Utilities
117 117 #-----------------------------------------------------------------------------
118 118
119 119 @undoc
120 120 def softspace(file, newvalue):
121 121 """Copied from code.py, to remove the dependency"""
122 122
123 123 oldvalue = 0
124 124 try:
125 125 oldvalue = file.softspace
126 126 except AttributeError:
127 127 pass
128 128 try:
129 129 file.softspace = newvalue
130 130 except (AttributeError, TypeError):
131 131 # "attribute-less object" or "read-only attributes"
132 132 pass
133 133 return oldvalue
134 134
135 135 @undoc
136 136 def no_op(*a, **kw): pass
137 137
138 138
139 139 class SpaceInInput(Exception): pass
140 140
141 141
142 142 def get_default_colors():
143 143 "DEPRECATED"
144 144 warn('get_default_color is Deprecated, and is `Neutral` on all platforms.',
145 145 DeprecationWarning, stacklevel=2)
146 146 return 'Neutral'
147 147
148 148
149 149 class SeparateUnicode(Unicode):
150 150 r"""A Unicode subclass to validate separate_in, separate_out, etc.
151 151
152 152 This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``.
153 153 """
154 154
155 155 def validate(self, obj, value):
156 156 if value == '0': value = ''
157 157 value = value.replace('\\n','\n')
158 158 return super(SeparateUnicode, self).validate(obj, value)
159 159
160 160
161 161 @undoc
162 162 class DummyMod(object):
163 163 """A dummy module used for IPython's interactive module when
164 164 a namespace must be assigned to the module's __dict__."""
165 165 pass
166 166
167 167
168 168 class ExecutionResult(object):
169 169 """The result of a call to :meth:`InteractiveShell.run_cell`
170 170
171 171 Stores information about what took place.
172 172 """
173 173 execution_count = None
174 174 error_before_exec = None
175 175 error_in_exec = None
176 176 result = None
177 177
178 178 @property
179 179 def success(self):
180 180 return (self.error_before_exec is None) and (self.error_in_exec is None)
181 181
182 182 def raise_error(self):
183 183 """Reraises error if `success` is `False`, otherwise does nothing"""
184 184 if self.error_before_exec is not None:
185 185 raise self.error_before_exec
186 186 if self.error_in_exec is not None:
187 187 raise self.error_in_exec
188 188
189 189 def __repr__(self):
190 190 if sys.version_info > (3,):
191 191 name = self.__class__.__qualname__
192 192 else:
193 193 name = self.__class__.__name__
194 194 return '<%s object at %x, execution_count=%s error_before_exec=%s error_in_exec=%s result=%s>' %\
195 195 (name, id(self), self.execution_count, self.error_before_exec, self.error_in_exec, repr(self.result))
196 196
197 197
198 198 class InteractiveShell(SingletonConfigurable):
199 199 """An enhanced, interactive shell for Python."""
200 200
201 201 _instance = None
202 202
203 203 ast_transformers = List([], help=
204 204 """
205 205 A list of ast.NodeTransformer subclass instances, which will be applied
206 206 to user input before code is run.
207 207 """
208 208 ).tag(config=True)
209 209
210 210 autocall = Enum((0,1,2), default_value=0, help=
211 211 """
212 212 Make IPython automatically call any callable object even if you didn't
213 213 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
214 214 automatically. The value can be '0' to disable the feature, '1' for
215 215 'smart' autocall, where it is not applied if there are no more
216 216 arguments on the line, and '2' for 'full' autocall, where all callable
217 217 objects are automatically called (even if no arguments are present).
218 218 """
219 219 ).tag(config=True)
220 220 # TODO: remove all autoindent logic and put into frontends.
221 221 # We can't do this yet because even runlines uses the autoindent.
222 222 autoindent = Bool(True, help=
223 223 """
224 224 Autoindent IPython code entered interactively.
225 225 """
226 226 ).tag(config=True)
227 227
228 228 automagic = Bool(True, help=
229 229 """
230 230 Enable magic commands to be called without the leading %.
231 231 """
232 232 ).tag(config=True)
233 233
234 234 banner1 = Unicode(default_banner,
235 235 help="""The part of the banner to be printed before the profile"""
236 236 ).tag(config=True)
237 237 banner2 = Unicode('',
238 238 help="""The part of the banner to be printed after the profile"""
239 239 ).tag(config=True)
240 240
241 241 cache_size = Integer(1000, help=
242 242 """
243 243 Set the size of the output cache. The default is 1000, you can
244 244 change it permanently in your config file. Setting it to 0 completely
245 245 disables the caching system, and the minimum value accepted is 20 (if
246 246 you provide a value less than 20, it is reset to 0 and a warning is
247 247 issued). This limit is defined because otherwise you'll spend more
248 248 time re-flushing a too small cache than working
249 249 """
250 250 ).tag(config=True)
251 251 color_info = Bool(True, help=
252 252 """
253 253 Use colors for displaying information about objects. Because this
254 254 information is passed through a pager (like 'less'), and some pagers
255 255 get confused with color codes, this capability can be turned off.
256 256 """
257 257 ).tag(config=True)
258 258 colors = CaselessStrEnum(('Neutral', 'NoColor','LightBG','Linux'),
259 259 default_value='Neutral',
260 260 help="Set the color scheme (NoColor, Neutral, Linux, or LightBG)."
261 261 ).tag(config=True)
262 262 debug = Bool(False).tag(config=True)
263 263 disable_failing_post_execute = Bool(False,
264 264 help="Don't call post-execute functions that have failed in the past."
265 265 ).tag(config=True)
266 266 display_formatter = Instance(DisplayFormatter, allow_none=True)
267 267 displayhook_class = Type(DisplayHook)
268 268 display_pub_class = Type(DisplayPublisher)
269 269
270 270 sphinxify_docstring = Bool(False, help=
271 271 """
272 272 Enables rich html representation of docstrings. (This requires the
273 273 docrepr module).
274 274 """).tag(config=True)
275 275
276 276 @observe("sphinxify_docstring")
277 277 def _sphinxify_docstring_changed(self, change):
278 278 if change['new']:
279 279 warn("`sphinxify_docstring` is provisional since IPython 5.0 and might change in future versions." , ProvisionalWarning)
280 280
281 281 enable_html_pager = Bool(False, help=
282 282 """
283 283 (Provisional API) enables html representation in mime bundles sent
284 284 to pagers.
285 285 """).tag(config=True)
286 286
287 287 @observe("enable_html_pager")
288 288 def _enable_html_pager_changed(self, change):
289 289 if change['new']:
290 290 warn("`enable_html_pager` is provisional since IPython 5.0 and might change in future versions.", ProvisionalWarning)
291 291
292 292 data_pub_class = None
293 293
294 294 exit_now = Bool(False)
295 295 exiter = Instance(ExitAutocall)
296 296 @default('exiter')
297 297 def _exiter_default(self):
298 298 return ExitAutocall(self)
299 299 # Monotonically increasing execution counter
300 300 execution_count = Integer(1)
301 301 filename = Unicode("<ipython console>")
302 302 ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__
303 303
304 304 # Input splitter, to transform input line by line and detect when a block
305 305 # is ready to be executed.
306 306 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
307 307 (), {'line_input_checker': True})
308 308
309 309 # This InputSplitter instance is used to transform completed cells before
310 310 # running them. It allows cell magics to contain blank lines.
311 311 input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
312 312 (), {'line_input_checker': False})
313 313
314 314 logstart = Bool(False, help=
315 315 """
316 316 Start logging to the default log file in overwrite mode.
317 317 Use `logappend` to specify a log file to **append** logs to.
318 318 """
319 319 ).tag(config=True)
320 320 logfile = Unicode('', help=
321 321 """
322 322 The name of the logfile to use.
323 323 """
324 324 ).tag(config=True)
325 325 logappend = Unicode('', help=
326 326 """
327 327 Start logging to the given file in append mode.
328 328 Use `logfile` to specify a log file to **overwrite** logs to.
329 329 """
330 330 ).tag(config=True)
331 331 object_info_string_level = Enum((0,1,2), default_value=0,
332 332 ).tag(config=True)
333 333 pdb = Bool(False, help=
334 334 """
335 335 Automatically call the pdb debugger after every exception.
336 336 """
337 337 ).tag(config=True)
338 338 display_page = Bool(False,
339 339 help="""If True, anything that would be passed to the pager
340 340 will be displayed as regular output instead."""
341 341 ).tag(config=True)
342 342
343 343 # deprecated prompt traits:
344 344
345 345 prompt_in1 = Unicode('In [\\#]: ',
346 346 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
347 347 ).tag(config=True)
348 348 prompt_in2 = Unicode(' .\\D.: ',
349 349 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
350 350 ).tag(config=True)
351 351 prompt_out = Unicode('Out[\\#]: ',
352 352 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
353 353 ).tag(config=True)
354 354 prompts_pad_left = Bool(True,
355 355 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
356 356 ).tag(config=True)
357 357
358 358 @observe('prompt_in1', 'prompt_in2', 'prompt_out', 'prompt_pad_left')
359 359 def _prompt_trait_changed(self, change):
360 360 name = change['name']
361 361 warn("InteractiveShell.{name} is deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly.".format(
362 362 name=name)
363 363 )
364 364 # protect against weird cases where self.config may not exist:
365 365
366 366 show_rewritten_input = Bool(True,
367 367 help="Show rewritten input, e.g. for autocall."
368 368 ).tag(config=True)
369 369
370 370 quiet = Bool(False).tag(config=True)
371 371
372 372 history_length = Integer(10000,
373 373 help='Total length of command history'
374 374 ).tag(config=True)
375 375
376 376 history_load_length = Integer(1000, help=
377 377 """
378 378 The number of saved history entries to be loaded
379 379 into the history buffer at startup.
380 380 """
381 381 ).tag(config=True)
382 382
383 383 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'],
384 384 default_value='last_expr',
385 385 help="""
386 386 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
387 387 run interactively (displaying output from expressions)."""
388 388 ).tag(config=True)
389 389
390 390 # TODO: this part of prompt management should be moved to the frontends.
391 391 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
392 392 separate_in = SeparateUnicode('\n').tag(config=True)
393 393 separate_out = SeparateUnicode('').tag(config=True)
394 394 separate_out2 = SeparateUnicode('').tag(config=True)
395 395 wildcards_case_sensitive = Bool(True).tag(config=True)
396 396 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
397 397 default_value='Context').tag(config=True)
398 398
399 399 # Subcomponents of InteractiveShell
400 400 alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True)
401 401 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
402 402 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True)
403 403 display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True)
404 404 extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True)
405 405 payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True)
406 406 history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True)
407 407 magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True)
408 408
409 409 profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True)
410 410 @property
411 411 def profile(self):
412 412 if self.profile_dir is not None:
413 413 name = os.path.basename(self.profile_dir.location)
414 414 return name.replace('profile_','')
415 415
416 416
417 417 # Private interface
418 418 _post_execute = Dict()
419 419
420 420 # Tracks any GUI loop loaded for pylab
421 421 pylab_gui_select = None
422 422
423 423 last_execution_succeeded = Bool(True, help='Did last executed command succeeded')
424 424
425 425 def __init__(self, ipython_dir=None, profile_dir=None,
426 426 user_module=None, user_ns=None,
427 427 custom_exceptions=((), None), **kwargs):
428 428
429 429 # This is where traits with a config_key argument are updated
430 430 # from the values on config.
431 431 super(InteractiveShell, self).__init__(**kwargs)
432 432 if 'PromptManager' in self.config:
433 433 warn('As of IPython 5.0 `PromptManager` config will have no effect'
434 434 ' and has been replaced by TerminalInteractiveShell.prompts_class')
435 435 self.configurables = [self]
436 436
437 437 # These are relatively independent and stateless
438 438 self.init_ipython_dir(ipython_dir)
439 439 self.init_profile_dir(profile_dir)
440 440 self.init_instance_attrs()
441 441 self.init_environment()
442 442
443 443 # Check if we're in a virtualenv, and set up sys.path.
444 444 self.init_virtualenv()
445 445
446 446 # Create namespaces (user_ns, user_global_ns, etc.)
447 447 self.init_create_namespaces(user_module, user_ns)
448 448 # This has to be done after init_create_namespaces because it uses
449 449 # something in self.user_ns, but before init_sys_modules, which
450 450 # is the first thing to modify sys.
451 451 # TODO: When we override sys.stdout and sys.stderr before this class
452 452 # is created, we are saving the overridden ones here. Not sure if this
453 453 # is what we want to do.
454 454 self.save_sys_module_state()
455 455 self.init_sys_modules()
456 456
457 457 # While we're trying to have each part of the code directly access what
458 458 # it needs without keeping redundant references to objects, we have too
459 459 # much legacy code that expects ip.db to exist.
460 460 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
461 461
462 462 self.init_history()
463 463 self.init_encoding()
464 464 self.init_prefilter()
465 465
466 466 self.init_syntax_highlighting()
467 467 self.init_hooks()
468 468 self.init_events()
469 469 self.init_pushd_popd_magic()
470 470 self.init_user_ns()
471 471 self.init_logger()
472 472 self.init_builtins()
473 473
474 474 # The following was in post_config_initialization
475 475 self.init_inspector()
476 476 self.raw_input_original = input
477 477 self.init_completer()
478 478 # TODO: init_io() needs to happen before init_traceback handlers
479 479 # because the traceback handlers hardcode the stdout/stderr streams.
480 480 # This logic in in debugger.Pdb and should eventually be changed.
481 481 self.init_io()
482 482 self.init_traceback_handlers(custom_exceptions)
483 483 self.init_prompts()
484 484 self.init_display_formatter()
485 485 self.init_display_pub()
486 486 self.init_data_pub()
487 487 self.init_displayhook()
488 488 self.init_magics()
489 489 self.init_alias()
490 490 self.init_logstart()
491 491 self.init_pdb()
492 492 self.init_extension_manager()
493 493 self.init_payload()
494 494 self.init_deprecation_warnings()
495 495 self.hooks.late_startup_hook()
496 496 self.events.trigger('shell_initialized', self)
497 497 atexit.register(self.atexit_operations)
498 498
499 499 def get_ipython(self):
500 500 """Return the currently running IPython instance."""
501 501 return self
502 502
503 503 #-------------------------------------------------------------------------
504 504 # Trait changed handlers
505 505 #-------------------------------------------------------------------------
506 506 @observe('ipython_dir')
507 507 def _ipython_dir_changed(self, change):
508 508 ensure_dir_exists(change['new'])
509 509
510 510 def set_autoindent(self,value=None):
511 511 """Set the autoindent flag.
512 512
513 513 If called with no arguments, it acts as a toggle."""
514 514 if value is None:
515 515 self.autoindent = not self.autoindent
516 516 else:
517 517 self.autoindent = value
518 518
519 519 #-------------------------------------------------------------------------
520 520 # init_* methods called by __init__
521 521 #-------------------------------------------------------------------------
522 522
523 523 def init_ipython_dir(self, ipython_dir):
524 524 if ipython_dir is not None:
525 525 self.ipython_dir = ipython_dir
526 526 return
527 527
528 528 self.ipython_dir = get_ipython_dir()
529 529
530 530 def init_profile_dir(self, profile_dir):
531 531 if profile_dir is not None:
532 532 self.profile_dir = profile_dir
533 533 return
534 534 self.profile_dir =\
535 535 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
536 536
537 537 def init_instance_attrs(self):
538 538 self.more = False
539 539
540 540 # command compiler
541 541 self.compile = CachingCompiler()
542 542
543 543 # Make an empty namespace, which extension writers can rely on both
544 544 # existing and NEVER being used by ipython itself. This gives them a
545 545 # convenient location for storing additional information and state
546 546 # their extensions may require, without fear of collisions with other
547 547 # ipython names that may develop later.
548 548 self.meta = Struct()
549 549
550 550 # Temporary files used for various purposes. Deleted at exit.
551 551 self.tempfiles = []
552 552 self.tempdirs = []
553 553
554 554 # keep track of where we started running (mainly for crash post-mortem)
555 555 # This is not being used anywhere currently.
556 556 self.starting_dir = py3compat.getcwd()
557 557
558 558 # Indentation management
559 559 self.indent_current_nsp = 0
560 560
561 561 # Dict to track post-execution functions that have been registered
562 562 self._post_execute = {}
563 563
564 564 def init_environment(self):
565 565 """Any changes we need to make to the user's environment."""
566 566 pass
567 567
568 568 def init_encoding(self):
569 569 # Get system encoding at startup time. Certain terminals (like Emacs
570 570 # under Win32 have it set to None, and we need to have a known valid
571 571 # encoding to use in the raw_input() method
572 572 try:
573 573 self.stdin_encoding = sys.stdin.encoding or 'ascii'
574 574 except AttributeError:
575 575 self.stdin_encoding = 'ascii'
576 576
577 577
578 578 @observe('colors')
579 579 def init_syntax_highlighting(self, changes=None):
580 580 # Python source parser/formatter for syntax highlighting
581 581 pyformat = PyColorize.Parser(style=self.colors).format
582 582 self.pycolorize = lambda src: pyformat(src,'str')
583 583
584 584 def refresh_style(self):
585 585 # No-op here, used in subclass
586 586 pass
587 587
588 588 def init_pushd_popd_magic(self):
589 589 # for pushd/popd management
590 590 self.home_dir = get_home_dir()
591 591
592 592 self.dir_stack = []
593 593
594 594 def init_logger(self):
595 595 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
596 596 logmode='rotate')
597 597
598 598 def init_logstart(self):
599 599 """Initialize logging in case it was requested at the command line.
600 600 """
601 601 if self.logappend:
602 602 self.magic('logstart %s append' % self.logappend)
603 603 elif self.logfile:
604 604 self.magic('logstart %s' % self.logfile)
605 605 elif self.logstart:
606 606 self.magic('logstart')
607 607
608 608 def init_deprecation_warnings(self):
609 609 """
610 610 register default filter for deprecation warning.
611 611
612 612 This will allow deprecation warning of function used interactively to show
613 613 warning to users, and still hide deprecation warning from libraries import.
614 614 """
615 615 warnings.filterwarnings("default", category=DeprecationWarning, module=self.user_ns.get("__name__"))
616 616
617 617 def init_builtins(self):
618 618 # A single, static flag that we set to True. Its presence indicates
619 619 # that an IPython shell has been created, and we make no attempts at
620 620 # removing on exit or representing the existence of more than one
621 621 # IPython at a time.
622 622 builtin_mod.__dict__['__IPYTHON__'] = True
623 623
624 624 self.builtin_trap = BuiltinTrap(shell=self)
625 625
626 626 def init_inspector(self):
627 627 # Object inspector
628 628 self.inspector = oinspect.Inspector(oinspect.InspectColors,
629 629 PyColorize.ANSICodeColors,
630 630 'NoColor',
631 631 self.object_info_string_level)
632 632
633 633 def init_io(self):
634 634 # This will just use sys.stdout and sys.stderr. If you want to
635 635 # override sys.stdout and sys.stderr themselves, you need to do that
636 636 # *before* instantiating this class, because io holds onto
637 637 # references to the underlying streams.
638 638 # io.std* are deprecated, but don't show our own deprecation warnings
639 639 # during initialization of the deprecated API.
640 640 with warnings.catch_warnings():
641 641 warnings.simplefilter('ignore', DeprecationWarning)
642 642 io.stdout = io.IOStream(sys.stdout)
643 643 io.stderr = io.IOStream(sys.stderr)
644 644
645 645 def init_prompts(self):
646 646 # Set system prompts, so that scripts can decide if they are running
647 647 # interactively.
648 648 sys.ps1 = 'In : '
649 649 sys.ps2 = '...: '
650 650 sys.ps3 = 'Out: '
651 651
652 652 def init_display_formatter(self):
653 653 self.display_formatter = DisplayFormatter(parent=self)
654 654 self.configurables.append(self.display_formatter)
655 655
656 656 def init_display_pub(self):
657 657 self.display_pub = self.display_pub_class(parent=self)
658 658 self.configurables.append(self.display_pub)
659 659
660 660 def init_data_pub(self):
661 661 if not self.data_pub_class:
662 662 self.data_pub = None
663 663 return
664 664 self.data_pub = self.data_pub_class(parent=self)
665 665 self.configurables.append(self.data_pub)
666 666
667 667 def init_displayhook(self):
668 668 # Initialize displayhook, set in/out prompts and printing system
669 669 self.displayhook = self.displayhook_class(
670 670 parent=self,
671 671 shell=self,
672 672 cache_size=self.cache_size,
673 673 )
674 674 self.configurables.append(self.displayhook)
675 675 # This is a context manager that installs/revmoes the displayhook at
676 676 # the appropriate time.
677 677 self.display_trap = DisplayTrap(hook=self.displayhook)
678 678
679 679 def init_virtualenv(self):
680 680 """Add a virtualenv to sys.path so the user can import modules from it.
681 681 This isn't perfect: it doesn't use the Python interpreter with which the
682 682 virtualenv was built, and it ignores the --no-site-packages option. A
683 683 warning will appear suggesting the user installs IPython in the
684 684 virtualenv, but for many cases, it probably works well enough.
685 685
686 686 Adapted from code snippets online.
687 687
688 688 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
689 689 """
690 690 if 'VIRTUAL_ENV' not in os.environ:
691 691 # Not in a virtualenv
692 692 return
693 693
694 694 # venv detection:
695 695 # stdlib venv may symlink sys.executable, so we can't use realpath.
696 696 # but others can symlink *to* the venv Python, so we can't just use sys.executable.
697 697 # So we just check every item in the symlink tree (generally <= 3)
698 698 p = os.path.normcase(sys.executable)
699 699 paths = [p]
700 700 while os.path.islink(p):
701 701 p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p)))
702 702 paths.append(p)
703 703 p_venv = os.path.normcase(os.environ['VIRTUAL_ENV'])
704 704 if any(p.startswith(p_venv) for p in paths):
705 705 # Running properly in the virtualenv, don't need to do anything
706 706 return
707 707
708 708 warn("Attempting to work in a virtualenv. If you encounter problems, please "
709 709 "install IPython inside the virtualenv.")
710 710 if sys.platform == "win32":
711 711 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
712 712 else:
713 713 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
714 714 'python%d.%d' % sys.version_info[:2], 'site-packages')
715 715
716 716 import site
717 717 sys.path.insert(0, virtual_env)
718 718 site.addsitedir(virtual_env)
719 719
720 720 #-------------------------------------------------------------------------
721 721 # Things related to injections into the sys module
722 722 #-------------------------------------------------------------------------
723 723
724 724 def save_sys_module_state(self):
725 725 """Save the state of hooks in the sys module.
726 726
727 727 This has to be called after self.user_module is created.
728 728 """
729 729 self._orig_sys_module_state = {'stdin': sys.stdin,
730 730 'stdout': sys.stdout,
731 731 'stderr': sys.stderr,
732 732 'excepthook': sys.excepthook}
733 733 self._orig_sys_modules_main_name = self.user_module.__name__
734 734 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
735 735
736 736 def restore_sys_module_state(self):
737 737 """Restore the state of the sys module."""
738 738 try:
739 739 for k, v in iteritems(self._orig_sys_module_state):
740 740 setattr(sys, k, v)
741 741 except AttributeError:
742 742 pass
743 743 # Reset what what done in self.init_sys_modules
744 744 if self._orig_sys_modules_main_mod is not None:
745 745 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
746 746
747 747 #-------------------------------------------------------------------------
748 748 # Things related to the banner
749 749 #-------------------------------------------------------------------------
750 750
751 751 @property
752 752 def banner(self):
753 753 banner = self.banner1
754 754 if self.profile and self.profile != 'default':
755 755 banner += '\nIPython profile: %s\n' % self.profile
756 756 if self.banner2:
757 757 banner += '\n' + self.banner2
758 758 return banner
759 759
760 760 def show_banner(self, banner=None):
761 761 if banner is None:
762 762 banner = self.banner
763 763 sys.stdout.write(banner)
764 764
765 765 #-------------------------------------------------------------------------
766 766 # Things related to hooks
767 767 #-------------------------------------------------------------------------
768 768
769 769 def init_hooks(self):
770 770 # hooks holds pointers used for user-side customizations
771 771 self.hooks = Struct()
772 772
773 773 self.strdispatchers = {}
774 774
775 775 # Set all default hooks, defined in the IPython.hooks module.
776 776 hooks = IPython.core.hooks
777 777 for hook_name in hooks.__all__:
778 778 # default hooks have priority 100, i.e. low; user hooks should have
779 779 # 0-100 priority
780 780 self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False)
781 781
782 782 if self.display_page:
783 783 self.set_hook('show_in_pager', page.as_hook(page.display_page), 90)
784 784
785 785 def set_hook(self,name,hook, priority=50, str_key=None, re_key=None,
786 786 _warn_deprecated=True):
787 787 """set_hook(name,hook) -> sets an internal IPython hook.
788 788
789 789 IPython exposes some of its internal API as user-modifiable hooks. By
790 790 adding your function to one of these hooks, you can modify IPython's
791 791 behavior to call at runtime your own routines."""
792 792
793 793 # At some point in the future, this should validate the hook before it
794 794 # accepts it. Probably at least check that the hook takes the number
795 795 # of args it's supposed to.
796 796
797 797 f = types.MethodType(hook,self)
798 798
799 799 # check if the hook is for strdispatcher first
800 800 if str_key is not None:
801 801 sdp = self.strdispatchers.get(name, StrDispatch())
802 802 sdp.add_s(str_key, f, priority )
803 803 self.strdispatchers[name] = sdp
804 804 return
805 805 if re_key is not None:
806 806 sdp = self.strdispatchers.get(name, StrDispatch())
807 807 sdp.add_re(re.compile(re_key), f, priority )
808 808 self.strdispatchers[name] = sdp
809 809 return
810 810
811 811 dp = getattr(self.hooks, name, None)
812 812 if name not in IPython.core.hooks.__all__:
813 813 print("Warning! Hook '%s' is not one of %s" % \
814 814 (name, IPython.core.hooks.__all__ ))
815 815
816 816 if _warn_deprecated and (name in IPython.core.hooks.deprecated):
817 817 alternative = IPython.core.hooks.deprecated[name]
818 818 warn("Hook {} is deprecated. Use {} instead.".format(name, alternative))
819 819
820 820 if not dp:
821 821 dp = IPython.core.hooks.CommandChainDispatcher()
822 822
823 823 try:
824 824 dp.add(f,priority)
825 825 except AttributeError:
826 826 # it was not commandchain, plain old func - replace
827 827 dp = f
828 828
829 829 setattr(self.hooks,name, dp)
830 830
831 831 #-------------------------------------------------------------------------
832 832 # Things related to events
833 833 #-------------------------------------------------------------------------
834 834
835 835 def init_events(self):
836 836 self.events = EventManager(self, available_events)
837 837
838 838 self.events.register("pre_execute", self._clear_warning_registry)
839 839
840 840 def register_post_execute(self, func):
841 841 """DEPRECATED: Use ip.events.register('post_run_cell', func)
842 842
843 843 Register a function for calling after code execution.
844 844 """
845 845 warn("ip.register_post_execute is deprecated, use "
846 846 "ip.events.register('post_run_cell', func) instead.")
847 847 self.events.register('post_run_cell', func)
848 848
849 849 def _clear_warning_registry(self):
850 850 # clear the warning registry, so that different code blocks with
851 851 # overlapping line number ranges don't cause spurious suppression of
852 852 # warnings (see gh-6611 for details)
853 853 if "__warningregistry__" in self.user_global_ns:
854 854 del self.user_global_ns["__warningregistry__"]
855 855
856 856 #-------------------------------------------------------------------------
857 857 # Things related to the "main" module
858 858 #-------------------------------------------------------------------------
859 859
860 860 def new_main_mod(self, filename, modname):
861 861 """Return a new 'main' module object for user code execution.
862 862
863 863 ``filename`` should be the path of the script which will be run in the
864 864 module. Requests with the same filename will get the same module, with
865 865 its namespace cleared.
866 866
867 867 ``modname`` should be the module name - normally either '__main__' or
868 868 the basename of the file without the extension.
869 869
870 870 When scripts are executed via %run, we must keep a reference to their
871 871 __main__ module around so that Python doesn't
872 872 clear it, rendering references to module globals useless.
873 873
874 874 This method keeps said reference in a private dict, keyed by the
875 875 absolute path of the script. This way, for multiple executions of the
876 876 same script we only keep one copy of the namespace (the last one),
877 877 thus preventing memory leaks from old references while allowing the
878 878 objects from the last execution to be accessible.
879 879 """
880 880 filename = os.path.abspath(filename)
881 881 try:
882 882 main_mod = self._main_mod_cache[filename]
883 883 except KeyError:
884 884 main_mod = self._main_mod_cache[filename] = types.ModuleType(
885 885 py3compat.cast_bytes_py2(modname),
886 886 doc="Module created for script run in IPython")
887 887 else:
888 888 main_mod.__dict__.clear()
889 889 main_mod.__name__ = modname
890 890
891 891 main_mod.__file__ = filename
892 892 # It seems pydoc (and perhaps others) needs any module instance to
893 893 # implement a __nonzero__ method
894 894 main_mod.__nonzero__ = lambda : True
895 895
896 896 return main_mod
897 897
898 898 def clear_main_mod_cache(self):
899 899 """Clear the cache of main modules.
900 900
901 901 Mainly for use by utilities like %reset.
902 902
903 903 Examples
904 904 --------
905 905
906 906 In [15]: import IPython
907 907
908 908 In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython')
909 909
910 910 In [17]: len(_ip._main_mod_cache) > 0
911 911 Out[17]: True
912 912
913 913 In [18]: _ip.clear_main_mod_cache()
914 914
915 915 In [19]: len(_ip._main_mod_cache) == 0
916 916 Out[19]: True
917 917 """
918 918 self._main_mod_cache.clear()
919 919
920 920 #-------------------------------------------------------------------------
921 921 # Things related to debugging
922 922 #-------------------------------------------------------------------------
923 923
924 924 def init_pdb(self):
925 925 # Set calling of pdb on exceptions
926 926 # self.call_pdb is a property
927 927 self.call_pdb = self.pdb
928 928
929 929 def _get_call_pdb(self):
930 930 return self._call_pdb
931 931
932 932 def _set_call_pdb(self,val):
933 933
934 934 if val not in (0,1,False,True):
935 935 raise ValueError('new call_pdb value must be boolean')
936 936
937 937 # store value in instance
938 938 self._call_pdb = val
939 939
940 940 # notify the actual exception handlers
941 941 self.InteractiveTB.call_pdb = val
942 942
943 943 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
944 944 'Control auto-activation of pdb at exceptions')
945 945
946 946 def debugger(self,force=False):
947 947 """Call the pdb debugger.
948 948
949 949 Keywords:
950 950
951 951 - force(False): by default, this routine checks the instance call_pdb
952 952 flag and does not actually invoke the debugger if the flag is false.
953 953 The 'force' option forces the debugger to activate even if the flag
954 954 is false.
955 955 """
956 956
957 957 if not (force or self.call_pdb):
958 958 return
959 959
960 960 if not hasattr(sys,'last_traceback'):
961 961 error('No traceback has been produced, nothing to debug.')
962 962 return
963 963
964 964 self.InteractiveTB.debugger(force=True)
965 965
966 966 #-------------------------------------------------------------------------
967 967 # Things related to IPython's various namespaces
968 968 #-------------------------------------------------------------------------
969 969 default_user_namespaces = True
970 970
971 971 def init_create_namespaces(self, user_module=None, user_ns=None):
972 972 # Create the namespace where the user will operate. user_ns is
973 973 # normally the only one used, and it is passed to the exec calls as
974 974 # the locals argument. But we do carry a user_global_ns namespace
975 975 # given as the exec 'globals' argument, This is useful in embedding
976 976 # situations where the ipython shell opens in a context where the
977 977 # distinction between locals and globals is meaningful. For
978 978 # non-embedded contexts, it is just the same object as the user_ns dict.
979 979
980 980 # FIXME. For some strange reason, __builtins__ is showing up at user
981 981 # level as a dict instead of a module. This is a manual fix, but I
982 982 # should really track down where the problem is coming from. Alex
983 983 # Schmolck reported this problem first.
984 984
985 985 # A useful post by Alex Martelli on this topic:
986 986 # Re: inconsistent value from __builtins__
987 987 # Von: Alex Martelli <aleaxit@yahoo.com>
988 988 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
989 989 # Gruppen: comp.lang.python
990 990
991 991 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
992 992 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
993 993 # > <type 'dict'>
994 994 # > >>> print type(__builtins__)
995 995 # > <type 'module'>
996 996 # > Is this difference in return value intentional?
997 997
998 998 # Well, it's documented that '__builtins__' can be either a dictionary
999 999 # or a module, and it's been that way for a long time. Whether it's
1000 1000 # intentional (or sensible), I don't know. In any case, the idea is
1001 1001 # that if you need to access the built-in namespace directly, you
1002 1002 # should start with "import __builtin__" (note, no 's') which will
1003 1003 # definitely give you a module. Yeah, it's somewhat confusing:-(.
1004 1004
1005 1005 # These routines return a properly built module and dict as needed by
1006 1006 # the rest of the code, and can also be used by extension writers to
1007 1007 # generate properly initialized namespaces.
1008 1008 if (user_ns is not None) or (user_module is not None):
1009 1009 self.default_user_namespaces = False
1010 1010 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
1011 1011
1012 1012 # A record of hidden variables we have added to the user namespace, so
1013 1013 # we can list later only variables defined in actual interactive use.
1014 1014 self.user_ns_hidden = {}
1015 1015
1016 1016 # Now that FakeModule produces a real module, we've run into a nasty
1017 1017 # problem: after script execution (via %run), the module where the user
1018 1018 # code ran is deleted. Now that this object is a true module (needed
1019 1019 # so doctest and other tools work correctly), the Python module
1020 1020 # teardown mechanism runs over it, and sets to None every variable
1021 1021 # present in that module. Top-level references to objects from the
1022 1022 # script survive, because the user_ns is updated with them. However,
1023 1023 # calling functions defined in the script that use other things from
1024 1024 # the script will fail, because the function's closure had references
1025 1025 # to the original objects, which are now all None. So we must protect
1026 1026 # these modules from deletion by keeping a cache.
1027 1027 #
1028 1028 # To avoid keeping stale modules around (we only need the one from the
1029 1029 # last run), we use a dict keyed with the full path to the script, so
1030 1030 # only the last version of the module is held in the cache. Note,
1031 1031 # however, that we must cache the module *namespace contents* (their
1032 1032 # __dict__). Because if we try to cache the actual modules, old ones
1033 1033 # (uncached) could be destroyed while still holding references (such as
1034 1034 # those held by GUI objects that tend to be long-lived)>
1035 1035 #
1036 1036 # The %reset command will flush this cache. See the cache_main_mod()
1037 1037 # and clear_main_mod_cache() methods for details on use.
1038 1038
1039 1039 # This is the cache used for 'main' namespaces
1040 1040 self._main_mod_cache = {}
1041 1041
1042 1042 # A table holding all the namespaces IPython deals with, so that
1043 1043 # introspection facilities can search easily.
1044 1044 self.ns_table = {'user_global':self.user_module.__dict__,
1045 1045 'user_local':self.user_ns,
1046 1046 'builtin':builtin_mod.__dict__
1047 1047 }
1048 1048
1049 1049 @property
1050 1050 def user_global_ns(self):
1051 1051 return self.user_module.__dict__
1052 1052
1053 1053 def prepare_user_module(self, user_module=None, user_ns=None):
1054 1054 """Prepare the module and namespace in which user code will be run.
1055 1055
1056 1056 When IPython is started normally, both parameters are None: a new module
1057 1057 is created automatically, and its __dict__ used as the namespace.
1058 1058
1059 1059 If only user_module is provided, its __dict__ is used as the namespace.
1060 1060 If only user_ns is provided, a dummy module is created, and user_ns
1061 1061 becomes the global namespace. If both are provided (as they may be
1062 1062 when embedding), user_ns is the local namespace, and user_module
1063 1063 provides the global namespace.
1064 1064
1065 1065 Parameters
1066 1066 ----------
1067 1067 user_module : module, optional
1068 1068 The current user module in which IPython is being run. If None,
1069 1069 a clean module will be created.
1070 1070 user_ns : dict, optional
1071 1071 A namespace in which to run interactive commands.
1072 1072
1073 1073 Returns
1074 1074 -------
1075 1075 A tuple of user_module and user_ns, each properly initialised.
1076 1076 """
1077 1077 if user_module is None and user_ns is not None:
1078 1078 user_ns.setdefault("__name__", "__main__")
1079 1079 user_module = DummyMod()
1080 1080 user_module.__dict__ = user_ns
1081 1081
1082 1082 if user_module is None:
1083 1083 user_module = types.ModuleType("__main__",
1084 1084 doc="Automatically created module for IPython interactive environment")
1085 1085
1086 1086 # We must ensure that __builtin__ (without the final 's') is always
1087 1087 # available and pointing to the __builtin__ *module*. For more details:
1088 1088 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1089 1089 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1090 1090 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1091 1091
1092 1092 if user_ns is None:
1093 1093 user_ns = user_module.__dict__
1094 1094
1095 1095 return user_module, user_ns
1096 1096
1097 1097 def init_sys_modules(self):
1098 1098 # We need to insert into sys.modules something that looks like a
1099 1099 # module but which accesses the IPython namespace, for shelve and
1100 1100 # pickle to work interactively. Normally they rely on getting
1101 1101 # everything out of __main__, but for embedding purposes each IPython
1102 1102 # instance has its own private namespace, so we can't go shoving
1103 1103 # everything into __main__.
1104 1104
1105 1105 # note, however, that we should only do this for non-embedded
1106 1106 # ipythons, which really mimic the __main__.__dict__ with their own
1107 1107 # namespace. Embedded instances, on the other hand, should not do
1108 1108 # this because they need to manage the user local/global namespaces
1109 1109 # only, but they live within a 'normal' __main__ (meaning, they
1110 1110 # shouldn't overtake the execution environment of the script they're
1111 1111 # embedded in).
1112 1112
1113 1113 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1114 1114 main_name = self.user_module.__name__
1115 1115 sys.modules[main_name] = self.user_module
1116 1116
1117 1117 def init_user_ns(self):
1118 1118 """Initialize all user-visible namespaces to their minimum defaults.
1119 1119
1120 1120 Certain history lists are also initialized here, as they effectively
1121 1121 act as user namespaces.
1122 1122
1123 1123 Notes
1124 1124 -----
1125 1125 All data structures here are only filled in, they are NOT reset by this
1126 1126 method. If they were not empty before, data will simply be added to
1127 1127 therm.
1128 1128 """
1129 1129 # This function works in two parts: first we put a few things in
1130 1130 # user_ns, and we sync that contents into user_ns_hidden so that these
1131 1131 # initial variables aren't shown by %who. After the sync, we add the
1132 1132 # rest of what we *do* want the user to see with %who even on a new
1133 1133 # session (probably nothing, so they really only see their own stuff)
1134 1134
1135 1135 # The user dict must *always* have a __builtin__ reference to the
1136 1136 # Python standard __builtin__ namespace, which must be imported.
1137 1137 # This is so that certain operations in prompt evaluation can be
1138 1138 # reliably executed with builtins. Note that we can NOT use
1139 1139 # __builtins__ (note the 's'), because that can either be a dict or a
1140 1140 # module, and can even mutate at runtime, depending on the context
1141 1141 # (Python makes no guarantees on it). In contrast, __builtin__ is
1142 1142 # always a module object, though it must be explicitly imported.
1143 1143
1144 1144 # For more details:
1145 1145 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1146 1146 ns = dict()
1147 1147
1148 1148 # make global variables for user access to the histories
1149 1149 ns['_ih'] = self.history_manager.input_hist_parsed
1150 1150 ns['_oh'] = self.history_manager.output_hist
1151 1151 ns['_dh'] = self.history_manager.dir_hist
1152 1152
1153 1153 ns['_sh'] = shadowns
1154 1154
1155 1155 # user aliases to input and output histories. These shouldn't show up
1156 1156 # in %who, as they can have very large reprs.
1157 1157 ns['In'] = self.history_manager.input_hist_parsed
1158 1158 ns['Out'] = self.history_manager.output_hist
1159 1159
1160 1160 # Store myself as the public api!!!
1161 1161 ns['get_ipython'] = self.get_ipython
1162 1162
1163 1163 ns['exit'] = self.exiter
1164 1164 ns['quit'] = self.exiter
1165 1165
1166 1166 # Sync what we've added so far to user_ns_hidden so these aren't seen
1167 1167 # by %who
1168 1168 self.user_ns_hidden.update(ns)
1169 1169
1170 1170 # Anything put into ns now would show up in %who. Think twice before
1171 1171 # putting anything here, as we really want %who to show the user their
1172 1172 # stuff, not our variables.
1173 1173
1174 1174 # Finally, update the real user's namespace
1175 1175 self.user_ns.update(ns)
1176 1176
1177 1177 @property
1178 1178 def all_ns_refs(self):
1179 1179 """Get a list of references to all the namespace dictionaries in which
1180 1180 IPython might store a user-created object.
1181 1181
1182 1182 Note that this does not include the displayhook, which also caches
1183 1183 objects from the output."""
1184 1184 return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
1185 1185 [m.__dict__ for m in self._main_mod_cache.values()]
1186 1186
1187 1187 def reset(self, new_session=True):
1188 1188 """Clear all internal namespaces, and attempt to release references to
1189 1189 user objects.
1190 1190
1191 1191 If new_session is True, a new history session will be opened.
1192 1192 """
1193 1193 # Clear histories
1194 1194 self.history_manager.reset(new_session)
1195 1195 # Reset counter used to index all histories
1196 1196 if new_session:
1197 1197 self.execution_count = 1
1198 1198
1199 1199 # Flush cached output items
1200 1200 if self.displayhook.do_full_cache:
1201 1201 self.displayhook.flush()
1202 1202
1203 1203 # The main execution namespaces must be cleared very carefully,
1204 1204 # skipping the deletion of the builtin-related keys, because doing so
1205 1205 # would cause errors in many object's __del__ methods.
1206 1206 if self.user_ns is not self.user_global_ns:
1207 1207 self.user_ns.clear()
1208 1208 ns = self.user_global_ns
1209 1209 drop_keys = set(ns.keys())
1210 1210 drop_keys.discard('__builtin__')
1211 1211 drop_keys.discard('__builtins__')
1212 1212 drop_keys.discard('__name__')
1213 1213 for k in drop_keys:
1214 1214 del ns[k]
1215 1215
1216 1216 self.user_ns_hidden.clear()
1217 1217
1218 1218 # Restore the user namespaces to minimal usability
1219 1219 self.init_user_ns()
1220 1220
1221 1221 # Restore the default and user aliases
1222 1222 self.alias_manager.clear_aliases()
1223 1223 self.alias_manager.init_aliases()
1224 1224
1225 1225 # Flush the private list of module references kept for script
1226 1226 # execution protection
1227 1227 self.clear_main_mod_cache()
1228 1228
1229 1229 def del_var(self, varname, by_name=False):
1230 1230 """Delete a variable from the various namespaces, so that, as
1231 1231 far as possible, we're not keeping any hidden references to it.
1232 1232
1233 1233 Parameters
1234 1234 ----------
1235 1235 varname : str
1236 1236 The name of the variable to delete.
1237 1237 by_name : bool
1238 1238 If True, delete variables with the given name in each
1239 1239 namespace. If False (default), find the variable in the user
1240 1240 namespace, and delete references to it.
1241 1241 """
1242 1242 if varname in ('__builtin__', '__builtins__'):
1243 1243 raise ValueError("Refusing to delete %s" % varname)
1244 1244
1245 1245 ns_refs = self.all_ns_refs
1246 1246
1247 1247 if by_name: # Delete by name
1248 1248 for ns in ns_refs:
1249 1249 try:
1250 1250 del ns[varname]
1251 1251 except KeyError:
1252 1252 pass
1253 1253 else: # Delete by object
1254 1254 try:
1255 1255 obj = self.user_ns[varname]
1256 1256 except KeyError:
1257 1257 raise NameError("name '%s' is not defined" % varname)
1258 1258 # Also check in output history
1259 1259 ns_refs.append(self.history_manager.output_hist)
1260 1260 for ns in ns_refs:
1261 1261 to_delete = [n for n, o in iteritems(ns) if o is obj]
1262 1262 for name in to_delete:
1263 1263 del ns[name]
1264 1264
1265 1265 # displayhook keeps extra references, but not in a dictionary
1266 1266 for name in ('_', '__', '___'):
1267 1267 if getattr(self.displayhook, name) is obj:
1268 1268 setattr(self.displayhook, name, None)
1269 1269
1270 1270 def reset_selective(self, regex=None):
1271 1271 """Clear selective variables from internal namespaces based on a
1272 1272 specified regular expression.
1273 1273
1274 1274 Parameters
1275 1275 ----------
1276 1276 regex : string or compiled pattern, optional
1277 1277 A regular expression pattern that will be used in searching
1278 1278 variable names in the users namespaces.
1279 1279 """
1280 1280 if regex is not None:
1281 1281 try:
1282 1282 m = re.compile(regex)
1283 1283 except TypeError:
1284 1284 raise TypeError('regex must be a string or compiled pattern')
1285 1285 # Search for keys in each namespace that match the given regex
1286 1286 # If a match is found, delete the key/value pair.
1287 1287 for ns in self.all_ns_refs:
1288 1288 for var in ns:
1289 1289 if m.search(var):
1290 1290 del ns[var]
1291 1291
1292 1292 def push(self, variables, interactive=True):
1293 1293 """Inject a group of variables into the IPython user namespace.
1294 1294
1295 1295 Parameters
1296 1296 ----------
1297 1297 variables : dict, str or list/tuple of str
1298 1298 The variables to inject into the user's namespace. If a dict, a
1299 1299 simple update is done. If a str, the string is assumed to have
1300 1300 variable names separated by spaces. A list/tuple of str can also
1301 1301 be used to give the variable names. If just the variable names are
1302 1302 give (list/tuple/str) then the variable values looked up in the
1303 1303 callers frame.
1304 1304 interactive : bool
1305 1305 If True (default), the variables will be listed with the ``who``
1306 1306 magic.
1307 1307 """
1308 1308 vdict = None
1309 1309
1310 1310 # We need a dict of name/value pairs to do namespace updates.
1311 1311 if isinstance(variables, dict):
1312 1312 vdict = variables
1313 1313 elif isinstance(variables, string_types+(list, tuple)):
1314 1314 if isinstance(variables, string_types):
1315 1315 vlist = variables.split()
1316 1316 else:
1317 1317 vlist = variables
1318 1318 vdict = {}
1319 1319 cf = sys._getframe(1)
1320 1320 for name in vlist:
1321 1321 try:
1322 1322 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1323 1323 except:
1324 1324 print('Could not get variable %s from %s' %
1325 1325 (name,cf.f_code.co_name))
1326 1326 else:
1327 1327 raise ValueError('variables must be a dict/str/list/tuple')
1328 1328
1329 1329 # Propagate variables to user namespace
1330 1330 self.user_ns.update(vdict)
1331 1331
1332 1332 # And configure interactive visibility
1333 1333 user_ns_hidden = self.user_ns_hidden
1334 1334 if interactive:
1335 1335 for name in vdict:
1336 1336 user_ns_hidden.pop(name, None)
1337 1337 else:
1338 1338 user_ns_hidden.update(vdict)
1339 1339
1340 1340 def drop_by_id(self, variables):
1341 1341 """Remove a dict of variables from the user namespace, if they are the
1342 1342 same as the values in the dictionary.
1343 1343
1344 1344 This is intended for use by extensions: variables that they've added can
1345 1345 be taken back out if they are unloaded, without removing any that the
1346 1346 user has overwritten.
1347 1347
1348 1348 Parameters
1349 1349 ----------
1350 1350 variables : dict
1351 1351 A dictionary mapping object names (as strings) to the objects.
1352 1352 """
1353 1353 for name, obj in iteritems(variables):
1354 1354 if name in self.user_ns and self.user_ns[name] is obj:
1355 1355 del self.user_ns[name]
1356 1356 self.user_ns_hidden.pop(name, None)
1357 1357
1358 1358 #-------------------------------------------------------------------------
1359 1359 # Things related to object introspection
1360 1360 #-------------------------------------------------------------------------
1361 1361
1362 1362 def _ofind(self, oname, namespaces=None):
1363 1363 """Find an object in the available namespaces.
1364 1364
1365 1365 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1366 1366
1367 1367 Has special code to detect magic functions.
1368 1368 """
1369 1369 oname = oname.strip()
1370 1370 #print '1- oname: <%r>' % oname # dbg
1371 1371 if not oname.startswith(ESC_MAGIC) and \
1372 1372 not oname.startswith(ESC_MAGIC2) and \
1373 1373 not py3compat.isidentifier(oname, dotted=True):
1374 1374 return dict(found=False)
1375 1375
1376 1376 if namespaces is None:
1377 1377 # Namespaces to search in:
1378 1378 # Put them in a list. The order is important so that we
1379 1379 # find things in the same order that Python finds them.
1380 1380 namespaces = [ ('Interactive', self.user_ns),
1381 1381 ('Interactive (global)', self.user_global_ns),
1382 1382 ('Python builtin', builtin_mod.__dict__),
1383 1383 ]
1384 1384
1385 1385 # initialize results to 'null'
1386 1386 found = False; obj = None; ospace = None;
1387 1387 ismagic = False; isalias = False; parent = None
1388 1388
1389 1389 # We need to special-case 'print', which as of python2.6 registers as a
1390 1390 # function but should only be treated as one if print_function was
1391 1391 # loaded with a future import. In this case, just bail.
1392 1392 if (oname == 'print' and not py3compat.PY3 and not \
1393 1393 (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)):
1394 1394 return {'found':found, 'obj':obj, 'namespace':ospace,
1395 1395 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1396 1396
1397 1397 # Look for the given name by splitting it in parts. If the head is
1398 1398 # found, then we look for all the remaining parts as members, and only
1399 1399 # declare success if we can find them all.
1400 1400 oname_parts = oname.split('.')
1401 1401 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1402 1402 for nsname,ns in namespaces:
1403 1403 try:
1404 1404 obj = ns[oname_head]
1405 1405 except KeyError:
1406 1406 continue
1407 1407 else:
1408 1408 #print 'oname_rest:', oname_rest # dbg
1409 1409 for idx, part in enumerate(oname_rest):
1410 1410 try:
1411 1411 parent = obj
1412 1412 # The last part is looked up in a special way to avoid
1413 1413 # descriptor invocation as it may raise or have side
1414 1414 # effects.
1415 1415 if idx == len(oname_rest) - 1:
1416 1416 obj = self._getattr_property(obj, part)
1417 1417 else:
1418 1418 obj = getattr(obj, part)
1419 1419 except:
1420 1420 # Blanket except b/c some badly implemented objects
1421 1421 # allow __getattr__ to raise exceptions other than
1422 1422 # AttributeError, which then crashes IPython.
1423 1423 break
1424 1424 else:
1425 1425 # If we finish the for loop (no break), we got all members
1426 1426 found = True
1427 1427 ospace = nsname
1428 1428 break # namespace loop
1429 1429
1430 1430 # Try to see if it's magic
1431 1431 if not found:
1432 1432 obj = None
1433 1433 if oname.startswith(ESC_MAGIC2):
1434 1434 oname = oname.lstrip(ESC_MAGIC2)
1435 1435 obj = self.find_cell_magic(oname)
1436 1436 elif oname.startswith(ESC_MAGIC):
1437 1437 oname = oname.lstrip(ESC_MAGIC)
1438 1438 obj = self.find_line_magic(oname)
1439 1439 else:
1440 1440 # search without prefix, so run? will find %run?
1441 1441 obj = self.find_line_magic(oname)
1442 1442 if obj is None:
1443 1443 obj = self.find_cell_magic(oname)
1444 1444 if obj is not None:
1445 1445 found = True
1446 1446 ospace = 'IPython internal'
1447 1447 ismagic = True
1448 1448 isalias = isinstance(obj, Alias)
1449 1449
1450 1450 # Last try: special-case some literals like '', [], {}, etc:
1451 1451 if not found and oname_head in ["''",'""','[]','{}','()']:
1452 1452 obj = eval(oname_head)
1453 1453 found = True
1454 1454 ospace = 'Interactive'
1455 1455
1456 1456 return {'found':found, 'obj':obj, 'namespace':ospace,
1457 1457 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1458 1458
1459 1459 @staticmethod
1460 1460 def _getattr_property(obj, attrname):
1461 1461 """Property-aware getattr to use in object finding.
1462 1462
1463 1463 If attrname represents a property, return it unevaluated (in case it has
1464 1464 side effects or raises an error.
1465 1465
1466 1466 """
1467 1467 if not isinstance(obj, type):
1468 1468 try:
1469 1469 # `getattr(type(obj), attrname)` is not guaranteed to return
1470 1470 # `obj`, but does so for property:
1471 1471 #
1472 1472 # property.__get__(self, None, cls) -> self
1473 1473 #
1474 1474 # The universal alternative is to traverse the mro manually
1475 1475 # searching for attrname in class dicts.
1476 1476 attr = getattr(type(obj), attrname)
1477 1477 except AttributeError:
1478 1478 pass
1479 1479 else:
1480 1480 # This relies on the fact that data descriptors (with both
1481 1481 # __get__ & __set__ magic methods) take precedence over
1482 1482 # instance-level attributes:
1483 1483 #
1484 1484 # class A(object):
1485 1485 # @property
1486 1486 # def foobar(self): return 123
1487 1487 # a = A()
1488 1488 # a.__dict__['foobar'] = 345
1489 1489 # a.foobar # == 123
1490 1490 #
1491 1491 # So, a property may be returned right away.
1492 1492 if isinstance(attr, property):
1493 1493 return attr
1494 1494
1495 1495 # Nothing helped, fall back.
1496 1496 return getattr(obj, attrname)
1497 1497
1498 1498 def _object_find(self, oname, namespaces=None):
1499 1499 """Find an object and return a struct with info about it."""
1500 1500 return Struct(self._ofind(oname, namespaces))
1501 1501
1502 1502 def _inspect(self, meth, oname, namespaces=None, **kw):
1503 1503 """Generic interface to the inspector system.
1504 1504
1505 1505 This function is meant to be called by pdef, pdoc & friends.
1506 1506 """
1507 1507 info = self._object_find(oname, namespaces)
1508 1508 docformat = sphinxify if self.sphinxify_docstring else None
1509 1509 if info.found:
1510 1510 pmethod = getattr(self.inspector, meth)
1511 1511 # TODO: only apply format_screen to the plain/text repr of the mime
1512 1512 # bundle.
1513 1513 formatter = format_screen if info.ismagic else docformat
1514 1514 if meth == 'pdoc':
1515 1515 pmethod(info.obj, oname, formatter)
1516 1516 elif meth == 'pinfo':
1517 1517 pmethod(info.obj, oname, formatter, info,
1518 1518 enable_html_pager=self.enable_html_pager, **kw)
1519 1519 else:
1520 1520 pmethod(info.obj, oname)
1521 1521 else:
1522 1522 print('Object `%s` not found.' % oname)
1523 1523 return 'not found' # so callers can take other action
1524 1524
1525 1525 def object_inspect(self, oname, detail_level=0):
1526 1526 """Get object info about oname"""
1527 1527 with self.builtin_trap:
1528 1528 info = self._object_find(oname)
1529 1529 if info.found:
1530 1530 return self.inspector.info(info.obj, oname, info=info,
1531 1531 detail_level=detail_level
1532 1532 )
1533 1533 else:
1534 1534 return oinspect.object_info(name=oname, found=False)
1535 1535
1536 1536 def object_inspect_text(self, oname, detail_level=0):
1537 1537 """Get object info as formatted text"""
1538 1538 return self.object_inspect_mime(oname, detail_level)['text/plain']
1539 1539
1540 1540 def object_inspect_mime(self, oname, detail_level=0):
1541 1541 """Get object info as a mimebundle of formatted representations.
1542 1542
1543 1543 A mimebundle is a dictionary, keyed by mime-type.
1544 1544 It must always have the key `'text/plain'`.
1545 1545 """
1546 1546 with self.builtin_trap:
1547 1547 info = self._object_find(oname)
1548 1548 if info.found:
1549 1549 return self.inspector._get_info(info.obj, oname, info=info,
1550 1550 detail_level=detail_level
1551 1551 )
1552 1552 else:
1553 1553 raise KeyError(oname)
1554 1554
1555 1555 #-------------------------------------------------------------------------
1556 1556 # Things related to history management
1557 1557 #-------------------------------------------------------------------------
1558 1558
1559 1559 def init_history(self):
1560 1560 """Sets up the command history, and starts regular autosaves."""
1561 1561 self.history_manager = HistoryManager(shell=self, parent=self)
1562 1562 self.configurables.append(self.history_manager)
1563 1563
1564 1564 #-------------------------------------------------------------------------
1565 1565 # Things related to exception handling and tracebacks (not debugging)
1566 1566 #-------------------------------------------------------------------------
1567 1567
1568 1568 debugger_cls = Pdb
1569 1569
1570 1570 def init_traceback_handlers(self, custom_exceptions):
1571 1571 # Syntax error handler.
1572 1572 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1573 1573
1574 1574 # The interactive one is initialized with an offset, meaning we always
1575 1575 # want to remove the topmost item in the traceback, which is our own
1576 1576 # internal code. Valid modes: ['Plain','Context','Verbose']
1577 1577 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1578 1578 color_scheme='NoColor',
1579 1579 tb_offset = 1,
1580 1580 check_cache=check_linecache_ipython,
1581 1581 debugger_cls=self.debugger_cls)
1582 1582
1583 1583 # The instance will store a pointer to the system-wide exception hook,
1584 1584 # so that runtime code (such as magics) can access it. This is because
1585 1585 # during the read-eval loop, it may get temporarily overwritten.
1586 1586 self.sys_excepthook = sys.excepthook
1587 1587
1588 1588 # and add any custom exception handlers the user may have specified
1589 1589 self.set_custom_exc(*custom_exceptions)
1590 1590
1591 1591 # Set the exception mode
1592 1592 self.InteractiveTB.set_mode(mode=self.xmode)
1593 1593
1594 1594 def set_custom_exc(self, exc_tuple, handler):
1595 1595 """set_custom_exc(exc_tuple, handler)
1596 1596
1597 1597 Set a custom exception handler, which will be called if any of the
1598 1598 exceptions in exc_tuple occur in the mainloop (specifically, in the
1599 1599 run_code() method).
1600 1600
1601 1601 Parameters
1602 1602 ----------
1603 1603
1604 1604 exc_tuple : tuple of exception classes
1605 1605 A *tuple* of exception classes, for which to call the defined
1606 1606 handler. It is very important that you use a tuple, and NOT A
1607 1607 LIST here, because of the way Python's except statement works. If
1608 1608 you only want to trap a single exception, use a singleton tuple::
1609 1609
1610 1610 exc_tuple == (MyCustomException,)
1611 1611
1612 1612 handler : callable
1613 1613 handler must have the following signature::
1614 1614
1615 1615 def my_handler(self, etype, value, tb, tb_offset=None):
1616 1616 ...
1617 1617 return structured_traceback
1618 1618
1619 1619 Your handler must return a structured traceback (a list of strings),
1620 1620 or None.
1621 1621
1622 1622 This will be made into an instance method (via types.MethodType)
1623 1623 of IPython itself, and it will be called if any of the exceptions
1624 1624 listed in the exc_tuple are caught. If the handler is None, an
1625 1625 internal basic one is used, which just prints basic info.
1626 1626
1627 1627 To protect IPython from crashes, if your handler ever raises an
1628 1628 exception or returns an invalid result, it will be immediately
1629 1629 disabled.
1630 1630
1631 1631 WARNING: by putting in your own exception handler into IPython's main
1632 1632 execution loop, you run a very good chance of nasty crashes. This
1633 1633 facility should only be used if you really know what you are doing."""
1634 1634
1635 1635 assert type(exc_tuple)==type(()) , \
1636 1636 "The custom exceptions must be given AS A TUPLE."
1637 1637
1638 1638 def dummy_handler(self, etype, value, tb, tb_offset=None):
1639 1639 print('*** Simple custom exception handler ***')
1640 1640 print('Exception type :',etype)
1641 1641 print('Exception value:',value)
1642 1642 print('Traceback :',tb)
1643 1643 #print 'Source code :','\n'.join(self.buffer)
1644 1644
1645 1645 def validate_stb(stb):
1646 1646 """validate structured traceback return type
1647 1647
1648 1648 return type of CustomTB *should* be a list of strings, but allow
1649 1649 single strings or None, which are harmless.
1650 1650
1651 1651 This function will *always* return a list of strings,
1652 1652 and will raise a TypeError if stb is inappropriate.
1653 1653 """
1654 1654 msg = "CustomTB must return list of strings, not %r" % stb
1655 1655 if stb is None:
1656 1656 return []
1657 1657 elif isinstance(stb, string_types):
1658 1658 return [stb]
1659 1659 elif not isinstance(stb, list):
1660 1660 raise TypeError(msg)
1661 1661 # it's a list
1662 1662 for line in stb:
1663 1663 # check every element
1664 1664 if not isinstance(line, string_types):
1665 1665 raise TypeError(msg)
1666 1666 return stb
1667 1667
1668 1668 if handler is None:
1669 1669 wrapped = dummy_handler
1670 1670 else:
1671 1671 def wrapped(self,etype,value,tb,tb_offset=None):
1672 1672 """wrap CustomTB handler, to protect IPython from user code
1673 1673
1674 1674 This makes it harder (but not impossible) for custom exception
1675 1675 handlers to crash IPython.
1676 1676 """
1677 1677 try:
1678 1678 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1679 1679 return validate_stb(stb)
1680 1680 except:
1681 1681 # clear custom handler immediately
1682 1682 self.set_custom_exc((), None)
1683 1683 print("Custom TB Handler failed, unregistering", file=sys.stderr)
1684 1684 # show the exception in handler first
1685 1685 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1686 1686 print(self.InteractiveTB.stb2text(stb))
1687 1687 print("The original exception:")
1688 1688 stb = self.InteractiveTB.structured_traceback(
1689 1689 (etype,value,tb), tb_offset=tb_offset
1690 1690 )
1691 1691 return stb
1692 1692
1693 1693 self.CustomTB = types.MethodType(wrapped,self)
1694 1694 self.custom_exceptions = exc_tuple
1695 1695
1696 1696 def excepthook(self, etype, value, tb):
1697 1697 """One more defense for GUI apps that call sys.excepthook.
1698 1698
1699 1699 GUI frameworks like wxPython trap exceptions and call
1700 1700 sys.excepthook themselves. I guess this is a feature that
1701 1701 enables them to keep running after exceptions that would
1702 1702 otherwise kill their mainloop. This is a bother for IPython
1703 1703 which excepts to catch all of the program exceptions with a try:
1704 1704 except: statement.
1705 1705
1706 1706 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1707 1707 any app directly invokes sys.excepthook, it will look to the user like
1708 1708 IPython crashed. In order to work around this, we can disable the
1709 1709 CrashHandler and replace it with this excepthook instead, which prints a
1710 1710 regular traceback using our InteractiveTB. In this fashion, apps which
1711 1711 call sys.excepthook will generate a regular-looking exception from
1712 1712 IPython, and the CrashHandler will only be triggered by real IPython
1713 1713 crashes.
1714 1714
1715 1715 This hook should be used sparingly, only in places which are not likely
1716 1716 to be true IPython errors.
1717 1717 """
1718 1718 self.showtraceback((etype, value, tb), tb_offset=0)
1719 1719
1720 1720 def _get_exc_info(self, exc_tuple=None):
1721 1721 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
1722 1722
1723 1723 Ensures sys.last_type,value,traceback hold the exc_info we found,
1724 1724 from whichever source.
1725 1725
1726 1726 raises ValueError if none of these contain any information
1727 1727 """
1728 1728 if exc_tuple is None:
1729 1729 etype, value, tb = sys.exc_info()
1730 1730 else:
1731 1731 etype, value, tb = exc_tuple
1732 1732
1733 1733 if etype is None:
1734 1734 if hasattr(sys, 'last_type'):
1735 1735 etype, value, tb = sys.last_type, sys.last_value, \
1736 1736 sys.last_traceback
1737 1737
1738 1738 if etype is None:
1739 1739 raise ValueError("No exception to find")
1740 1740
1741 1741 # Now store the exception info in sys.last_type etc.
1742 1742 # WARNING: these variables are somewhat deprecated and not
1743 1743 # necessarily safe to use in a threaded environment, but tools
1744 1744 # like pdb depend on their existence, so let's set them. If we
1745 1745 # find problems in the field, we'll need to revisit their use.
1746 1746 sys.last_type = etype
1747 1747 sys.last_value = value
1748 1748 sys.last_traceback = tb
1749 1749
1750 1750 return etype, value, tb
1751 1751
1752 1752 def show_usage_error(self, exc):
1753 1753 """Show a short message for UsageErrors
1754 1754
1755 1755 These are special exceptions that shouldn't show a traceback.
1756 1756 """
1757 1757 print("UsageError: %s" % exc, file=sys.stderr)
1758 1758
1759 1759 def get_exception_only(self, exc_tuple=None):
1760 1760 """
1761 1761 Return as a string (ending with a newline) the exception that
1762 1762 just occurred, without any traceback.
1763 1763 """
1764 1764 etype, value, tb = self._get_exc_info(exc_tuple)
1765 1765 msg = traceback.format_exception_only(etype, value)
1766 1766 return ''.join(msg)
1767 1767
1768 1768 def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None,
1769 1769 exception_only=False):
1770 1770 """Display the exception that just occurred.
1771 1771
1772 1772 If nothing is known about the exception, this is the method which
1773 1773 should be used throughout the code for presenting user tracebacks,
1774 1774 rather than directly invoking the InteractiveTB object.
1775 1775
1776 1776 A specific showsyntaxerror() also exists, but this method can take
1777 1777 care of calling it if needed, so unless you are explicitly catching a
1778 1778 SyntaxError exception, don't try to analyze the stack manually and
1779 1779 simply call this method."""
1780 1780
1781 1781 try:
1782 1782 try:
1783 1783 etype, value, tb = self._get_exc_info(exc_tuple)
1784 1784 except ValueError:
1785 1785 print('No traceback available to show.', file=sys.stderr)
1786 1786 return
1787 1787
1788 1788 if issubclass(etype, SyntaxError):
1789 1789 # Though this won't be called by syntax errors in the input
1790 1790 # line, there may be SyntaxError cases with imported code.
1791 1791 self.showsyntaxerror(filename)
1792 1792 elif etype is UsageError:
1793 1793 self.show_usage_error(value)
1794 1794 else:
1795 1795 if exception_only:
1796 1796 stb = ['An exception has occurred, use %tb to see '
1797 1797 'the full traceback.\n']
1798 1798 stb.extend(self.InteractiveTB.get_exception_only(etype,
1799 1799 value))
1800 1800 else:
1801 1801 try:
1802 1802 # Exception classes can customise their traceback - we
1803 1803 # use this in IPython.parallel for exceptions occurring
1804 1804 # in the engines. This should return a list of strings.
1805 1805 stb = value._render_traceback_()
1806 1806 except Exception:
1807 1807 stb = self.InteractiveTB.structured_traceback(etype,
1808 1808 value, tb, tb_offset=tb_offset)
1809 1809
1810 1810 self._showtraceback(etype, value, stb)
1811 1811 if self.call_pdb:
1812 1812 # drop into debugger
1813 1813 self.debugger(force=True)
1814 1814 return
1815 1815
1816 1816 # Actually show the traceback
1817 1817 self._showtraceback(etype, value, stb)
1818 1818
1819 1819 except KeyboardInterrupt:
1820 1820 print('\n' + self.get_exception_only(), file=sys.stderr)
1821 1821
1822 1822 def _showtraceback(self, etype, evalue, stb):
1823 1823 """Actually show a traceback.
1824 1824
1825 1825 Subclasses may override this method to put the traceback on a different
1826 1826 place, like a side channel.
1827 1827 """
1828 1828 print(self.InteractiveTB.stb2text(stb))
1829 1829
1830 1830 def showsyntaxerror(self, filename=None):
1831 1831 """Display the syntax error that just occurred.
1832 1832
1833 1833 This doesn't display a stack trace because there isn't one.
1834 1834
1835 1835 If a filename is given, it is stuffed in the exception instead
1836 1836 of what was there before (because Python's parser always uses
1837 1837 "<string>" when reading from a string).
1838 1838 """
1839 1839 etype, value, last_traceback = self._get_exc_info()
1840 1840
1841 1841 if filename and issubclass(etype, SyntaxError):
1842 1842 try:
1843 1843 value.filename = filename
1844 1844 except:
1845 1845 # Not the format we expect; leave it alone
1846 1846 pass
1847 1847
1848 1848 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1849 1849 self._showtraceback(etype, value, stb)
1850 1850
1851 1851 # This is overridden in TerminalInteractiveShell to show a message about
1852 1852 # the %paste magic.
1853 1853 def showindentationerror(self):
1854 1854 """Called by run_cell when there's an IndentationError in code entered
1855 1855 at the prompt.
1856 1856
1857 1857 This is overridden in TerminalInteractiveShell to show a message about
1858 1858 the %paste magic."""
1859 1859 self.showsyntaxerror()
1860 1860
1861 1861 #-------------------------------------------------------------------------
1862 1862 # Things related to readline
1863 1863 #-------------------------------------------------------------------------
1864 1864
1865 1865 def init_readline(self):
1866 1866 """DEPRECATED
1867 1867
1868 1868 Moved to terminal subclass, here only to simplify the init logic."""
1869 1869 # Set a number of methods that depend on readline to be no-op
1870 1870 warnings.warn('`init_readline` is no-op since IPython 5.0 and is Deprecated',
1871 1871 DeprecationWarning, stacklevel=2)
1872 1872 self.set_custom_completer = no_op
1873 1873
1874 1874 @skip_doctest
1875 1875 def set_next_input(self, s, replace=False):
1876 1876 """ Sets the 'default' input string for the next command line.
1877 1877
1878 1878 Example::
1879 1879
1880 1880 In [1]: _ip.set_next_input("Hello Word")
1881 1881 In [2]: Hello Word_ # cursor is here
1882 1882 """
1883 1883 self.rl_next_input = py3compat.cast_bytes_py2(s)
1884 1884
1885 1885 def _indent_current_str(self):
1886 1886 """return the current level of indentation as a string"""
1887 1887 return self.input_splitter.indent_spaces * ' '
1888 1888
1889 1889 #-------------------------------------------------------------------------
1890 1890 # Things related to text completion
1891 1891 #-------------------------------------------------------------------------
1892 1892
1893 1893 def init_completer(self):
1894 1894 """Initialize the completion machinery.
1895 1895
1896 1896 This creates completion machinery that can be used by client code,
1897 1897 either interactively in-process (typically triggered by the readline
1898 1898 library), programmatically (such as in test suites) or out-of-process
1899 1899 (typically over the network by remote frontends).
1900 1900 """
1901 1901 from IPython.core.completer import IPCompleter
1902 1902 from IPython.core.completerlib import (module_completer,
1903 1903 magic_run_completer, cd_completer, reset_completer)
1904 1904
1905 1905 self.Completer = IPCompleter(shell=self,
1906 1906 namespace=self.user_ns,
1907 1907 global_namespace=self.user_global_ns,
1908 use_readline=False,
1909 1908 parent=self,
1910 1909 )
1911 1910 self.configurables.append(self.Completer)
1912 1911
1913 1912 # Add custom completers to the basic ones built into IPCompleter
1914 1913 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1915 1914 self.strdispatchers['complete_command'] = sdisp
1916 1915 self.Completer.custom_completers = sdisp
1917 1916
1918 1917 self.set_hook('complete_command', module_completer, str_key = 'import')
1919 1918 self.set_hook('complete_command', module_completer, str_key = 'from')
1920 1919 self.set_hook('complete_command', module_completer, str_key = '%aimport')
1921 1920 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1922 1921 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1923 1922 self.set_hook('complete_command', reset_completer, str_key = '%reset')
1924 1923
1925 1924
1926 1925 @skip_doctest_py2
1927 1926 def complete(self, text, line=None, cursor_pos=None):
1928 1927 """Return the completed text and a list of completions.
1929 1928
1930 1929 Parameters
1931 1930 ----------
1932 1931
1933 1932 text : string
1934 1933 A string of text to be completed on. It can be given as empty and
1935 1934 instead a line/position pair are given. In this case, the
1936 1935 completer itself will split the line like readline does.
1937 1936
1938 1937 line : string, optional
1939 1938 The complete line that text is part of.
1940 1939
1941 1940 cursor_pos : int, optional
1942 1941 The position of the cursor on the input line.
1943 1942
1944 1943 Returns
1945 1944 -------
1946 1945 text : string
1947 1946 The actual text that was completed.
1948 1947
1949 1948 matches : list
1950 1949 A sorted list with all possible completions.
1951 1950
1952 1951 The optional arguments allow the completion to take more context into
1953 1952 account, and are part of the low-level completion API.
1954 1953
1955 1954 This is a wrapper around the completion mechanism, similar to what
1956 1955 readline does at the command line when the TAB key is hit. By
1957 1956 exposing it as a method, it can be used by other non-readline
1958 1957 environments (such as GUIs) for text completion.
1959 1958
1960 1959 Simple usage example:
1961 1960
1962 1961 In [1]: x = 'hello'
1963 1962
1964 1963 In [2]: _ip.complete('x.l')
1965 1964 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1966 1965 """
1967 1966
1968 1967 # Inject names into __builtin__ so we can complete on the added names.
1969 1968 with self.builtin_trap:
1970 1969 return self.Completer.complete(text, line, cursor_pos)
1971 1970
1972 1971 def set_custom_completer(self, completer, pos=0):
1973 1972 """Adds a new custom completer function.
1974 1973
1975 1974 The position argument (defaults to 0) is the index in the completers
1976 1975 list where you want the completer to be inserted."""
1977 1976
1978 1977 newcomp = types.MethodType(completer,self.Completer)
1979 1978 self.Completer.matchers.insert(pos,newcomp)
1980 1979
1981 1980 def set_completer_frame(self, frame=None):
1982 1981 """Set the frame of the completer."""
1983 1982 if frame:
1984 1983 self.Completer.namespace = frame.f_locals
1985 1984 self.Completer.global_namespace = frame.f_globals
1986 1985 else:
1987 1986 self.Completer.namespace = self.user_ns
1988 1987 self.Completer.global_namespace = self.user_global_ns
1989 1988
1990 1989 #-------------------------------------------------------------------------
1991 1990 # Things related to magics
1992 1991 #-------------------------------------------------------------------------
1993 1992
1994 1993 def init_magics(self):
1995 1994 from IPython.core import magics as m
1996 1995 self.magics_manager = magic.MagicsManager(shell=self,
1997 1996 parent=self,
1998 1997 user_magics=m.UserMagics(self))
1999 1998 self.configurables.append(self.magics_manager)
2000 1999
2001 2000 # Expose as public API from the magics manager
2002 2001 self.register_magics = self.magics_manager.register
2003 2002
2004 2003 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
2005 2004 m.ConfigMagics, m.DisplayMagics, m.ExecutionMagics,
2006 2005 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2007 2006 m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics,
2008 2007 )
2009 2008
2010 2009 # Register Magic Aliases
2011 2010 mman = self.magics_manager
2012 2011 # FIXME: magic aliases should be defined by the Magics classes
2013 2012 # or in MagicsManager, not here
2014 2013 mman.register_alias('ed', 'edit')
2015 2014 mman.register_alias('hist', 'history')
2016 2015 mman.register_alias('rep', 'recall')
2017 2016 mman.register_alias('SVG', 'svg', 'cell')
2018 2017 mman.register_alias('HTML', 'html', 'cell')
2019 2018 mman.register_alias('file', 'writefile', 'cell')
2020 2019
2021 2020 # FIXME: Move the color initialization to the DisplayHook, which
2022 2021 # should be split into a prompt manager and displayhook. We probably
2023 2022 # even need a centralize colors management object.
2024 2023 self.magic('colors %s' % self.colors)
2025 2024
2026 2025 # Defined here so that it's included in the documentation
2027 2026 @functools.wraps(magic.MagicsManager.register_function)
2028 2027 def register_magic_function(self, func, magic_kind='line', magic_name=None):
2029 2028 self.magics_manager.register_function(func,
2030 2029 magic_kind=magic_kind, magic_name=magic_name)
2031 2030
2032 2031 def run_line_magic(self, magic_name, line):
2033 2032 """Execute the given line magic.
2034 2033
2035 2034 Parameters
2036 2035 ----------
2037 2036 magic_name : str
2038 2037 Name of the desired magic function, without '%' prefix.
2039 2038
2040 2039 line : str
2041 2040 The rest of the input line as a single string.
2042 2041 """
2043 2042 fn = self.find_line_magic(magic_name)
2044 2043 if fn is None:
2045 2044 cm = self.find_cell_magic(magic_name)
2046 2045 etpl = "Line magic function `%%%s` not found%s."
2047 2046 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2048 2047 'did you mean that instead?)' % magic_name )
2049 2048 error(etpl % (magic_name, extra))
2050 2049 else:
2051 2050 # Note: this is the distance in the stack to the user's frame.
2052 2051 # This will need to be updated if the internal calling logic gets
2053 2052 # refactored, or else we'll be expanding the wrong variables.
2054 2053 stack_depth = 2
2055 2054 magic_arg_s = self.var_expand(line, stack_depth)
2056 2055 # Put magic args in a list so we can call with f(*a) syntax
2057 2056 args = [magic_arg_s]
2058 2057 kwargs = {}
2059 2058 # Grab local namespace if we need it:
2060 2059 if getattr(fn, "needs_local_scope", False):
2061 2060 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2062 2061 with self.builtin_trap:
2063 2062 result = fn(*args,**kwargs)
2064 2063 return result
2065 2064
2066 2065 def run_cell_magic(self, magic_name, line, cell):
2067 2066 """Execute the given cell magic.
2068 2067
2069 2068 Parameters
2070 2069 ----------
2071 2070 magic_name : str
2072 2071 Name of the desired magic function, without '%' prefix.
2073 2072
2074 2073 line : str
2075 2074 The rest of the first input line as a single string.
2076 2075
2077 2076 cell : str
2078 2077 The body of the cell as a (possibly multiline) string.
2079 2078 """
2080 2079 fn = self.find_cell_magic(magic_name)
2081 2080 if fn is None:
2082 2081 lm = self.find_line_magic(magic_name)
2083 2082 etpl = "Cell magic `%%{0}` not found{1}."
2084 2083 extra = '' if lm is None else (' (But line magic `%{0}` exists, '
2085 2084 'did you mean that instead?)'.format(magic_name))
2086 2085 error(etpl.format(magic_name, extra))
2087 2086 elif cell == '':
2088 2087 message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
2089 2088 if self.find_line_magic(magic_name) is not None:
2090 2089 message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
2091 2090 raise UsageError(message)
2092 2091 else:
2093 2092 # Note: this is the distance in the stack to the user's frame.
2094 2093 # This will need to be updated if the internal calling logic gets
2095 2094 # refactored, or else we'll be expanding the wrong variables.
2096 2095 stack_depth = 2
2097 2096 magic_arg_s = self.var_expand(line, stack_depth)
2098 2097 with self.builtin_trap:
2099 2098 result = fn(magic_arg_s, cell)
2100 2099 return result
2101 2100
2102 2101 def find_line_magic(self, magic_name):
2103 2102 """Find and return a line magic by name.
2104 2103
2105 2104 Returns None if the magic isn't found."""
2106 2105 return self.magics_manager.magics['line'].get(magic_name)
2107 2106
2108 2107 def find_cell_magic(self, magic_name):
2109 2108 """Find and return a cell magic by name.
2110 2109
2111 2110 Returns None if the magic isn't found."""
2112 2111 return self.magics_manager.magics['cell'].get(magic_name)
2113 2112
2114 2113 def find_magic(self, magic_name, magic_kind='line'):
2115 2114 """Find and return a magic of the given type by name.
2116 2115
2117 2116 Returns None if the magic isn't found."""
2118 2117 return self.magics_manager.magics[magic_kind].get(magic_name)
2119 2118
2120 2119 def magic(self, arg_s):
2121 2120 """DEPRECATED. Use run_line_magic() instead.
2122 2121
2123 2122 Call a magic function by name.
2124 2123
2125 2124 Input: a string containing the name of the magic function to call and
2126 2125 any additional arguments to be passed to the magic.
2127 2126
2128 2127 magic('name -opt foo bar') is equivalent to typing at the ipython
2129 2128 prompt:
2130 2129
2131 2130 In[1]: %name -opt foo bar
2132 2131
2133 2132 To call a magic without arguments, simply use magic('name').
2134 2133
2135 2134 This provides a proper Python function to call IPython's magics in any
2136 2135 valid Python code you can type at the interpreter, including loops and
2137 2136 compound statements.
2138 2137 """
2139 2138 # TODO: should we issue a loud deprecation warning here?
2140 2139 magic_name, _, magic_arg_s = arg_s.partition(' ')
2141 2140 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2142 2141 return self.run_line_magic(magic_name, magic_arg_s)
2143 2142
2144 2143 #-------------------------------------------------------------------------
2145 2144 # Things related to macros
2146 2145 #-------------------------------------------------------------------------
2147 2146
2148 2147 def define_macro(self, name, themacro):
2149 2148 """Define a new macro
2150 2149
2151 2150 Parameters
2152 2151 ----------
2153 2152 name : str
2154 2153 The name of the macro.
2155 2154 themacro : str or Macro
2156 2155 The action to do upon invoking the macro. If a string, a new
2157 2156 Macro object is created by passing the string to it.
2158 2157 """
2159 2158
2160 2159 from IPython.core import macro
2161 2160
2162 2161 if isinstance(themacro, string_types):
2163 2162 themacro = macro.Macro(themacro)
2164 2163 if not isinstance(themacro, macro.Macro):
2165 2164 raise ValueError('A macro must be a string or a Macro instance.')
2166 2165 self.user_ns[name] = themacro
2167 2166
2168 2167 #-------------------------------------------------------------------------
2169 2168 # Things related to the running of system commands
2170 2169 #-------------------------------------------------------------------------
2171 2170
2172 2171 def system_piped(self, cmd):
2173 2172 """Call the given cmd in a subprocess, piping stdout/err
2174 2173
2175 2174 Parameters
2176 2175 ----------
2177 2176 cmd : str
2178 2177 Command to execute (can not end in '&', as background processes are
2179 2178 not supported. Should not be a command that expects input
2180 2179 other than simple text.
2181 2180 """
2182 2181 if cmd.rstrip().endswith('&'):
2183 2182 # this is *far* from a rigorous test
2184 2183 # We do not support backgrounding processes because we either use
2185 2184 # pexpect or pipes to read from. Users can always just call
2186 2185 # os.system() or use ip.system=ip.system_raw
2187 2186 # if they really want a background process.
2188 2187 raise OSError("Background processes not supported.")
2189 2188
2190 2189 # we explicitly do NOT return the subprocess status code, because
2191 2190 # a non-None value would trigger :func:`sys.displayhook` calls.
2192 2191 # Instead, we store the exit_code in user_ns.
2193 2192 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2194 2193
2195 2194 def system_raw(self, cmd):
2196 2195 """Call the given cmd in a subprocess using os.system on Windows or
2197 2196 subprocess.call using the system shell on other platforms.
2198 2197
2199 2198 Parameters
2200 2199 ----------
2201 2200 cmd : str
2202 2201 Command to execute.
2203 2202 """
2204 2203 cmd = self.var_expand(cmd, depth=1)
2205 2204 # protect os.system from UNC paths on Windows, which it can't handle:
2206 2205 if sys.platform == 'win32':
2207 2206 from IPython.utils._process_win32 import AvoidUNCPath
2208 2207 with AvoidUNCPath() as path:
2209 2208 if path is not None:
2210 2209 cmd = '"pushd %s &&"%s' % (path, cmd)
2211 2210 cmd = py3compat.unicode_to_str(cmd)
2212 2211 try:
2213 2212 ec = os.system(cmd)
2214 2213 except KeyboardInterrupt:
2215 2214 print('\n' + self.get_exception_only(), file=sys.stderr)
2216 2215 ec = -2
2217 2216 else:
2218 2217 cmd = py3compat.unicode_to_str(cmd)
2219 2218 # For posix the result of the subprocess.call() below is an exit
2220 2219 # code, which by convention is zero for success, positive for
2221 2220 # program failure. Exit codes above 128 are reserved for signals,
2222 2221 # and the formula for converting a signal to an exit code is usually
2223 2222 # signal_number+128. To more easily differentiate between exit
2224 2223 # codes and signals, ipython uses negative numbers. For instance
2225 2224 # since control-c is signal 2 but exit code 130, ipython's
2226 2225 # _exit_code variable will read -2. Note that some shells like
2227 2226 # csh and fish don't follow sh/bash conventions for exit codes.
2228 2227 executable = os.environ.get('SHELL', None)
2229 2228 try:
2230 2229 # Use env shell instead of default /bin/sh
2231 2230 ec = subprocess.call(cmd, shell=True, executable=executable)
2232 2231 except KeyboardInterrupt:
2233 2232 # intercept control-C; a long traceback is not useful here
2234 2233 print('\n' + self.get_exception_only(), file=sys.stderr)
2235 2234 ec = 130
2236 2235 if ec > 128:
2237 2236 ec = -(ec - 128)
2238 2237
2239 2238 # We explicitly do NOT return the subprocess status code, because
2240 2239 # a non-None value would trigger :func:`sys.displayhook` calls.
2241 2240 # Instead, we store the exit_code in user_ns. Note the semantics
2242 2241 # of _exit_code: for control-c, _exit_code == -signal.SIGNIT,
2243 2242 # but raising SystemExit(_exit_code) will give status 254!
2244 2243 self.user_ns['_exit_code'] = ec
2245 2244
2246 2245 # use piped system by default, because it is better behaved
2247 2246 system = system_piped
2248 2247
2249 2248 def getoutput(self, cmd, split=True, depth=0):
2250 2249 """Get output (possibly including stderr) from a subprocess.
2251 2250
2252 2251 Parameters
2253 2252 ----------
2254 2253 cmd : str
2255 2254 Command to execute (can not end in '&', as background processes are
2256 2255 not supported.
2257 2256 split : bool, optional
2258 2257 If True, split the output into an IPython SList. Otherwise, an
2259 2258 IPython LSString is returned. These are objects similar to normal
2260 2259 lists and strings, with a few convenience attributes for easier
2261 2260 manipulation of line-based output. You can use '?' on them for
2262 2261 details.
2263 2262 depth : int, optional
2264 2263 How many frames above the caller are the local variables which should
2265 2264 be expanded in the command string? The default (0) assumes that the
2266 2265 expansion variables are in the stack frame calling this function.
2267 2266 """
2268 2267 if cmd.rstrip().endswith('&'):
2269 2268 # this is *far* from a rigorous test
2270 2269 raise OSError("Background processes not supported.")
2271 2270 out = getoutput(self.var_expand(cmd, depth=depth+1))
2272 2271 if split:
2273 2272 out = SList(out.splitlines())
2274 2273 else:
2275 2274 out = LSString(out)
2276 2275 return out
2277 2276
2278 2277 #-------------------------------------------------------------------------
2279 2278 # Things related to aliases
2280 2279 #-------------------------------------------------------------------------
2281 2280
2282 2281 def init_alias(self):
2283 2282 self.alias_manager = AliasManager(shell=self, parent=self)
2284 2283 self.configurables.append(self.alias_manager)
2285 2284
2286 2285 #-------------------------------------------------------------------------
2287 2286 # Things related to extensions
2288 2287 #-------------------------------------------------------------------------
2289 2288
2290 2289 def init_extension_manager(self):
2291 2290 self.extension_manager = ExtensionManager(shell=self, parent=self)
2292 2291 self.configurables.append(self.extension_manager)
2293 2292
2294 2293 #-------------------------------------------------------------------------
2295 2294 # Things related to payloads
2296 2295 #-------------------------------------------------------------------------
2297 2296
2298 2297 def init_payload(self):
2299 2298 self.payload_manager = PayloadManager(parent=self)
2300 2299 self.configurables.append(self.payload_manager)
2301 2300
2302 2301 #-------------------------------------------------------------------------
2303 2302 # Things related to the prefilter
2304 2303 #-------------------------------------------------------------------------
2305 2304
2306 2305 def init_prefilter(self):
2307 2306 self.prefilter_manager = PrefilterManager(shell=self, parent=self)
2308 2307 self.configurables.append(self.prefilter_manager)
2309 2308 # Ultimately this will be refactored in the new interpreter code, but
2310 2309 # for now, we should expose the main prefilter method (there's legacy
2311 2310 # code out there that may rely on this).
2312 2311 self.prefilter = self.prefilter_manager.prefilter_lines
2313 2312
2314 2313 def auto_rewrite_input(self, cmd):
2315 2314 """Print to the screen the rewritten form of the user's command.
2316 2315
2317 2316 This shows visual feedback by rewriting input lines that cause
2318 2317 automatic calling to kick in, like::
2319 2318
2320 2319 /f x
2321 2320
2322 2321 into::
2323 2322
2324 2323 ------> f(x)
2325 2324
2326 2325 after the user's input prompt. This helps the user understand that the
2327 2326 input line was transformed automatically by IPython.
2328 2327 """
2329 2328 if not self.show_rewritten_input:
2330 2329 return
2331 2330
2332 2331 # This is overridden in TerminalInteractiveShell to use fancy prompts
2333 2332 print("------> " + cmd)
2334 2333
2335 2334 #-------------------------------------------------------------------------
2336 2335 # Things related to extracting values/expressions from kernel and user_ns
2337 2336 #-------------------------------------------------------------------------
2338 2337
2339 2338 def _user_obj_error(self):
2340 2339 """return simple exception dict
2341 2340
2342 2341 for use in user_expressions
2343 2342 """
2344 2343
2345 2344 etype, evalue, tb = self._get_exc_info()
2346 2345 stb = self.InteractiveTB.get_exception_only(etype, evalue)
2347 2346
2348 2347 exc_info = {
2349 2348 u'status' : 'error',
2350 2349 u'traceback' : stb,
2351 2350 u'ename' : unicode_type(etype.__name__),
2352 2351 u'evalue' : py3compat.safe_unicode(evalue),
2353 2352 }
2354 2353
2355 2354 return exc_info
2356 2355
2357 2356 def _format_user_obj(self, obj):
2358 2357 """format a user object to display dict
2359 2358
2360 2359 for use in user_expressions
2361 2360 """
2362 2361
2363 2362 data, md = self.display_formatter.format(obj)
2364 2363 value = {
2365 2364 'status' : 'ok',
2366 2365 'data' : data,
2367 2366 'metadata' : md,
2368 2367 }
2369 2368 return value
2370 2369
2371 2370 def user_expressions(self, expressions):
2372 2371 """Evaluate a dict of expressions in the user's namespace.
2373 2372
2374 2373 Parameters
2375 2374 ----------
2376 2375 expressions : dict
2377 2376 A dict with string keys and string values. The expression values
2378 2377 should be valid Python expressions, each of which will be evaluated
2379 2378 in the user namespace.
2380 2379
2381 2380 Returns
2382 2381 -------
2383 2382 A dict, keyed like the input expressions dict, with the rich mime-typed
2384 2383 display_data of each value.
2385 2384 """
2386 2385 out = {}
2387 2386 user_ns = self.user_ns
2388 2387 global_ns = self.user_global_ns
2389 2388
2390 2389 for key, expr in iteritems(expressions):
2391 2390 try:
2392 2391 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2393 2392 except:
2394 2393 value = self._user_obj_error()
2395 2394 out[key] = value
2396 2395 return out
2397 2396
2398 2397 #-------------------------------------------------------------------------
2399 2398 # Things related to the running of code
2400 2399 #-------------------------------------------------------------------------
2401 2400
2402 2401 def ex(self, cmd):
2403 2402 """Execute a normal python statement in user namespace."""
2404 2403 with self.builtin_trap:
2405 2404 exec(cmd, self.user_global_ns, self.user_ns)
2406 2405
2407 2406 def ev(self, expr):
2408 2407 """Evaluate python expression expr in user namespace.
2409 2408
2410 2409 Returns the result of evaluation
2411 2410 """
2412 2411 with self.builtin_trap:
2413 2412 return eval(expr, self.user_global_ns, self.user_ns)
2414 2413
2415 2414 def safe_execfile(self, fname, *where, **kw):
2416 2415 """A safe version of the builtin execfile().
2417 2416
2418 2417 This version will never throw an exception, but instead print
2419 2418 helpful error messages to the screen. This only works on pure
2420 2419 Python files with the .py extension.
2421 2420
2422 2421 Parameters
2423 2422 ----------
2424 2423 fname : string
2425 2424 The name of the file to be executed.
2426 2425 where : tuple
2427 2426 One or two namespaces, passed to execfile() as (globals,locals).
2428 2427 If only one is given, it is passed as both.
2429 2428 exit_ignore : bool (False)
2430 2429 If True, then silence SystemExit for non-zero status (it is always
2431 2430 silenced for zero status, as it is so common).
2432 2431 raise_exceptions : bool (False)
2433 2432 If True raise exceptions everywhere. Meant for testing.
2434 2433 shell_futures : bool (False)
2435 2434 If True, the code will share future statements with the interactive
2436 2435 shell. It will both be affected by previous __future__ imports, and
2437 2436 any __future__ imports in the code will affect the shell. If False,
2438 2437 __future__ imports are not shared in either direction.
2439 2438
2440 2439 """
2441 2440 kw.setdefault('exit_ignore', False)
2442 2441 kw.setdefault('raise_exceptions', False)
2443 2442 kw.setdefault('shell_futures', False)
2444 2443
2445 2444 fname = os.path.abspath(os.path.expanduser(fname))
2446 2445
2447 2446 # Make sure we can open the file
2448 2447 try:
2449 2448 with open(fname):
2450 2449 pass
2451 2450 except:
2452 2451 warn('Could not open file <%s> for safe execution.' % fname)
2453 2452 return
2454 2453
2455 2454 # Find things also in current directory. This is needed to mimic the
2456 2455 # behavior of running a script from the system command line, where
2457 2456 # Python inserts the script's directory into sys.path
2458 2457 dname = os.path.dirname(fname)
2459 2458
2460 2459 with prepended_to_syspath(dname), self.builtin_trap:
2461 2460 try:
2462 2461 glob, loc = (where + (None, ))[:2]
2463 2462 py3compat.execfile(
2464 2463 fname, glob, loc,
2465 2464 self.compile if kw['shell_futures'] else None)
2466 2465 except SystemExit as status:
2467 2466 # If the call was made with 0 or None exit status (sys.exit(0)
2468 2467 # or sys.exit() ), don't bother showing a traceback, as both of
2469 2468 # these are considered normal by the OS:
2470 2469 # > python -c'import sys;sys.exit(0)'; echo $?
2471 2470 # 0
2472 2471 # > python -c'import sys;sys.exit()'; echo $?
2473 2472 # 0
2474 2473 # For other exit status, we show the exception unless
2475 2474 # explicitly silenced, but only in short form.
2476 2475 if status.code:
2477 2476 if kw['raise_exceptions']:
2478 2477 raise
2479 2478 if not kw['exit_ignore']:
2480 2479 self.showtraceback(exception_only=True)
2481 2480 except:
2482 2481 if kw['raise_exceptions']:
2483 2482 raise
2484 2483 # tb offset is 2 because we wrap execfile
2485 2484 self.showtraceback(tb_offset=2)
2486 2485
2487 2486 def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False):
2488 2487 """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.
2489 2488
2490 2489 Parameters
2491 2490 ----------
2492 2491 fname : str
2493 2492 The name of the file to execute. The filename must have a
2494 2493 .ipy or .ipynb extension.
2495 2494 shell_futures : bool (False)
2496 2495 If True, the code will share future statements with the interactive
2497 2496 shell. It will both be affected by previous __future__ imports, and
2498 2497 any __future__ imports in the code will affect the shell. If False,
2499 2498 __future__ imports are not shared in either direction.
2500 2499 raise_exceptions : bool (False)
2501 2500 If True raise exceptions everywhere. Meant for testing.
2502 2501 """
2503 2502 fname = os.path.abspath(os.path.expanduser(fname))
2504 2503
2505 2504 # Make sure we can open the file
2506 2505 try:
2507 2506 with open(fname):
2508 2507 pass
2509 2508 except:
2510 2509 warn('Could not open file <%s> for safe execution.' % fname)
2511 2510 return
2512 2511
2513 2512 # Find things also in current directory. This is needed to mimic the
2514 2513 # behavior of running a script from the system command line, where
2515 2514 # Python inserts the script's directory into sys.path
2516 2515 dname = os.path.dirname(fname)
2517 2516
2518 2517 def get_cells():
2519 2518 """generator for sequence of code blocks to run"""
2520 2519 if fname.endswith('.ipynb'):
2521 2520 from nbformat import read
2522 2521 with io_open(fname) as f:
2523 2522 nb = read(f, as_version=4)
2524 2523 if not nb.cells:
2525 2524 return
2526 2525 for cell in nb.cells:
2527 2526 if cell.cell_type == 'code':
2528 2527 yield cell.source
2529 2528 else:
2530 2529 with open(fname) as f:
2531 2530 yield f.read()
2532 2531
2533 2532 with prepended_to_syspath(dname):
2534 2533 try:
2535 2534 for cell in get_cells():
2536 2535 result = self.run_cell(cell, silent=True, shell_futures=shell_futures)
2537 2536 if raise_exceptions:
2538 2537 result.raise_error()
2539 2538 elif not result.success:
2540 2539 break
2541 2540 except:
2542 2541 if raise_exceptions:
2543 2542 raise
2544 2543 self.showtraceback()
2545 2544 warn('Unknown failure executing file: <%s>' % fname)
2546 2545
2547 2546 def safe_run_module(self, mod_name, where):
2548 2547 """A safe version of runpy.run_module().
2549 2548
2550 2549 This version will never throw an exception, but instead print
2551 2550 helpful error messages to the screen.
2552 2551
2553 2552 `SystemExit` exceptions with status code 0 or None are ignored.
2554 2553
2555 2554 Parameters
2556 2555 ----------
2557 2556 mod_name : string
2558 2557 The name of the module to be executed.
2559 2558 where : dict
2560 2559 The globals namespace.
2561 2560 """
2562 2561 try:
2563 2562 try:
2564 2563 where.update(
2565 2564 runpy.run_module(str(mod_name), run_name="__main__",
2566 2565 alter_sys=True)
2567 2566 )
2568 2567 except SystemExit as status:
2569 2568 if status.code:
2570 2569 raise
2571 2570 except:
2572 2571 self.showtraceback()
2573 2572 warn('Unknown failure executing module: <%s>' % mod_name)
2574 2573
2575 2574 def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
2576 2575 """Run a complete IPython cell.
2577 2576
2578 2577 Parameters
2579 2578 ----------
2580 2579 raw_cell : str
2581 2580 The code (including IPython code such as %magic functions) to run.
2582 2581 store_history : bool
2583 2582 If True, the raw and translated cell will be stored in IPython's
2584 2583 history. For user code calling back into IPython's machinery, this
2585 2584 should be set to False.
2586 2585 silent : bool
2587 2586 If True, avoid side-effects, such as implicit displayhooks and
2588 2587 and logging. silent=True forces store_history=False.
2589 2588 shell_futures : bool
2590 2589 If True, the code will share future statements with the interactive
2591 2590 shell. It will both be affected by previous __future__ imports, and
2592 2591 any __future__ imports in the code will affect the shell. If False,
2593 2592 __future__ imports are not shared in either direction.
2594 2593
2595 2594 Returns
2596 2595 -------
2597 2596 result : :class:`ExecutionResult`
2598 2597 """
2599 2598 result = ExecutionResult()
2600 2599
2601 2600 if (not raw_cell) or raw_cell.isspace():
2602 2601 self.last_execution_succeeded = True
2603 2602 return result
2604 2603
2605 2604 if silent:
2606 2605 store_history = False
2607 2606
2608 2607 if store_history:
2609 2608 result.execution_count = self.execution_count
2610 2609
2611 2610 def error_before_exec(value):
2612 2611 result.error_before_exec = value
2613 2612 self.last_execution_succeeded = False
2614 2613 return result
2615 2614
2616 2615 self.events.trigger('pre_execute')
2617 2616 if not silent:
2618 2617 self.events.trigger('pre_run_cell')
2619 2618
2620 2619 # If any of our input transformation (input_transformer_manager or
2621 2620 # prefilter_manager) raises an exception, we store it in this variable
2622 2621 # so that we can display the error after logging the input and storing
2623 2622 # it in the history.
2624 2623 preprocessing_exc_tuple = None
2625 2624 try:
2626 2625 # Static input transformations
2627 2626 cell = self.input_transformer_manager.transform_cell(raw_cell)
2628 2627 except SyntaxError:
2629 2628 preprocessing_exc_tuple = sys.exc_info()
2630 2629 cell = raw_cell # cell has to exist so it can be stored/logged
2631 2630 else:
2632 2631 if len(cell.splitlines()) == 1:
2633 2632 # Dynamic transformations - only applied for single line commands
2634 2633 with self.builtin_trap:
2635 2634 try:
2636 2635 # use prefilter_lines to handle trailing newlines
2637 2636 # restore trailing newline for ast.parse
2638 2637 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2639 2638 except Exception:
2640 2639 # don't allow prefilter errors to crash IPython
2641 2640 preprocessing_exc_tuple = sys.exc_info()
2642 2641
2643 2642 # Store raw and processed history
2644 2643 if store_history:
2645 2644 self.history_manager.store_inputs(self.execution_count,
2646 2645 cell, raw_cell)
2647 2646 if not silent:
2648 2647 self.logger.log(cell, raw_cell)
2649 2648
2650 2649 # Display the exception if input processing failed.
2651 2650 if preprocessing_exc_tuple is not None:
2652 2651 self.showtraceback(preprocessing_exc_tuple)
2653 2652 if store_history:
2654 2653 self.execution_count += 1
2655 2654 return error_before_exec(preprocessing_exc_tuple[2])
2656 2655
2657 2656 # Our own compiler remembers the __future__ environment. If we want to
2658 2657 # run code with a separate __future__ environment, use the default
2659 2658 # compiler
2660 2659 compiler = self.compile if shell_futures else CachingCompiler()
2661 2660
2662 2661 with self.builtin_trap:
2663 2662 cell_name = self.compile.cache(cell, self.execution_count)
2664 2663
2665 2664 with self.display_trap:
2666 2665 # Compile to bytecode
2667 2666 try:
2668 2667 code_ast = compiler.ast_parse(cell, filename=cell_name)
2669 2668 except self.custom_exceptions as e:
2670 2669 etype, value, tb = sys.exc_info()
2671 2670 self.CustomTB(etype, value, tb)
2672 2671 return error_before_exec(e)
2673 2672 except IndentationError as e:
2674 2673 self.showindentationerror()
2675 2674 if store_history:
2676 2675 self.execution_count += 1
2677 2676 return error_before_exec(e)
2678 2677 except (OverflowError, SyntaxError, ValueError, TypeError,
2679 2678 MemoryError) as e:
2680 2679 self.showsyntaxerror()
2681 2680 if store_history:
2682 2681 self.execution_count += 1
2683 2682 return error_before_exec(e)
2684 2683
2685 2684 # Apply AST transformations
2686 2685 try:
2687 2686 code_ast = self.transform_ast(code_ast)
2688 2687 except InputRejected as e:
2689 2688 self.showtraceback()
2690 2689 if store_history:
2691 2690 self.execution_count += 1
2692 2691 return error_before_exec(e)
2693 2692
2694 2693 # Give the displayhook a reference to our ExecutionResult so it
2695 2694 # can fill in the output value.
2696 2695 self.displayhook.exec_result = result
2697 2696
2698 2697 # Execute the user code
2699 2698 interactivity = "none" if silent else self.ast_node_interactivity
2700 2699 has_raised = self.run_ast_nodes(code_ast.body, cell_name,
2701 2700 interactivity=interactivity, compiler=compiler, result=result)
2702 2701
2703 2702 self.last_execution_succeeded = not has_raised
2704 2703
2705 2704 # Reset this so later displayed values do not modify the
2706 2705 # ExecutionResult
2707 2706 self.displayhook.exec_result = None
2708 2707
2709 2708 self.events.trigger('post_execute')
2710 2709 if not silent:
2711 2710 self.events.trigger('post_run_cell')
2712 2711
2713 2712 if store_history:
2714 2713 # Write output to the database. Does nothing unless
2715 2714 # history output logging is enabled.
2716 2715 self.history_manager.store_output(self.execution_count)
2717 2716 # Each cell is a *single* input, regardless of how many lines it has
2718 2717 self.execution_count += 1
2719 2718
2720 2719 return result
2721 2720
2722 2721 def transform_ast(self, node):
2723 2722 """Apply the AST transformations from self.ast_transformers
2724 2723
2725 2724 Parameters
2726 2725 ----------
2727 2726 node : ast.Node
2728 2727 The root node to be transformed. Typically called with the ast.Module
2729 2728 produced by parsing user input.
2730 2729
2731 2730 Returns
2732 2731 -------
2733 2732 An ast.Node corresponding to the node it was called with. Note that it
2734 2733 may also modify the passed object, so don't rely on references to the
2735 2734 original AST.
2736 2735 """
2737 2736 for transformer in self.ast_transformers:
2738 2737 try:
2739 2738 node = transformer.visit(node)
2740 2739 except InputRejected:
2741 2740 # User-supplied AST transformers can reject an input by raising
2742 2741 # an InputRejected. Short-circuit in this case so that we
2743 2742 # don't unregister the transform.
2744 2743 raise
2745 2744 except Exception:
2746 2745 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
2747 2746 self.ast_transformers.remove(transformer)
2748 2747
2749 2748 if self.ast_transformers:
2750 2749 ast.fix_missing_locations(node)
2751 2750 return node
2752 2751
2753 2752
2754 2753 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr',
2755 2754 compiler=compile, result=None):
2756 2755 """Run a sequence of AST nodes. The execution mode depends on the
2757 2756 interactivity parameter.
2758 2757
2759 2758 Parameters
2760 2759 ----------
2761 2760 nodelist : list
2762 2761 A sequence of AST nodes to run.
2763 2762 cell_name : str
2764 2763 Will be passed to the compiler as the filename of the cell. Typically
2765 2764 the value returned by ip.compile.cache(cell).
2766 2765 interactivity : str
2767 2766 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2768 2767 run interactively (displaying output from expressions). 'last_expr'
2769 2768 will run the last node interactively only if it is an expression (i.e.
2770 2769 expressions in loops or other blocks are not displayed. Other values
2771 2770 for this parameter will raise a ValueError.
2772 2771 compiler : callable
2773 2772 A function with the same interface as the built-in compile(), to turn
2774 2773 the AST nodes into code objects. Default is the built-in compile().
2775 2774 result : ExecutionResult, optional
2776 2775 An object to store exceptions that occur during execution.
2777 2776
2778 2777 Returns
2779 2778 -------
2780 2779 True if an exception occurred while running code, False if it finished
2781 2780 running.
2782 2781 """
2783 2782 if not nodelist:
2784 2783 return
2785 2784
2786 2785 if interactivity == 'last_expr':
2787 2786 if isinstance(nodelist[-1], ast.Expr):
2788 2787 interactivity = "last"
2789 2788 else:
2790 2789 interactivity = "none"
2791 2790
2792 2791 if interactivity == 'none':
2793 2792 to_run_exec, to_run_interactive = nodelist, []
2794 2793 elif interactivity == 'last':
2795 2794 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2796 2795 elif interactivity == 'all':
2797 2796 to_run_exec, to_run_interactive = [], nodelist
2798 2797 else:
2799 2798 raise ValueError("Interactivity was %r" % interactivity)
2800 2799
2801 2800 try:
2802 2801 for i, node in enumerate(to_run_exec):
2803 2802 mod = ast.Module([node])
2804 2803 code = compiler(mod, cell_name, "exec")
2805 2804 if self.run_code(code, result):
2806 2805 return True
2807 2806
2808 2807 for i, node in enumerate(to_run_interactive):
2809 2808 mod = ast.Interactive([node])
2810 2809 code = compiler(mod, cell_name, "single")
2811 2810 if self.run_code(code, result):
2812 2811 return True
2813 2812
2814 2813 # Flush softspace
2815 2814 if softspace(sys.stdout, 0):
2816 2815 print()
2817 2816
2818 2817 except:
2819 2818 # It's possible to have exceptions raised here, typically by
2820 2819 # compilation of odd code (such as a naked 'return' outside a
2821 2820 # function) that did parse but isn't valid. Typically the exception
2822 2821 # is a SyntaxError, but it's safest just to catch anything and show
2823 2822 # the user a traceback.
2824 2823
2825 2824 # We do only one try/except outside the loop to minimize the impact
2826 2825 # on runtime, and also because if any node in the node list is
2827 2826 # broken, we should stop execution completely.
2828 2827 if result:
2829 2828 result.error_before_exec = sys.exc_info()[1]
2830 2829 self.showtraceback()
2831 2830 return True
2832 2831
2833 2832 return False
2834 2833
2835 2834 def run_code(self, code_obj, result=None):
2836 2835 """Execute a code object.
2837 2836
2838 2837 When an exception occurs, self.showtraceback() is called to display a
2839 2838 traceback.
2840 2839
2841 2840 Parameters
2842 2841 ----------
2843 2842 code_obj : code object
2844 2843 A compiled code object, to be executed
2845 2844 result : ExecutionResult, optional
2846 2845 An object to store exceptions that occur during execution.
2847 2846
2848 2847 Returns
2849 2848 -------
2850 2849 False : successful execution.
2851 2850 True : an error occurred.
2852 2851 """
2853 2852 # Set our own excepthook in case the user code tries to call it
2854 2853 # directly, so that the IPython crash handler doesn't get triggered
2855 2854 old_excepthook, sys.excepthook = sys.excepthook, self.excepthook
2856 2855
2857 2856 # we save the original sys.excepthook in the instance, in case config
2858 2857 # code (such as magics) needs access to it.
2859 2858 self.sys_excepthook = old_excepthook
2860 2859 outflag = 1 # happens in more places, so it's easier as default
2861 2860 try:
2862 2861 try:
2863 2862 self.hooks.pre_run_code_hook()
2864 2863 #rprint('Running code', repr(code_obj)) # dbg
2865 2864 exec(code_obj, self.user_global_ns, self.user_ns)
2866 2865 finally:
2867 2866 # Reset our crash handler in place
2868 2867 sys.excepthook = old_excepthook
2869 2868 except SystemExit as e:
2870 2869 if result is not None:
2871 2870 result.error_in_exec = e
2872 2871 self.showtraceback(exception_only=True)
2873 2872 warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
2874 2873 except self.custom_exceptions:
2875 2874 etype, value, tb = sys.exc_info()
2876 2875 if result is not None:
2877 2876 result.error_in_exec = value
2878 2877 self.CustomTB(etype, value, tb)
2879 2878 except:
2880 2879 if result is not None:
2881 2880 result.error_in_exec = sys.exc_info()[1]
2882 2881 self.showtraceback()
2883 2882 else:
2884 2883 outflag = 0
2885 2884 return outflag
2886 2885
2887 2886 # For backwards compatibility
2888 2887 runcode = run_code
2889 2888
2890 2889 #-------------------------------------------------------------------------
2891 2890 # Things related to GUI support and pylab
2892 2891 #-------------------------------------------------------------------------
2893 2892
2894 2893 def enable_gui(self, gui=None):
2895 2894 raise NotImplementedError('Implement enable_gui in a subclass')
2896 2895
2897 2896 def enable_matplotlib(self, gui=None):
2898 2897 """Enable interactive matplotlib and inline figure support.
2899 2898
2900 2899 This takes the following steps:
2901 2900
2902 2901 1. select the appropriate eventloop and matplotlib backend
2903 2902 2. set up matplotlib for interactive use with that backend
2904 2903 3. configure formatters for inline figure display
2905 2904 4. enable the selected gui eventloop
2906 2905
2907 2906 Parameters
2908 2907 ----------
2909 2908 gui : optional, string
2910 2909 If given, dictates the choice of matplotlib GUI backend to use
2911 2910 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2912 2911 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2913 2912 matplotlib (as dictated by the matplotlib build-time options plus the
2914 2913 user's matplotlibrc configuration file). Note that not all backends
2915 2914 make sense in all contexts, for example a terminal ipython can't
2916 2915 display figures inline.
2917 2916 """
2918 2917 from IPython.core import pylabtools as pt
2919 2918 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
2920 2919
2921 2920 if gui != 'inline':
2922 2921 # If we have our first gui selection, store it
2923 2922 if self.pylab_gui_select is None:
2924 2923 self.pylab_gui_select = gui
2925 2924 # Otherwise if they are different
2926 2925 elif gui != self.pylab_gui_select:
2927 2926 print ('Warning: Cannot change to a different GUI toolkit: %s.'
2928 2927 ' Using %s instead.' % (gui, self.pylab_gui_select))
2929 2928 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
2930 2929
2931 2930 pt.activate_matplotlib(backend)
2932 2931 pt.configure_inline_support(self, backend)
2933 2932
2934 2933 # Now we must activate the gui pylab wants to use, and fix %run to take
2935 2934 # plot updates into account
2936 2935 self.enable_gui(gui)
2937 2936 self.magics_manager.registry['ExecutionMagics'].default_runner = \
2938 2937 pt.mpl_runner(self.safe_execfile)
2939 2938
2940 2939 return gui, backend
2941 2940
2942 2941 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
2943 2942 """Activate pylab support at runtime.
2944 2943
2945 2944 This turns on support for matplotlib, preloads into the interactive
2946 2945 namespace all of numpy and pylab, and configures IPython to correctly
2947 2946 interact with the GUI event loop. The GUI backend to be used can be
2948 2947 optionally selected with the optional ``gui`` argument.
2949 2948
2950 2949 This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
2951 2950
2952 2951 Parameters
2953 2952 ----------
2954 2953 gui : optional, string
2955 2954 If given, dictates the choice of matplotlib GUI backend to use
2956 2955 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2957 2956 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2958 2957 matplotlib (as dictated by the matplotlib build-time options plus the
2959 2958 user's matplotlibrc configuration file). Note that not all backends
2960 2959 make sense in all contexts, for example a terminal ipython can't
2961 2960 display figures inline.
2962 2961 import_all : optional, bool, default: True
2963 2962 Whether to do `from numpy import *` and `from pylab import *`
2964 2963 in addition to module imports.
2965 2964 welcome_message : deprecated
2966 2965 This argument is ignored, no welcome message will be displayed.
2967 2966 """
2968 2967 from IPython.core.pylabtools import import_pylab
2969 2968
2970 2969 gui, backend = self.enable_matplotlib(gui)
2971 2970
2972 2971 # We want to prevent the loading of pylab to pollute the user's
2973 2972 # namespace as shown by the %who* magics, so we execute the activation
2974 2973 # code in an empty namespace, and we update *both* user_ns and
2975 2974 # user_ns_hidden with this information.
2976 2975 ns = {}
2977 2976 import_pylab(ns, import_all)
2978 2977 # warn about clobbered names
2979 2978 ignored = {"__builtins__"}
2980 2979 both = set(ns).intersection(self.user_ns).difference(ignored)
2981 2980 clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
2982 2981 self.user_ns.update(ns)
2983 2982 self.user_ns_hidden.update(ns)
2984 2983 return gui, backend, clobbered
2985 2984
2986 2985 #-------------------------------------------------------------------------
2987 2986 # Utilities
2988 2987 #-------------------------------------------------------------------------
2989 2988
2990 2989 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
2991 2990 """Expand python variables in a string.
2992 2991
2993 2992 The depth argument indicates how many frames above the caller should
2994 2993 be walked to look for the local namespace where to expand variables.
2995 2994
2996 2995 The global namespace for expansion is always the user's interactive
2997 2996 namespace.
2998 2997 """
2999 2998 ns = self.user_ns.copy()
3000 2999 try:
3001 3000 frame = sys._getframe(depth+1)
3002 3001 except ValueError:
3003 3002 # This is thrown if there aren't that many frames on the stack,
3004 3003 # e.g. if a script called run_line_magic() directly.
3005 3004 pass
3006 3005 else:
3007 3006 ns.update(frame.f_locals)
3008 3007
3009 3008 try:
3010 3009 # We have to use .vformat() here, because 'self' is a valid and common
3011 3010 # name, and expanding **ns for .format() would make it collide with
3012 3011 # the 'self' argument of the method.
3013 3012 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
3014 3013 except Exception:
3015 3014 # if formatter couldn't format, just let it go untransformed
3016 3015 pass
3017 3016 return cmd
3018 3017
3019 3018 def mktempfile(self, data=None, prefix='ipython_edit_'):
3020 3019 """Make a new tempfile and return its filename.
3021 3020
3022 3021 This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp),
3023 3022 but it registers the created filename internally so ipython cleans it up
3024 3023 at exit time.
3025 3024
3026 3025 Optional inputs:
3027 3026
3028 3027 - data(None): if data is given, it gets written out to the temp file
3029 3028 immediately, and the file is closed again."""
3030 3029
3031 3030 dirname = tempfile.mkdtemp(prefix=prefix)
3032 3031 self.tempdirs.append(dirname)
3033 3032
3034 3033 handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname)
3035 3034 os.close(handle) # On Windows, there can only be one open handle on a file
3036 3035 self.tempfiles.append(filename)
3037 3036
3038 3037 if data:
3039 3038 tmp_file = open(filename,'w')
3040 3039 tmp_file.write(data)
3041 3040 tmp_file.close()
3042 3041 return filename
3043 3042
3044 3043 @undoc
3045 3044 def write(self,data):
3046 3045 """DEPRECATED: Write a string to the default output"""
3047 3046 warn('InteractiveShell.write() is deprecated, use sys.stdout instead',
3048 3047 DeprecationWarning, stacklevel=2)
3049 3048 sys.stdout.write(data)
3050 3049
3051 3050 @undoc
3052 3051 def write_err(self,data):
3053 3052 """DEPRECATED: Write a string to the default error output"""
3054 3053 warn('InteractiveShell.write_err() is deprecated, use sys.stderr instead',
3055 3054 DeprecationWarning, stacklevel=2)
3056 3055 sys.stderr.write(data)
3057 3056
3058 3057 def ask_yes_no(self, prompt, default=None, interrupt=None):
3059 3058 if self.quiet:
3060 3059 return True
3061 3060 return ask_yes_no(prompt,default,interrupt)
3062 3061
3063 3062 def show_usage(self):
3064 3063 """Show a usage message"""
3065 3064 page.page(IPython.core.usage.interactive_usage)
3066 3065
3067 3066 def extract_input_lines(self, range_str, raw=False):
3068 3067 """Return as a string a set of input history slices.
3069 3068
3070 3069 Parameters
3071 3070 ----------
3072 3071 range_str : string
3073 3072 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
3074 3073 since this function is for use by magic functions which get their
3075 3074 arguments as strings. The number before the / is the session
3076 3075 number: ~n goes n back from the current session.
3077 3076
3078 3077 raw : bool, optional
3079 3078 By default, the processed input is used. If this is true, the raw
3080 3079 input history is used instead.
3081 3080
3082 3081 Notes
3083 3082 -----
3084 3083
3085 3084 Slices can be described with two notations:
3086 3085
3087 3086 * ``N:M`` -> standard python form, means including items N...(M-1).
3088 3087 * ``N-M`` -> include items N..M (closed endpoint).
3089 3088 """
3090 3089 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
3091 3090 return "\n".join(x for _, _, x in lines)
3092 3091
3093 3092 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False):
3094 3093 """Get a code string from history, file, url, or a string or macro.
3095 3094
3096 3095 This is mainly used by magic functions.
3097 3096
3098 3097 Parameters
3099 3098 ----------
3100 3099
3101 3100 target : str
3102 3101
3103 3102 A string specifying code to retrieve. This will be tried respectively
3104 3103 as: ranges of input history (see %history for syntax), url,
3105 3104 corresponding .py file, filename, or an expression evaluating to a
3106 3105 string or Macro in the user namespace.
3107 3106
3108 3107 raw : bool
3109 3108 If true (default), retrieve raw history. Has no effect on the other
3110 3109 retrieval mechanisms.
3111 3110
3112 3111 py_only : bool (default False)
3113 3112 Only try to fetch python code, do not try alternative methods to decode file
3114 3113 if unicode fails.
3115 3114
3116 3115 Returns
3117 3116 -------
3118 3117 A string of code.
3119 3118
3120 3119 ValueError is raised if nothing is found, and TypeError if it evaluates
3121 3120 to an object of another type. In each case, .args[0] is a printable
3122 3121 message.
3123 3122 """
3124 3123 code = self.extract_input_lines(target, raw=raw) # Grab history
3125 3124 if code:
3126 3125 return code
3127 3126 try:
3128 3127 if target.startswith(('http://', 'https://')):
3129 3128 return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie)
3130 3129 except UnicodeDecodeError:
3131 3130 if not py_only :
3132 3131 # Deferred import
3133 3132 try:
3134 3133 from urllib.request import urlopen # Py3
3135 3134 except ImportError:
3136 3135 from urllib import urlopen
3137 3136 response = urlopen(target)
3138 3137 return response.read().decode('latin1')
3139 3138 raise ValueError(("'%s' seem to be unreadable.") % target)
3140 3139
3141 3140 potential_target = [target]
3142 3141 try :
3143 3142 potential_target.insert(0,get_py_filename(target))
3144 3143 except IOError:
3145 3144 pass
3146 3145
3147 3146 for tgt in potential_target :
3148 3147 if os.path.isfile(tgt): # Read file
3149 3148 try :
3150 3149 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
3151 3150 except UnicodeDecodeError :
3152 3151 if not py_only :
3153 3152 with io_open(tgt,'r', encoding='latin1') as f :
3154 3153 return f.read()
3155 3154 raise ValueError(("'%s' seem to be unreadable.") % target)
3156 3155 elif os.path.isdir(os.path.expanduser(tgt)):
3157 3156 raise ValueError("'%s' is a directory, not a regular file." % target)
3158 3157
3159 3158 if search_ns:
3160 3159 # Inspect namespace to load object source
3161 3160 object_info = self.object_inspect(target, detail_level=1)
3162 3161 if object_info['found'] and object_info['source']:
3163 3162 return object_info['source']
3164 3163
3165 3164 try: # User namespace
3166 3165 codeobj = eval(target, self.user_ns)
3167 3166 except Exception:
3168 3167 raise ValueError(("'%s' was not found in history, as a file, url, "
3169 3168 "nor in the user namespace.") % target)
3170 3169
3171 3170 if isinstance(codeobj, string_types):
3172 3171 return codeobj
3173 3172 elif isinstance(codeobj, Macro):
3174 3173 return codeobj.value
3175 3174
3176 3175 raise TypeError("%s is neither a string nor a macro." % target,
3177 3176 codeobj)
3178 3177
3179 3178 #-------------------------------------------------------------------------
3180 3179 # Things related to IPython exiting
3181 3180 #-------------------------------------------------------------------------
3182 3181 def atexit_operations(self):
3183 3182 """This will be executed at the time of exit.
3184 3183
3185 3184 Cleanup operations and saving of persistent data that is done
3186 3185 unconditionally by IPython should be performed here.
3187 3186
3188 3187 For things that may depend on startup flags or platform specifics (such
3189 3188 as having readline or not), register a separate atexit function in the
3190 3189 code that has the appropriate information, rather than trying to
3191 3190 clutter
3192 3191 """
3193 3192 # Close the history session (this stores the end time and line count)
3194 3193 # this must be *before* the tempfile cleanup, in case of temporary
3195 3194 # history db
3196 3195 self.history_manager.end_session()
3197 3196
3198 3197 # Cleanup all tempfiles and folders left around
3199 3198 for tfile in self.tempfiles:
3200 3199 try:
3201 3200 os.unlink(tfile)
3202 3201 except OSError:
3203 3202 pass
3204 3203
3205 3204 for tdir in self.tempdirs:
3206 3205 try:
3207 3206 os.rmdir(tdir)
3208 3207 except OSError:
3209 3208 pass
3210 3209
3211 3210 # Clear all user namespaces to release all references cleanly.
3212 3211 self.reset(new_session=False)
3213 3212
3214 3213 # Run user hooks
3215 3214 self.hooks.shutdown_hook()
3216 3215
3217 3216 def cleanup(self):
3218 3217 self.restore_sys_module_state()
3219 3218
3220 3219
3221 3220 # Overridden in terminal subclass to change prompts
3222 3221 def switch_doctest_mode(self, mode):
3223 3222 pass
3224 3223
3225 3224
3226 3225 class InteractiveShellABC(with_metaclass(abc.ABCMeta, object)):
3227 3226 """An abstract base class for InteractiveShell."""
3228 3227
3229 3228 InteractiveShellABC.register(InteractiveShell)
@@ -1,96 +1,95 b''
1 1 from IPython.core.debugger import Pdb
2 2
3 3 from IPython.core.completer import IPCompleter
4 4 from .ptutils import IPythonPTCompleter
5 5
6 6 from prompt_toolkit.token import Token
7 7 from prompt_toolkit.shortcuts import create_prompt_application
8 8 from prompt_toolkit.interface import CommandLineInterface
9 9 from prompt_toolkit.enums import EditingMode
10 10 import sys
11 11
12 12
13 13 class TerminalPdb(Pdb):
14 14 def __init__(self, *args, **kwargs):
15 15 Pdb.__init__(self, *args, **kwargs)
16 16 self._ptcomp = None
17 17 self.pt_init()
18 18
19 19 def pt_init(self):
20 20 def get_prompt_tokens(cli):
21 21 return [(Token.Prompt, self.prompt)]
22 22
23 23 if self._ptcomp is None:
24 24 compl = IPCompleter(shell=self.shell,
25 25 namespace={},
26 26 global_namespace={},
27 use_readline=False,
28 27 parent=self.shell,
29 28 )
30 29 self._ptcomp = IPythonPTCompleter(compl)
31 30
32 31 self._pt_app = create_prompt_application(
33 32 editing_mode=getattr(EditingMode, self.shell.editing_mode.upper()),
34 33 history=self.shell.debugger_history,
35 34 completer= self._ptcomp,
36 35 enable_history_search=True,
37 36 mouse_support=self.shell.mouse_support,
38 37 get_prompt_tokens=get_prompt_tokens
39 38 )
40 39 self.pt_cli = CommandLineInterface(self._pt_app, eventloop=self.shell._eventloop)
41 40
42 41 def cmdloop(self, intro=None):
43 42 """Repeatedly issue a prompt, accept input, parse an initial prefix
44 43 off the received input, and dispatch to action methods, passing them
45 44 the remainder of the line as argument.
46 45
47 46 override the same methods from cmd.Cmd to provide prompt toolkit replacement.
48 47 """
49 48 if not self.use_rawinput:
50 49 raise ValueError('Sorry ipdb does not support use_rawinput=False')
51 50
52 51 self.preloop()
53 52
54 53 try:
55 54 if intro is not None:
56 55 self.intro = intro
57 56 if self.intro:
58 57 self.stdout.write(str(self.intro)+"\n")
59 58 stop = None
60 59 while not stop:
61 60 if self.cmdqueue:
62 61 line = self.cmdqueue.pop(0)
63 62 else:
64 63 self._ptcomp.ipy_completer.namespace = self.curframe_locals
65 64 self._ptcomp.ipy_completer.global_namespace = self.curframe.f_globals
66 65 try:
67 66 line = self.pt_cli.run(reset_current_buffer=True).text
68 67 except EOFError:
69 68 line = 'EOF'
70 69 line = self.precmd(line)
71 70 stop = self.onecmd(line)
72 71 stop = self.postcmd(stop, line)
73 72 self.postloop()
74 73 except Exception:
75 74 raise
76 75
77 76
78 77 def set_trace(frame=None):
79 78 """
80 79 Start debugging from `frame`.
81 80
82 81 If frame is not specified, debugging starts from caller's frame.
83 82 """
84 83 TerminalPdb().set_trace(frame or sys._getframe().f_back)
85 84
86 85
87 86 if __name__ == '__main__':
88 87 import pdb
89 88 # IPython.core.debugger.Pdb.trace_dispatch shall not catch
90 89 # bdb.BdbQuit. When started through __main__ and an exception
91 90 # happened after hitting "c", this is needed in order to
92 91 # be able to quit the debugging session (see #9950).
93 92 old_trace_dispatch = pdb.Pdb.trace_dispatch
94 93 pdb.Pdb = TerminalPdb
95 94 pdb.Pdb.trace_dispatch = old_trace_dispatch
96 95 pdb.main()
@@ -1,23 +1,20 b''
1 1 # encoding: utf-8
2 2
3 3 def test_import_coloransi():
4 4 from IPython.utils import coloransi
5 5
6 6 def test_import_generics():
7 7 from IPython.utils import generics
8 8
9 9 def test_import_ipstruct():
10 10 from IPython.utils import ipstruct
11 11
12 12 def test_import_PyColorize():
13 13 from IPython.utils import PyColorize
14 14
15 def test_import_rlineimpl():
16 from IPython.utils import rlineimpl
17
18 15 def test_import_strdispatch():
19 16 from IPython.utils import strdispatch
20 17
21 18 def test_import_wildcard():
22 19 from IPython.utils import wildcard
23 20
1 NO CONTENT: file was removed
General Comments 0
You need to be logged in to leave comments. Login now