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