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