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