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