##// END OF EJS Templates
Start refactoring handling of color....
Matthias Bussonnier -
Show More
@@ -1,636 +1,637 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 Pdb debugger class.
4 4
5 5 Modified from the standard pdb.Pdb class to avoid including readline, so that
6 6 the command line completion of other programs which include this isn't
7 7 damaged.
8 8
9 9 In the future, this class will be expanded with improvements over the standard
10 10 pdb.
11 11
12 12 The code in this file is mainly lifted out of cmd.py in Python 2.2, with minor
13 13 changes. Licensing should therefore be under the standard Python terms. For
14 14 details on the PSF (Python Software Foundation) standard license, see:
15 15
16 16 http://www.python.org/2.2.3/license.html"""
17 17
18 18 #*****************************************************************************
19 19 #
20 20 # This file is licensed under the PSF license.
21 21 #
22 22 # Copyright (C) 2001 Python Software Foundation, www.python.org
23 23 # Copyright (C) 2005-2006 Fernando Perez. <fperez@colorado.edu>
24 24 #
25 25 #
26 26 #*****************************************************************************
27 27 from __future__ import print_function
28 28
29 29 import bdb
30 30 import functools
31 31 import inspect
32 32 import sys
33 33 import warnings
34 34
35 35 from IPython import get_ipython
36 36 from IPython.utils import PyColorize, ulinecache
37 37 from IPython.utils import coloransi, py3compat
38 38 from IPython.core.excolors import exception_colors
39 39 from IPython.testing.skipdoctest import skip_doctest
40 40
41 41
42 42 prompt = 'ipdb> '
43 43
44 44 #We have to check this directly from sys.argv, config struct not yet available
45 45 from pdb import Pdb as OldPdb
46 46
47 47 # Allow the set_trace code to operate outside of an ipython instance, even if
48 48 # it does so with some limitations. The rest of this support is implemented in
49 49 # the Tracer constructor.
50 50
51 51 def make_arrow(pad):
52 52 """generate the leading arrow in front of traceback or debugger"""
53 53 if pad >= 2:
54 54 return '-'*(pad-2) + '> '
55 55 elif pad == 1:
56 56 return '>'
57 57 return ''
58 58
59 59
60 60 def BdbQuit_excepthook(et, ev, tb, excepthook=None):
61 61 """Exception hook which handles `BdbQuit` exceptions.
62 62
63 63 All other exceptions are processed using the `excepthook`
64 64 parameter.
65 65 """
66 66 warnings.warn("`BdbQuit_excepthook` is deprecated since version 5.1",
67 67 DeprecationWarning)
68 68 if et==bdb.BdbQuit:
69 69 print('Exiting Debugger.')
70 70 elif excepthook is not None:
71 71 excepthook(et, ev, tb)
72 72 else:
73 73 # Backwards compatibility. Raise deprecation warning?
74 74 BdbQuit_excepthook.excepthook_ori(et,ev,tb)
75 75
76 76
77 77 def BdbQuit_IPython_excepthook(self,et,ev,tb,tb_offset=None):
78 78 warnings.warn(
79 79 "`BdbQuit_IPython_excepthook` is deprecated since version 5.1",
80 80 DeprecationWarning)
81 81 print('Exiting Debugger.')
82 82
83 83
84 84 class Tracer(object):
85 85 """
86 86 DEPRECATED
87 87
88 88 Class for local debugging, similar to pdb.set_trace.
89 89
90 90 Instances of this class, when called, behave like pdb.set_trace, but
91 91 providing IPython's enhanced capabilities.
92 92
93 93 This is implemented as a class which must be initialized in your own code
94 94 and not as a standalone function because we need to detect at runtime
95 95 whether IPython is already active or not. That detection is done in the
96 96 constructor, ensuring that this code plays nicely with a running IPython,
97 97 while functioning acceptably (though with limitations) if outside of it.
98 98 """
99 99
100 100 @skip_doctest
101 101 def __init__(self, colors=None):
102 102 """
103 103 DEPRECATED
104 104
105 105 Create a local debugger instance.
106 106
107 107 Parameters
108 108 ----------
109 109
110 110 colors : str, optional
111 111 The name of the color scheme to use, it must be one of IPython's
112 112 valid color schemes. If not given, the function will default to
113 113 the current IPython scheme when running inside IPython, and to
114 114 'NoColor' otherwise.
115 115
116 116 Examples
117 117 --------
118 118 ::
119 119
120 120 from IPython.core.debugger import Tracer; debug_here = Tracer()
121 121
122 122 Later in your code::
123 123
124 124 debug_here() # -> will open up the debugger at that point.
125 125
126 126 Once the debugger activates, you can use all of its regular commands to
127 127 step through code, set breakpoints, etc. See the pdb documentation
128 128 from the Python standard library for usage details.
129 129 """
130 130 warnings.warn("`Tracer` is deprecated since version 5.1, directly use "
131 131 "`IPython.core.debugger.Pdb.set_trace()`",
132 132 DeprecationWarning)
133 133
134 134 ip = get_ipython()
135 135 if ip is None:
136 136 # Outside of ipython, we set our own exception hook manually
137 137 sys.excepthook = functools.partial(BdbQuit_excepthook,
138 138 excepthook=sys.excepthook)
139 139 def_colors = 'NoColor'
140 140 else:
141 141 # In ipython, we use its custom exception handler mechanism
142 142 def_colors = ip.colors
143 143 ip.set_custom_exc((bdb.BdbQuit,), BdbQuit_IPython_excepthook)
144 144
145 145 if colors is None:
146 146 colors = def_colors
147 147
148 148 # The stdlib debugger internally uses a modified repr from the `repr`
149 149 # module, that limits the length of printed strings to a hardcoded
150 150 # limit of 30 characters. That much trimming is too aggressive, let's
151 151 # at least raise that limit to 80 chars, which should be enough for
152 152 # most interactive uses.
153 153 try:
154 154 try:
155 155 from reprlib import aRepr # Py 3
156 156 except ImportError:
157 157 from repr import aRepr # Py 2
158 158 aRepr.maxstring = 80
159 159 except:
160 160 # This is only a user-facing convenience, so any error we encounter
161 161 # here can be warned about but can be otherwise ignored. These
162 162 # printouts will tell us about problems if this API changes
163 163 import traceback
164 164 traceback.print_exc()
165 165
166 166 self.debugger = Pdb(colors)
167 167
168 168 def __call__(self):
169 169 """Starts an interactive debugger at the point where called.
170 170
171 171 This is similar to the pdb.set_trace() function from the std lib, but
172 172 using IPython's enhanced debugger."""
173 173
174 174 self.debugger.set_trace(sys._getframe().f_back)
175 175
176 176
177 177 def decorate_fn_with_doc(new_fn, old_fn, additional_text=""):
178 178 """Make new_fn have old_fn's doc string. This is particularly useful
179 179 for the ``do_...`` commands that hook into the help system.
180 180 Adapted from from a comp.lang.python posting
181 181 by Duncan Booth."""
182 182 def wrapper(*args, **kw):
183 183 return new_fn(*args, **kw)
184 184 if old_fn.__doc__:
185 185 wrapper.__doc__ = old_fn.__doc__ + additional_text
186 186 return wrapper
187 187
188 188
189 189 def _file_lines(fname):
190 190 """Return the contents of a named file as a list of lines.
191 191
192 192 This function never raises an IOError exception: if the file can't be
193 193 read, it simply returns an empty list."""
194 194
195 195 try:
196 196 outfile = open(fname)
197 197 except IOError:
198 198 return []
199 199 else:
200 200 out = outfile.readlines()
201 201 outfile.close()
202 202 return out
203 203
204 204
205 205 class Pdb(OldPdb, object):
206 206 """Modified Pdb class, does not load readline.
207 207
208 208 for a standalone version that uses prompt_toolkit, see
209 209 `IPython.terminal.debugger.TerminalPdb` and
210 210 `IPython.terminal.debugger.set_trace()`
211 211 """
212 212
213 213 def __init__(self, color_scheme=None, completekey=None,
214 214 stdin=None, stdout=None, context=5):
215 215
216 216 # Parent constructor:
217 217 try:
218 218 self.context = int(context)
219 219 if self.context <= 0:
220 220 raise ValueError("Context must be a positive integer")
221 221 except (TypeError, ValueError):
222 222 raise ValueError("Context must be a positive integer")
223 223
224 224 OldPdb.__init__(self, completekey, stdin, stdout)
225 225
226 226 # IPython changes...
227 227 self.shell = get_ipython()
228 228
229 229 if self.shell is None:
230 230 save_main = sys.modules['__main__']
231 231 # No IPython instance running, we must create one
232 232 from IPython.terminal.interactiveshell import \
233 233 TerminalInteractiveShell
234 234 self.shell = TerminalInteractiveShell.instance()
235 235 # needed by any code which calls __import__("__main__") after
236 236 # the debugger was entered. See also #9941.
237 237 sys.modules['__main__'] = save_main
238 238
239 239 if color_scheme is not None:
240 240 warnings.warn(
241 241 "The `color_scheme` argument is deprecated since version 5.1",
242 DeprecationWarning)
242 DeprecationWarning, stacklevel=2)
243 243 else:
244 244 color_scheme = self.shell.colors
245 245
246 246 self.aliases = {}
247 247
248 248 # Create color table: we copy the default one from the traceback
249 249 # module and add a few attributes needed for debugging
250 250 self.color_scheme_table = exception_colors()
251 251
252 252 # shorthands
253 253 C = coloransi.TermColors
254 254 cst = self.color_scheme_table
255 255
256 256 cst['NoColor'].colors.prompt = C.NoColor
257 257 cst['NoColor'].colors.breakpoint_enabled = C.NoColor
258 258 cst['NoColor'].colors.breakpoint_disabled = C.NoColor
259 259
260 260 cst['Linux'].colors.prompt = C.Green
261 261 cst['Linux'].colors.breakpoint_enabled = C.LightRed
262 262 cst['Linux'].colors.breakpoint_disabled = C.Red
263 263
264 264 cst['LightBG'].colors.prompt = C.Blue
265 265 cst['LightBG'].colors.breakpoint_enabled = C.LightRed
266 266 cst['LightBG'].colors.breakpoint_disabled = C.Red
267 267
268 268 cst['Neutral'].colors.prompt = C.Blue
269 269 cst['Neutral'].colors.breakpoint_enabled = C.LightRed
270 270 cst['Neutral'].colors.breakpoint_disabled = C.Red
271 271
272 self.set_colors(color_scheme)
273 272
274 273 # Add a python parser so we can syntax highlight source while
275 274 # debugging.
276 self.parser = PyColorize.Parser()
275 self.parser = PyColorize.Parser(style=color_scheme)
276 self.set_colors(color_scheme)
277 277
278 278 # Set the prompt - the default prompt is '(Pdb)'
279 279 self.prompt = prompt
280 280
281 281 def set_colors(self, scheme):
282 282 """Shorthand access to the color table scheme selector method."""
283 283 self.color_scheme_table.set_active_scheme(scheme)
284 self.parser.style = scheme
284 285
285 286 def trace_dispatch(self, frame, event, arg):
286 287 try:
287 288 return super(Pdb, self).trace_dispatch(frame, event, arg)
288 289 except bdb.BdbQuit:
289 290 pass
290 291
291 292 def interaction(self, frame, traceback):
292 293 try:
293 294 OldPdb.interaction(self, frame, traceback)
294 295 except KeyboardInterrupt:
295 296 sys.stdout.write('\n' + self.shell.get_exception_only())
296 297
297 298 def parseline(self, line):
298 299 if line.startswith("!!"):
299 300 # Force standard behavior.
300 301 return super(Pdb, self).parseline(line[2:])
301 302 # "Smart command mode" from pdb++: don't execute commands if a variable
302 303 # with the same name exists.
303 304 cmd, arg, newline = super(Pdb, self).parseline(line)
304 305 # Fix for #9611: Do not trigger smart command if the command is `exit`
305 306 # or `quit` and it would resolve to their *global* value (the
306 307 # `ExitAutocall` object). Just checking that it is not present in the
307 308 # locals dict is not enough as locals and globals match at the
308 309 # toplevel.
309 310 if ((cmd in self.curframe.f_locals or cmd in self.curframe.f_globals)
310 311 and not (cmd in ["exit", "quit"]
311 312 and (self.curframe.f_locals is self.curframe.f_globals
312 313 or cmd not in self.curframe.f_locals))):
313 314 return super(Pdb, self).parseline("!" + line)
314 315 return super(Pdb, self).parseline(line)
315 316
316 317 def new_do_up(self, arg):
317 318 OldPdb.do_up(self, arg)
318 319 do_u = do_up = decorate_fn_with_doc(new_do_up, OldPdb.do_up)
319 320
320 321 def new_do_down(self, arg):
321 322 OldPdb.do_down(self, arg)
322 323
323 324 do_d = do_down = decorate_fn_with_doc(new_do_down, OldPdb.do_down)
324 325
325 326 def new_do_frame(self, arg):
326 327 OldPdb.do_frame(self, arg)
327 328
328 329 def new_do_quit(self, arg):
329 330
330 331 if hasattr(self, 'old_all_completions'):
331 332 self.shell.Completer.all_completions=self.old_all_completions
332 333
333 334 return OldPdb.do_quit(self, arg)
334 335
335 336 do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit)
336 337
337 338 def new_do_restart(self, arg):
338 339 """Restart command. In the context of ipython this is exactly the same
339 340 thing as 'quit'."""
340 341 self.msg("Restart doesn't make sense here. Using 'quit' instead.")
341 342 return self.do_quit(arg)
342 343
343 344 def print_stack_trace(self, context=None):
344 345 if context is None:
345 346 context = self.context
346 347 try:
347 348 context=int(context)
348 349 if context <= 0:
349 350 raise ValueError("Context must be a positive integer")
350 351 except (TypeError, ValueError):
351 352 raise ValueError("Context must be a positive integer")
352 353 try:
353 354 for frame_lineno in self.stack:
354 355 self.print_stack_entry(frame_lineno, context=context)
355 356 except KeyboardInterrupt:
356 357 pass
357 358
358 359 def print_stack_entry(self,frame_lineno, prompt_prefix='\n-> ',
359 360 context=None):
360 361 if context is None:
361 362 context = self.context
362 363 try:
363 364 context=int(context)
364 365 if context <= 0:
365 366 raise ValueError("Context must be a positive integer")
366 367 except (TypeError, ValueError):
367 368 raise ValueError("Context must be a positive integer")
368 369 print(self.format_stack_entry(frame_lineno, '', context))
369 370
370 371 # vds: >>
371 372 frame, lineno = frame_lineno
372 373 filename = frame.f_code.co_filename
373 374 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
374 375 # vds: <<
375 376
376 377 def format_stack_entry(self, frame_lineno, lprefix=': ', context=None):
377 378 if context is None:
378 379 context = self.context
379 380 try:
380 381 context=int(context)
381 382 if context <= 0:
382 383 print("Context must be a positive integer")
383 384 except (TypeError, ValueError):
384 385 print("Context must be a positive integer")
385 386 try:
386 387 import reprlib # Py 3
387 388 except ImportError:
388 389 import repr as reprlib # Py 2
389 390
390 391 ret = []
391 392
392 393 Colors = self.color_scheme_table.active_colors
393 394 ColorsNormal = Colors.Normal
394 395 tpl_link = u'%s%%s%s' % (Colors.filenameEm, ColorsNormal)
395 396 tpl_call = u'%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal)
396 397 tpl_line = u'%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
397 398 tpl_line_em = u'%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line,
398 399 ColorsNormal)
399 400
400 401 frame, lineno = frame_lineno
401 402
402 403 return_value = ''
403 404 if '__return__' in frame.f_locals:
404 405 rv = frame.f_locals['__return__']
405 406 #return_value += '->'
406 407 return_value += reprlib.repr(rv) + '\n'
407 408 ret.append(return_value)
408 409
409 410 #s = filename + '(' + `lineno` + ')'
410 411 filename = self.canonic(frame.f_code.co_filename)
411 412 link = tpl_link % py3compat.cast_unicode(filename)
412 413
413 414 if frame.f_code.co_name:
414 415 func = frame.f_code.co_name
415 416 else:
416 417 func = "<lambda>"
417 418
418 419 call = ''
419 420 if func != '?':
420 421 if '__args__' in frame.f_locals:
421 422 args = reprlib.repr(frame.f_locals['__args__'])
422 423 else:
423 424 args = '()'
424 425 call = tpl_call % (func, args)
425 426
426 427 # The level info should be generated in the same format pdb uses, to
427 428 # avoid breaking the pdbtrack functionality of python-mode in *emacs.
428 429 if frame is self.curframe:
429 430 ret.append('> ')
430 431 else:
431 432 ret.append(' ')
432 433 ret.append(u'%s(%s)%s\n' % (link,lineno,call))
433 434
434 435 start = lineno - 1 - context//2
435 436 lines = ulinecache.getlines(filename)
436 437 start = min(start, len(lines) - context)
437 438 start = max(start, 0)
438 439 lines = lines[start : start + context]
439 440
440 441 for i,line in enumerate(lines):
441 442 show_arrow = (start + 1 + i == lineno)
442 443 linetpl = (frame is self.curframe or show_arrow) \
443 444 and tpl_line_em \
444 445 or tpl_line
445 446 ret.append(self.__format_line(linetpl, filename,
446 447 start + 1 + i, line,
447 448 arrow = show_arrow) )
448 449 return ''.join(ret)
449 450
450 451 def __format_line(self, tpl_line, filename, lineno, line, arrow = False):
451 452 bp_mark = ""
452 453 bp_mark_color = ""
453 454
454 scheme = self.color_scheme_table.active_scheme_name
455 new_line, err = self.parser.format2(line, 'str', scheme)
456 if not err: line = new_line
455 new_line, err = self.parser.format2(line, 'str')
456 if not err:
457 line = new_line
457 458
458 459 bp = None
459 460 if lineno in self.get_file_breaks(filename):
460 461 bps = self.get_breaks(filename, lineno)
461 462 bp = bps[-1]
462 463
463 464 if bp:
464 465 Colors = self.color_scheme_table.active_colors
465 466 bp_mark = str(bp.number)
466 467 bp_mark_color = Colors.breakpoint_enabled
467 468 if not bp.enabled:
468 469 bp_mark_color = Colors.breakpoint_disabled
469 470
470 471 numbers_width = 7
471 472 if arrow:
472 473 # This is the line with the error
473 474 pad = numbers_width - len(str(lineno)) - len(bp_mark)
474 475 num = '%s%s' % (make_arrow(pad), str(lineno))
475 476 else:
476 477 num = '%*s' % (numbers_width - len(bp_mark), str(lineno))
477 478
478 479 return tpl_line % (bp_mark_color + bp_mark, num, line)
479 480
480 481
481 482 def print_list_lines(self, filename, first, last):
482 483 """The printing (as opposed to the parsing part of a 'list'
483 484 command."""
484 485 try:
485 486 Colors = self.color_scheme_table.active_colors
486 487 ColorsNormal = Colors.Normal
487 488 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
488 489 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal)
489 490 src = []
490 491 if filename == "<string>" and hasattr(self, "_exec_filename"):
491 492 filename = self._exec_filename
492 493
493 494 for lineno in range(first, last+1):
494 495 line = ulinecache.getline(filename, lineno)
495 496 if not line:
496 497 break
497 498
498 499 if lineno == self.curframe.f_lineno:
499 500 line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True)
500 501 else:
501 502 line = self.__format_line(tpl_line, filename, lineno, line, arrow = False)
502 503
503 504 src.append(line)
504 505 self.lineno = lineno
505 506
506 507 print(''.join(src))
507 508
508 509 except KeyboardInterrupt:
509 510 pass
510 511
511 512 def do_list(self, arg):
512 513 self.lastcmd = 'list'
513 514 last = None
514 515 if arg:
515 516 try:
516 517 x = eval(arg, {}, {})
517 518 if type(x) == type(()):
518 519 first, last = x
519 520 first = int(first)
520 521 last = int(last)
521 522 if last < first:
522 523 # Assume it's a count
523 524 last = first + last
524 525 else:
525 526 first = max(1, int(x) - 5)
526 527 except:
527 528 print('*** Error in argument:', repr(arg))
528 529 return
529 530 elif self.lineno is None:
530 531 first = max(1, self.curframe.f_lineno - 5)
531 532 else:
532 533 first = self.lineno + 1
533 534 if last is None:
534 535 last = first + 10
535 536 self.print_list_lines(self.curframe.f_code.co_filename, first, last)
536 537
537 538 # vds: >>
538 539 lineno = first
539 540 filename = self.curframe.f_code.co_filename
540 541 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
541 542 # vds: <<
542 543
543 544 do_l = do_list
544 545
545 546 def getsourcelines(self, obj):
546 547 lines, lineno = inspect.findsource(obj)
547 548 if inspect.isframe(obj) and obj.f_globals is obj.f_locals:
548 549 # must be a module frame: do not try to cut a block out of it
549 550 return lines, 1
550 551 elif inspect.ismodule(obj):
551 552 return lines, 1
552 553 return inspect.getblock(lines[lineno:]), lineno+1
553 554
554 555 def do_longlist(self, arg):
555 556 self.lastcmd = 'longlist'
556 557 try:
557 558 lines, lineno = self.getsourcelines(self.curframe)
558 559 except OSError as err:
559 560 self.error(err)
560 561 return
561 562 last = lineno + len(lines)
562 563 self.print_list_lines(self.curframe.f_code.co_filename, lineno, last)
563 564 do_ll = do_longlist
564 565
565 566 def do_pdef(self, arg):
566 567 """Print the call signature for any callable object.
567 568
568 569 The debugger interface to %pdef"""
569 570 namespaces = [('Locals', self.curframe.f_locals),
570 571 ('Globals', self.curframe.f_globals)]
571 572 self.shell.find_line_magic('pdef')(arg, namespaces=namespaces)
572 573
573 574 def do_pdoc(self, arg):
574 575 """Print the docstring for an object.
575 576
576 577 The debugger interface to %pdoc."""
577 578 namespaces = [('Locals', self.curframe.f_locals),
578 579 ('Globals', self.curframe.f_globals)]
579 580 self.shell.find_line_magic('pdoc')(arg, namespaces=namespaces)
580 581
581 582 def do_pfile(self, arg):
582 583 """Print (or run through pager) the file where an object is defined.
583 584
584 585 The debugger interface to %pfile.
585 586 """
586 587 namespaces = [('Locals', self.curframe.f_locals),
587 588 ('Globals', self.curframe.f_globals)]
588 589 self.shell.find_line_magic('pfile')(arg, namespaces=namespaces)
589 590
590 591 def do_pinfo(self, arg):
591 592 """Provide detailed information about an object.
592 593
593 594 The debugger interface to %pinfo, i.e., obj?."""
594 595 namespaces = [('Locals', self.curframe.f_locals),
595 596 ('Globals', self.curframe.f_globals)]
596 597 self.shell.find_line_magic('pinfo')(arg, namespaces=namespaces)
597 598
598 599 def do_pinfo2(self, arg):
599 600 """Provide extra detailed information about an object.
600 601
601 602 The debugger interface to %pinfo2, i.e., obj??."""
602 603 namespaces = [('Locals', self.curframe.f_locals),
603 604 ('Globals', self.curframe.f_globals)]
604 605 self.shell.find_line_magic('pinfo2')(arg, namespaces=namespaces)
605 606
606 607 def do_psource(self, arg):
607 608 """Print (or run through pager) the source code for an object."""
608 609 namespaces = [('Locals', self.curframe.f_locals),
609 610 ('Globals', self.curframe.f_globals)]
610 611 self.shell.find_line_magic('psource')(arg, namespaces=namespaces)
611 612
612 613 if sys.version_info > (3, ):
613 614 def do_where(self, arg):
614 615 """w(here)
615 616 Print a stack trace, with the most recent frame at the bottom.
616 617 An arrow indicates the "current frame", which determines the
617 618 context of most commands. 'bt' is an alias for this command.
618 619
619 620 Take a number as argument as an (optional) number of context line to
620 621 print"""
621 622 if arg:
622 623 context = int(arg)
623 624 self.print_stack_trace(context)
624 625 else:
625 626 self.print_stack_trace()
626 627
627 628 do_w = do_where
628 629
629 630
630 631 def set_trace(frame=None):
631 632 """
632 633 Start debugging from `frame`.
633 634
634 635 If frame is not specified, debugging starts from caller's frame.
635 636 """
636 637 Pdb().set_trace(frame or sys._getframe().f_back)
@@ -1,3230 +1,3229 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Main IPython class."""
3 3
4 4 #-----------------------------------------------------------------------------
5 5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 7 # Copyright (C) 2008-2011 The IPython Development Team
8 8 #
9 9 # Distributed under the terms of the BSD License. The full license is in
10 10 # the file COPYING, distributed as part of this software.
11 11 #-----------------------------------------------------------------------------
12 12
13 13 from __future__ import absolute_import, print_function
14 14
15 15 import __future__
16 16 import abc
17 17 import ast
18 18 import atexit
19 19 import functools
20 20 import os
21 21 import re
22 22 import runpy
23 23 import sys
24 24 import tempfile
25 25 import traceback
26 26 import types
27 27 import subprocess
28 28 import warnings
29 29 from io import open as io_open
30 30
31 31 from pickleshare import PickleShareDB
32 32
33 33 from traitlets.config.configurable import SingletonConfigurable
34 34 from IPython.core import oinspect
35 35 from IPython.core import magic
36 36 from IPython.core import page
37 37 from IPython.core import prefilter
38 38 from IPython.core import shadowns
39 39 from IPython.core import ultratb
40 40 from IPython.core.alias import Alias, AliasManager
41 41 from IPython.core.autocall import ExitAutocall
42 42 from IPython.core.builtin_trap import BuiltinTrap
43 43 from IPython.core.events import EventManager, available_events
44 44 from IPython.core.compilerop import CachingCompiler, check_linecache_ipython
45 45 from IPython.core.debugger import Pdb
46 46 from IPython.core.display_trap import DisplayTrap
47 47 from IPython.core.displayhook import DisplayHook
48 48 from IPython.core.displaypub import DisplayPublisher
49 49 from IPython.core.error import InputRejected, UsageError
50 50 from IPython.core.extensions import ExtensionManager
51 51 from IPython.core.formatters import DisplayFormatter
52 52 from IPython.core.history import HistoryManager
53 53 from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2
54 54 from IPython.core.logger import Logger
55 55 from IPython.core.macro import Macro
56 56 from IPython.core.payload import PayloadManager
57 57 from IPython.core.prefilter import PrefilterManager
58 58 from IPython.core.profiledir import ProfileDir
59 59 from IPython.core.usage import default_banner
60 60 from IPython.testing.skipdoctest import skip_doctest_py2, skip_doctest
61 61 from IPython.utils import PyColorize
62 62 from IPython.utils import io
63 63 from IPython.utils import py3compat
64 64 from IPython.utils import openpy
65 65 from IPython.utils.decorators import undoc
66 66 from IPython.utils.io import ask_yes_no
67 67 from IPython.utils.ipstruct import Struct
68 68 from IPython.paths import get_ipython_dir
69 69 from IPython.utils.path import get_home_dir, get_py_filename, ensure_dir_exists
70 70 from IPython.utils.process import system, getoutput
71 71 from IPython.utils.py3compat import (builtin_mod, unicode_type, string_types,
72 72 with_metaclass, iteritems)
73 73 from IPython.utils.strdispatch import StrDispatch
74 74 from IPython.utils.syspathcontext import prepended_to_syspath
75 75 from IPython.utils.text import format_screen, LSString, SList, DollarFormatter
76 76 from IPython.utils.tempdir import TemporaryDirectory
77 77 from traitlets import (
78 78 Integer, Bool, CaselessStrEnum, Enum, List, Dict, Unicode, Instance, Type,
79 79 observe, default,
80 80 )
81 81 from warnings import warn
82 82 from logging import error
83 83 import IPython.core.hooks
84 84
85 85 # NoOpContext is deprecated, but ipykernel imports it from here.
86 86 # See https://github.com/ipython/ipykernel/issues/157
87 87 from IPython.utils.contexts import NoOpContext
88 88
89 89 try:
90 90 import docrepr.sphinxify as sphx
91 91
92 92 def sphinxify(doc):
93 93 with TemporaryDirectory() as dirname:
94 94 return {
95 95 'text/html': sphx.sphinxify(doc, dirname),
96 96 'text/plain': doc
97 97 }
98 98 except ImportError:
99 99 sphinxify = None
100 100
101 101
102 102 class ProvisionalWarning(DeprecationWarning):
103 103 """
104 104 Warning class for unstable features
105 105 """
106 106 pass
107 107
108 108 #-----------------------------------------------------------------------------
109 109 # Globals
110 110 #-----------------------------------------------------------------------------
111 111
112 112 # compiled regexps for autoindent management
113 113 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
114 114
115 115 #-----------------------------------------------------------------------------
116 116 # Utilities
117 117 #-----------------------------------------------------------------------------
118 118
119 119 @undoc
120 120 def softspace(file, newvalue):
121 121 """Copied from code.py, to remove the dependency"""
122 122
123 123 oldvalue = 0
124 124 try:
125 125 oldvalue = file.softspace
126 126 except AttributeError:
127 127 pass
128 128 try:
129 129 file.softspace = newvalue
130 130 except (AttributeError, TypeError):
131 131 # "attribute-less object" or "read-only attributes"
132 132 pass
133 133 return oldvalue
134 134
135 135 @undoc
136 136 def no_op(*a, **kw): pass
137 137
138 138
139 139 class SpaceInInput(Exception): pass
140 140
141 141
142 142 def get_default_colors():
143 143 "DEPRECATED"
144 144 warn('get_default_color is Deprecated, and is `Neutral` on all platforms.',
145 145 DeprecationWarning, stacklevel=2)
146 146 return 'Neutral'
147 147
148 148
149 149 class SeparateUnicode(Unicode):
150 150 r"""A Unicode subclass to validate separate_in, separate_out, etc.
151 151
152 152 This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``.
153 153 """
154 154
155 155 def validate(self, obj, value):
156 156 if value == '0': value = ''
157 157 value = value.replace('\\n','\n')
158 158 return super(SeparateUnicode, self).validate(obj, value)
159 159
160 160
161 161 @undoc
162 162 class DummyMod(object):
163 163 """A dummy module used for IPython's interactive module when
164 164 a namespace must be assigned to the module's __dict__."""
165 165 pass
166 166
167 167
168 168 class ExecutionResult(object):
169 169 """The result of a call to :meth:`InteractiveShell.run_cell`
170 170
171 171 Stores information about what took place.
172 172 """
173 173 execution_count = None
174 174 error_before_exec = None
175 175 error_in_exec = None
176 176 result = None
177 177
178 178 @property
179 179 def success(self):
180 180 return (self.error_before_exec is None) and (self.error_in_exec is None)
181 181
182 182 def raise_error(self):
183 183 """Reraises error if `success` is `False`, otherwise does nothing"""
184 184 if self.error_before_exec is not None:
185 185 raise self.error_before_exec
186 186 if self.error_in_exec is not None:
187 187 raise self.error_in_exec
188 188
189 189 def __repr__(self):
190 190 if sys.version_info > (3,):
191 191 name = self.__class__.__qualname__
192 192 else:
193 193 name = self.__class__.__name__
194 194 return '<%s object at %x, execution_count=%s error_before_exec=%s error_in_exec=%s result=%s>' %\
195 195 (name, id(self), self.execution_count, self.error_before_exec, self.error_in_exec, repr(self.result))
196 196
197 197
198 198 class InteractiveShell(SingletonConfigurable):
199 199 """An enhanced, interactive shell for Python."""
200 200
201 201 _instance = None
202 202
203 203 ast_transformers = List([], help=
204 204 """
205 205 A list of ast.NodeTransformer subclass instances, which will be applied
206 206 to user input before code is run.
207 207 """
208 208 ).tag(config=True)
209 209
210 210 autocall = Enum((0,1,2), default_value=0, help=
211 211 """
212 212 Make IPython automatically call any callable object even if you didn't
213 213 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
214 214 automatically. The value can be '0' to disable the feature, '1' for
215 215 'smart' autocall, where it is not applied if there are no more
216 216 arguments on the line, and '2' for 'full' autocall, where all callable
217 217 objects are automatically called (even if no arguments are present).
218 218 """
219 219 ).tag(config=True)
220 220 # TODO: remove all autoindent logic and put into frontends.
221 221 # We can't do this yet because even runlines uses the autoindent.
222 222 autoindent = Bool(True, help=
223 223 """
224 224 Autoindent IPython code entered interactively.
225 225 """
226 226 ).tag(config=True)
227 227
228 228 automagic = Bool(True, help=
229 229 """
230 230 Enable magic commands to be called without the leading %.
231 231 """
232 232 ).tag(config=True)
233 233
234 234 banner1 = Unicode(default_banner,
235 235 help="""The part of the banner to be printed before the profile"""
236 236 ).tag(config=True)
237 237 banner2 = Unicode('',
238 238 help="""The part of the banner to be printed after the profile"""
239 239 ).tag(config=True)
240 240
241 241 cache_size = Integer(1000, help=
242 242 """
243 243 Set the size of the output cache. The default is 1000, you can
244 244 change it permanently in your config file. Setting it to 0 completely
245 245 disables the caching system, and the minimum value accepted is 20 (if
246 246 you provide a value less than 20, it is reset to 0 and a warning is
247 247 issued). This limit is defined because otherwise you'll spend more
248 248 time re-flushing a too small cache than working
249 249 """
250 250 ).tag(config=True)
251 251 color_info = Bool(True, help=
252 252 """
253 253 Use colors for displaying information about objects. Because this
254 254 information is passed through a pager (like 'less'), and some pagers
255 255 get confused with color codes, this capability can be turned off.
256 256 """
257 257 ).tag(config=True)
258 258 colors = CaselessStrEnum(('Neutral', 'NoColor','LightBG','Linux'),
259 259 default_value='Neutral',
260 260 help="Set the color scheme (NoColor, Neutral, Linux, or LightBG)."
261 261 ).tag(config=True)
262 262 debug = Bool(False).tag(config=True)
263 263 disable_failing_post_execute = Bool(False,
264 264 help="Don't call post-execute functions that have failed in the past."
265 265 ).tag(config=True)
266 266 display_formatter = Instance(DisplayFormatter, allow_none=True)
267 267 displayhook_class = Type(DisplayHook)
268 268 display_pub_class = Type(DisplayPublisher)
269 269
270 270 sphinxify_docstring = Bool(False, help=
271 271 """
272 272 Enables rich html representation of docstrings. (This requires the
273 273 docrepr module).
274 274 """).tag(config=True)
275 275
276 276 @observe("sphinxify_docstring")
277 277 def _sphinxify_docstring_changed(self, change):
278 278 if change['new']:
279 279 warn("`sphinxify_docstring` is provisional since IPython 5.0 and might change in future versions." , ProvisionalWarning)
280 280
281 281 enable_html_pager = Bool(False, help=
282 282 """
283 283 (Provisional API) enables html representation in mime bundles sent
284 284 to pagers.
285 285 """).tag(config=True)
286 286
287 287 @observe("enable_html_pager")
288 288 def _enable_html_pager_changed(self, change):
289 289 if change['new']:
290 290 warn("`enable_html_pager` is provisional since IPython 5.0 and might change in future versions.", ProvisionalWarning)
291 291
292 292 data_pub_class = None
293 293
294 294 exit_now = Bool(False)
295 295 exiter = Instance(ExitAutocall)
296 296 @default('exiter')
297 297 def _exiter_default(self):
298 298 return ExitAutocall(self)
299 299 # Monotonically increasing execution counter
300 300 execution_count = Integer(1)
301 301 filename = Unicode("<ipython console>")
302 302 ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__
303 303
304 304 # Input splitter, to transform input line by line and detect when a block
305 305 # is ready to be executed.
306 306 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
307 307 (), {'line_input_checker': True})
308 308
309 309 # This InputSplitter instance is used to transform completed cells before
310 310 # running them. It allows cell magics to contain blank lines.
311 311 input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
312 312 (), {'line_input_checker': False})
313 313
314 314 logstart = Bool(False, help=
315 315 """
316 316 Start logging to the default log file in overwrite mode.
317 317 Use `logappend` to specify a log file to **append** logs to.
318 318 """
319 319 ).tag(config=True)
320 320 logfile = Unicode('', help=
321 321 """
322 322 The name of the logfile to use.
323 323 """
324 324 ).tag(config=True)
325 325 logappend = Unicode('', help=
326 326 """
327 327 Start logging to the given file in append mode.
328 328 Use `logfile` to specify a log file to **overwrite** logs to.
329 329 """
330 330 ).tag(config=True)
331 331 object_info_string_level = Enum((0,1,2), default_value=0,
332 332 ).tag(config=True)
333 333 pdb = Bool(False, help=
334 334 """
335 335 Automatically call the pdb debugger after every exception.
336 336 """
337 337 ).tag(config=True)
338 338 display_page = Bool(False,
339 339 help="""If True, anything that would be passed to the pager
340 340 will be displayed as regular output instead."""
341 341 ).tag(config=True)
342 342
343 343 # deprecated prompt traits:
344 344
345 345 prompt_in1 = Unicode('In [\\#]: ',
346 346 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
347 347 ).tag(config=True)
348 348 prompt_in2 = Unicode(' .\\D.: ',
349 349 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
350 350 ).tag(config=True)
351 351 prompt_out = Unicode('Out[\\#]: ',
352 352 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
353 353 ).tag(config=True)
354 354 prompts_pad_left = Bool(True,
355 355 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
356 356 ).tag(config=True)
357 357
358 358 @observe('prompt_in1', 'prompt_in2', 'prompt_out', 'prompt_pad_left')
359 359 def _prompt_trait_changed(self, change):
360 360 name = change['name']
361 361 warn("InteractiveShell.{name} is deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly.".format(
362 362 name=name)
363 363 )
364 364 # protect against weird cases where self.config may not exist:
365 365
366 366 show_rewritten_input = Bool(True,
367 367 help="Show rewritten input, e.g. for autocall."
368 368 ).tag(config=True)
369 369
370 370 quiet = Bool(False).tag(config=True)
371 371
372 372 history_length = Integer(10000,
373 373 help='Total length of command history'
374 374 ).tag(config=True)
375 375
376 376 history_load_length = Integer(1000, help=
377 377 """
378 378 The number of saved history entries to be loaded
379 379 into the history buffer at startup.
380 380 """
381 381 ).tag(config=True)
382 382
383 383 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'],
384 384 default_value='last_expr',
385 385 help="""
386 386 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
387 387 run interactively (displaying output from expressions)."""
388 388 ).tag(config=True)
389 389
390 390 # TODO: this part of prompt management should be moved to the frontends.
391 391 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
392 392 separate_in = SeparateUnicode('\n').tag(config=True)
393 393 separate_out = SeparateUnicode('').tag(config=True)
394 394 separate_out2 = SeparateUnicode('').tag(config=True)
395 395 wildcards_case_sensitive = Bool(True).tag(config=True)
396 396 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
397 397 default_value='Context').tag(config=True)
398 398
399 399 # Subcomponents of InteractiveShell
400 400 alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True)
401 401 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
402 402 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True)
403 403 display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True)
404 404 extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True)
405 405 payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True)
406 406 history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True)
407 407 magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True)
408 408
409 409 profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True)
410 410 @property
411 411 def profile(self):
412 412 if self.profile_dir is not None:
413 413 name = os.path.basename(self.profile_dir.location)
414 414 return name.replace('profile_','')
415 415
416 416
417 417 # Private interface
418 418 _post_execute = Dict()
419 419
420 420 # Tracks any GUI loop loaded for pylab
421 421 pylab_gui_select = None
422 422
423 423 last_execution_succeeded = Bool(True, help='Did last executed command succeeded')
424 424
425 425 def __init__(self, ipython_dir=None, profile_dir=None,
426 426 user_module=None, user_ns=None,
427 427 custom_exceptions=((), None), **kwargs):
428 428
429 429 # This is where traits with a config_key argument are updated
430 430 # from the values on config.
431 431 super(InteractiveShell, self).__init__(**kwargs)
432 432 if 'PromptManager' in self.config:
433 433 warn('As of IPython 5.0 `PromptManager` config will have no effect'
434 434 ' and has been replaced by TerminalInteractiveShell.prompts_class')
435 435 self.configurables = [self]
436 436
437 437 # These are relatively independent and stateless
438 438 self.init_ipython_dir(ipython_dir)
439 439 self.init_profile_dir(profile_dir)
440 440 self.init_instance_attrs()
441 441 self.init_environment()
442 442
443 443 # Check if we're in a virtualenv, and set up sys.path.
444 444 self.init_virtualenv()
445 445
446 446 # Create namespaces (user_ns, user_global_ns, etc.)
447 447 self.init_create_namespaces(user_module, user_ns)
448 448 # This has to be done after init_create_namespaces because it uses
449 449 # something in self.user_ns, but before init_sys_modules, which
450 450 # is the first thing to modify sys.
451 451 # TODO: When we override sys.stdout and sys.stderr before this class
452 452 # is created, we are saving the overridden ones here. Not sure if this
453 453 # is what we want to do.
454 454 self.save_sys_module_state()
455 455 self.init_sys_modules()
456 456
457 457 # While we're trying to have each part of the code directly access what
458 458 # it needs without keeping redundant references to objects, we have too
459 459 # much legacy code that expects ip.db to exist.
460 460 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
461 461
462 462 self.init_history()
463 463 self.init_encoding()
464 464 self.init_prefilter()
465 465
466 466 self.init_syntax_highlighting()
467 467 self.init_hooks()
468 468 self.init_events()
469 469 self.init_pushd_popd_magic()
470 470 self.init_user_ns()
471 471 self.init_logger()
472 472 self.init_builtins()
473 473
474 474 # The following was in post_config_initialization
475 475 self.init_inspector()
476 if py3compat.PY3:
477 self.raw_input_original = input
478 else:
479 self.raw_input_original = raw_input
476 self.raw_input_original = input
480 477 self.init_completer()
481 478 # TODO: init_io() needs to happen before init_traceback handlers
482 479 # because the traceback handlers hardcode the stdout/stderr streams.
483 480 # This logic in in debugger.Pdb and should eventually be changed.
484 481 self.init_io()
485 482 self.init_traceback_handlers(custom_exceptions)
486 483 self.init_prompts()
487 484 self.init_display_formatter()
488 485 self.init_display_pub()
489 486 self.init_data_pub()
490 487 self.init_displayhook()
491 488 self.init_magics()
492 489 self.init_alias()
493 490 self.init_logstart()
494 491 self.init_pdb()
495 492 self.init_extension_manager()
496 493 self.init_payload()
497 494 self.init_deprecation_warnings()
498 495 self.hooks.late_startup_hook()
499 496 self.events.trigger('shell_initialized', self)
500 497 atexit.register(self.atexit_operations)
501 498
502 499 def get_ipython(self):
503 500 """Return the currently running IPython instance."""
504 501 return self
505 502
506 503 #-------------------------------------------------------------------------
507 504 # Trait changed handlers
508 505 #-------------------------------------------------------------------------
509 506 @observe('ipython_dir')
510 507 def _ipython_dir_changed(self, change):
511 508 ensure_dir_exists(change['new'])
512 509
513 510 def set_autoindent(self,value=None):
514 511 """Set the autoindent flag.
515 512
516 513 If called with no arguments, it acts as a toggle."""
517 514 if value is None:
518 515 self.autoindent = not self.autoindent
519 516 else:
520 517 self.autoindent = value
521 518
522 519 #-------------------------------------------------------------------------
523 520 # init_* methods called by __init__
524 521 #-------------------------------------------------------------------------
525 522
526 523 def init_ipython_dir(self, ipython_dir):
527 524 if ipython_dir is not None:
528 525 self.ipython_dir = ipython_dir
529 526 return
530 527
531 528 self.ipython_dir = get_ipython_dir()
532 529
533 530 def init_profile_dir(self, profile_dir):
534 531 if profile_dir is not None:
535 532 self.profile_dir = profile_dir
536 533 return
537 534 self.profile_dir =\
538 535 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
539 536
540 537 def init_instance_attrs(self):
541 538 self.more = False
542 539
543 540 # command compiler
544 541 self.compile = CachingCompiler()
545 542
546 543 # Make an empty namespace, which extension writers can rely on both
547 544 # existing and NEVER being used by ipython itself. This gives them a
548 545 # convenient location for storing additional information and state
549 546 # their extensions may require, without fear of collisions with other
550 547 # ipython names that may develop later.
551 548 self.meta = Struct()
552 549
553 550 # Temporary files used for various purposes. Deleted at exit.
554 551 self.tempfiles = []
555 552 self.tempdirs = []
556 553
557 554 # keep track of where we started running (mainly for crash post-mortem)
558 555 # This is not being used anywhere currently.
559 556 self.starting_dir = py3compat.getcwd()
560 557
561 558 # Indentation management
562 559 self.indent_current_nsp = 0
563 560
564 561 # Dict to track post-execution functions that have been registered
565 562 self._post_execute = {}
566 563
567 564 def init_environment(self):
568 565 """Any changes we need to make to the user's environment."""
569 566 pass
570 567
571 568 def init_encoding(self):
572 569 # Get system encoding at startup time. Certain terminals (like Emacs
573 570 # under Win32 have it set to None, and we need to have a known valid
574 571 # encoding to use in the raw_input() method
575 572 try:
576 573 self.stdin_encoding = sys.stdin.encoding or 'ascii'
577 574 except AttributeError:
578 575 self.stdin_encoding = 'ascii'
579 576
580 def init_syntax_highlighting(self):
577
578 @observe('colors')
579 def init_syntax_highlighting(self, changes=None):
581 580 # Python source parser/formatter for syntax highlighting
582 pyformat = PyColorize.Parser().format
583 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
581 pyformat = PyColorize.Parser(style=self.colors).format
582 self.pycolorize = lambda src: pyformat(src,'str')
584 583
585 584 def refresh_style(self):
586 585 # No-op here, used in subclass
587 586 pass
588 587
589 588 def init_pushd_popd_magic(self):
590 589 # for pushd/popd management
591 590 self.home_dir = get_home_dir()
592 591
593 592 self.dir_stack = []
594 593
595 594 def init_logger(self):
596 595 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
597 596 logmode='rotate')
598 597
599 598 def init_logstart(self):
600 599 """Initialize logging in case it was requested at the command line.
601 600 """
602 601 if self.logappend:
603 602 self.magic('logstart %s append' % self.logappend)
604 603 elif self.logfile:
605 604 self.magic('logstart %s' % self.logfile)
606 605 elif self.logstart:
607 606 self.magic('logstart')
608 607
609 608 def init_deprecation_warnings(self):
610 609 """
611 610 register default filter for deprecation warning.
612 611
613 612 This will allow deprecation warning of function used interactively to show
614 613 warning to users, and still hide deprecation warning from libraries import.
615 614 """
616 615 warnings.filterwarnings("default", category=DeprecationWarning, module=self.user_ns.get("__name__"))
617 616
618 617 def init_builtins(self):
619 618 # A single, static flag that we set to True. Its presence indicates
620 619 # that an IPython shell has been created, and we make no attempts at
621 620 # removing on exit or representing the existence of more than one
622 621 # IPython at a time.
623 622 builtin_mod.__dict__['__IPYTHON__'] = True
624 623
625 624 self.builtin_trap = BuiltinTrap(shell=self)
626 625
627 626 def init_inspector(self):
628 627 # Object inspector
629 628 self.inspector = oinspect.Inspector(oinspect.InspectColors,
630 629 PyColorize.ANSICodeColors,
631 630 'NoColor',
632 631 self.object_info_string_level)
633 632
634 633 def init_io(self):
635 634 # This will just use sys.stdout and sys.stderr. If you want to
636 635 # override sys.stdout and sys.stderr themselves, you need to do that
637 636 # *before* instantiating this class, because io holds onto
638 637 # references to the underlying streams.
639 638 # io.std* are deprecated, but don't show our own deprecation warnings
640 639 # during initialization of the deprecated API.
641 640 with warnings.catch_warnings():
642 641 warnings.simplefilter('ignore', DeprecationWarning)
643 642 io.stdout = io.IOStream(sys.stdout)
644 643 io.stderr = io.IOStream(sys.stderr)
645 644
646 645 def init_prompts(self):
647 646 # Set system prompts, so that scripts can decide if they are running
648 647 # interactively.
649 648 sys.ps1 = 'In : '
650 649 sys.ps2 = '...: '
651 650 sys.ps3 = 'Out: '
652 651
653 652 def init_display_formatter(self):
654 653 self.display_formatter = DisplayFormatter(parent=self)
655 654 self.configurables.append(self.display_formatter)
656 655
657 656 def init_display_pub(self):
658 657 self.display_pub = self.display_pub_class(parent=self)
659 658 self.configurables.append(self.display_pub)
660 659
661 660 def init_data_pub(self):
662 661 if not self.data_pub_class:
663 662 self.data_pub = None
664 663 return
665 664 self.data_pub = self.data_pub_class(parent=self)
666 665 self.configurables.append(self.data_pub)
667 666
668 667 def init_displayhook(self):
669 668 # Initialize displayhook, set in/out prompts and printing system
670 669 self.displayhook = self.displayhook_class(
671 670 parent=self,
672 671 shell=self,
673 672 cache_size=self.cache_size,
674 673 )
675 674 self.configurables.append(self.displayhook)
676 675 # This is a context manager that installs/revmoes the displayhook at
677 676 # the appropriate time.
678 677 self.display_trap = DisplayTrap(hook=self.displayhook)
679 678
680 679 def init_virtualenv(self):
681 680 """Add a virtualenv to sys.path so the user can import modules from it.
682 681 This isn't perfect: it doesn't use the Python interpreter with which the
683 682 virtualenv was built, and it ignores the --no-site-packages option. A
684 683 warning will appear suggesting the user installs IPython in the
685 684 virtualenv, but for many cases, it probably works well enough.
686 685
687 686 Adapted from code snippets online.
688 687
689 688 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
690 689 """
691 690 if 'VIRTUAL_ENV' not in os.environ:
692 691 # Not in a virtualenv
693 692 return
694 693
695 694 # venv detection:
696 695 # stdlib venv may symlink sys.executable, so we can't use realpath.
697 696 # but others can symlink *to* the venv Python, so we can't just use sys.executable.
698 697 # So we just check every item in the symlink tree (generally <= 3)
699 698 p = os.path.normcase(sys.executable)
700 699 paths = [p]
701 700 while os.path.islink(p):
702 701 p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p)))
703 702 paths.append(p)
704 703 p_venv = os.path.normcase(os.environ['VIRTUAL_ENV'])
705 704 if any(p.startswith(p_venv) for p in paths):
706 705 # Running properly in the virtualenv, don't need to do anything
707 706 return
708 707
709 708 warn("Attempting to work in a virtualenv. If you encounter problems, please "
710 709 "install IPython inside the virtualenv.")
711 710 if sys.platform == "win32":
712 711 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
713 712 else:
714 713 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
715 714 'python%d.%d' % sys.version_info[:2], 'site-packages')
716 715
717 716 import site
718 717 sys.path.insert(0, virtual_env)
719 718 site.addsitedir(virtual_env)
720 719
721 720 #-------------------------------------------------------------------------
722 721 # Things related to injections into the sys module
723 722 #-------------------------------------------------------------------------
724 723
725 724 def save_sys_module_state(self):
726 725 """Save the state of hooks in the sys module.
727 726
728 727 This has to be called after self.user_module is created.
729 728 """
730 729 self._orig_sys_module_state = {'stdin': sys.stdin,
731 730 'stdout': sys.stdout,
732 731 'stderr': sys.stderr,
733 732 'excepthook': sys.excepthook}
734 733 self._orig_sys_modules_main_name = self.user_module.__name__
735 734 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
736 735
737 736 def restore_sys_module_state(self):
738 737 """Restore the state of the sys module."""
739 738 try:
740 739 for k, v in iteritems(self._orig_sys_module_state):
741 740 setattr(sys, k, v)
742 741 except AttributeError:
743 742 pass
744 743 # Reset what what done in self.init_sys_modules
745 744 if self._orig_sys_modules_main_mod is not None:
746 745 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
747 746
748 747 #-------------------------------------------------------------------------
749 748 # Things related to the banner
750 749 #-------------------------------------------------------------------------
751 750
752 751 @property
753 752 def banner(self):
754 753 banner = self.banner1
755 754 if self.profile and self.profile != 'default':
756 755 banner += '\nIPython profile: %s\n' % self.profile
757 756 if self.banner2:
758 757 banner += '\n' + self.banner2
759 758 return banner
760 759
761 760 def show_banner(self, banner=None):
762 761 if banner is None:
763 762 banner = self.banner
764 763 sys.stdout.write(banner)
765 764
766 765 #-------------------------------------------------------------------------
767 766 # Things related to hooks
768 767 #-------------------------------------------------------------------------
769 768
770 769 def init_hooks(self):
771 770 # hooks holds pointers used for user-side customizations
772 771 self.hooks = Struct()
773 772
774 773 self.strdispatchers = {}
775 774
776 775 # Set all default hooks, defined in the IPython.hooks module.
777 776 hooks = IPython.core.hooks
778 777 for hook_name in hooks.__all__:
779 778 # default hooks have priority 100, i.e. low; user hooks should have
780 779 # 0-100 priority
781 780 self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False)
782 781
783 782 if self.display_page:
784 783 self.set_hook('show_in_pager', page.as_hook(page.display_page), 90)
785 784
786 785 def set_hook(self,name,hook, priority=50, str_key=None, re_key=None,
787 786 _warn_deprecated=True):
788 787 """set_hook(name,hook) -> sets an internal IPython hook.
789 788
790 789 IPython exposes some of its internal API as user-modifiable hooks. By
791 790 adding your function to one of these hooks, you can modify IPython's
792 791 behavior to call at runtime your own routines."""
793 792
794 793 # At some point in the future, this should validate the hook before it
795 794 # accepts it. Probably at least check that the hook takes the number
796 795 # of args it's supposed to.
797 796
798 797 f = types.MethodType(hook,self)
799 798
800 799 # check if the hook is for strdispatcher first
801 800 if str_key is not None:
802 801 sdp = self.strdispatchers.get(name, StrDispatch())
803 802 sdp.add_s(str_key, f, priority )
804 803 self.strdispatchers[name] = sdp
805 804 return
806 805 if re_key is not None:
807 806 sdp = self.strdispatchers.get(name, StrDispatch())
808 807 sdp.add_re(re.compile(re_key), f, priority )
809 808 self.strdispatchers[name] = sdp
810 809 return
811 810
812 811 dp = getattr(self.hooks, name, None)
813 812 if name not in IPython.core.hooks.__all__:
814 813 print("Warning! Hook '%s' is not one of %s" % \
815 814 (name, IPython.core.hooks.__all__ ))
816 815
817 816 if _warn_deprecated and (name in IPython.core.hooks.deprecated):
818 817 alternative = IPython.core.hooks.deprecated[name]
819 818 warn("Hook {} is deprecated. Use {} instead.".format(name, alternative))
820 819
821 820 if not dp:
822 821 dp = IPython.core.hooks.CommandChainDispatcher()
823 822
824 823 try:
825 824 dp.add(f,priority)
826 825 except AttributeError:
827 826 # it was not commandchain, plain old func - replace
828 827 dp = f
829 828
830 829 setattr(self.hooks,name, dp)
831 830
832 831 #-------------------------------------------------------------------------
833 832 # Things related to events
834 833 #-------------------------------------------------------------------------
835 834
836 835 def init_events(self):
837 836 self.events = EventManager(self, available_events)
838 837
839 838 self.events.register("pre_execute", self._clear_warning_registry)
840 839
841 840 def register_post_execute(self, func):
842 841 """DEPRECATED: Use ip.events.register('post_run_cell', func)
843 842
844 843 Register a function for calling after code execution.
845 844 """
846 845 warn("ip.register_post_execute is deprecated, use "
847 846 "ip.events.register('post_run_cell', func) instead.")
848 847 self.events.register('post_run_cell', func)
849 848
850 849 def _clear_warning_registry(self):
851 850 # clear the warning registry, so that different code blocks with
852 851 # overlapping line number ranges don't cause spurious suppression of
853 852 # warnings (see gh-6611 for details)
854 853 if "__warningregistry__" in self.user_global_ns:
855 854 del self.user_global_ns["__warningregistry__"]
856 855
857 856 #-------------------------------------------------------------------------
858 857 # Things related to the "main" module
859 858 #-------------------------------------------------------------------------
860 859
861 860 def new_main_mod(self, filename, modname):
862 861 """Return a new 'main' module object for user code execution.
863 862
864 863 ``filename`` should be the path of the script which will be run in the
865 864 module. Requests with the same filename will get the same module, with
866 865 its namespace cleared.
867 866
868 867 ``modname`` should be the module name - normally either '__main__' or
869 868 the basename of the file without the extension.
870 869
871 870 When scripts are executed via %run, we must keep a reference to their
872 871 __main__ module around so that Python doesn't
873 872 clear it, rendering references to module globals useless.
874 873
875 874 This method keeps said reference in a private dict, keyed by the
876 875 absolute path of the script. This way, for multiple executions of the
877 876 same script we only keep one copy of the namespace (the last one),
878 877 thus preventing memory leaks from old references while allowing the
879 878 objects from the last execution to be accessible.
880 879 """
881 880 filename = os.path.abspath(filename)
882 881 try:
883 882 main_mod = self._main_mod_cache[filename]
884 883 except KeyError:
885 884 main_mod = self._main_mod_cache[filename] = types.ModuleType(
886 885 py3compat.cast_bytes_py2(modname),
887 886 doc="Module created for script run in IPython")
888 887 else:
889 888 main_mod.__dict__.clear()
890 889 main_mod.__name__ = modname
891 890
892 891 main_mod.__file__ = filename
893 892 # It seems pydoc (and perhaps others) needs any module instance to
894 893 # implement a __nonzero__ method
895 894 main_mod.__nonzero__ = lambda : True
896 895
897 896 return main_mod
898 897
899 898 def clear_main_mod_cache(self):
900 899 """Clear the cache of main modules.
901 900
902 901 Mainly for use by utilities like %reset.
903 902
904 903 Examples
905 904 --------
906 905
907 906 In [15]: import IPython
908 907
909 908 In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython')
910 909
911 910 In [17]: len(_ip._main_mod_cache) > 0
912 911 Out[17]: True
913 912
914 913 In [18]: _ip.clear_main_mod_cache()
915 914
916 915 In [19]: len(_ip._main_mod_cache) == 0
917 916 Out[19]: True
918 917 """
919 918 self._main_mod_cache.clear()
920 919
921 920 #-------------------------------------------------------------------------
922 921 # Things related to debugging
923 922 #-------------------------------------------------------------------------
924 923
925 924 def init_pdb(self):
926 925 # Set calling of pdb on exceptions
927 926 # self.call_pdb is a property
928 927 self.call_pdb = self.pdb
929 928
930 929 def _get_call_pdb(self):
931 930 return self._call_pdb
932 931
933 932 def _set_call_pdb(self,val):
934 933
935 934 if val not in (0,1,False,True):
936 935 raise ValueError('new call_pdb value must be boolean')
937 936
938 937 # store value in instance
939 938 self._call_pdb = val
940 939
941 940 # notify the actual exception handlers
942 941 self.InteractiveTB.call_pdb = val
943 942
944 943 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
945 944 'Control auto-activation of pdb at exceptions')
946 945
947 946 def debugger(self,force=False):
948 947 """Call the pdb debugger.
949 948
950 949 Keywords:
951 950
952 951 - force(False): by default, this routine checks the instance call_pdb
953 952 flag and does not actually invoke the debugger if the flag is false.
954 953 The 'force' option forces the debugger to activate even if the flag
955 954 is false.
956 955 """
957 956
958 957 if not (force or self.call_pdb):
959 958 return
960 959
961 960 if not hasattr(sys,'last_traceback'):
962 961 error('No traceback has been produced, nothing to debug.')
963 962 return
964 963
965 964 self.InteractiveTB.debugger(force=True)
966 965
967 966 #-------------------------------------------------------------------------
968 967 # Things related to IPython's various namespaces
969 968 #-------------------------------------------------------------------------
970 969 default_user_namespaces = True
971 970
972 971 def init_create_namespaces(self, user_module=None, user_ns=None):
973 972 # Create the namespace where the user will operate. user_ns is
974 973 # normally the only one used, and it is passed to the exec calls as
975 974 # the locals argument. But we do carry a user_global_ns namespace
976 975 # given as the exec 'globals' argument, This is useful in embedding
977 976 # situations where the ipython shell opens in a context where the
978 977 # distinction between locals and globals is meaningful. For
979 978 # non-embedded contexts, it is just the same object as the user_ns dict.
980 979
981 980 # FIXME. For some strange reason, __builtins__ is showing up at user
982 981 # level as a dict instead of a module. This is a manual fix, but I
983 982 # should really track down where the problem is coming from. Alex
984 983 # Schmolck reported this problem first.
985 984
986 985 # A useful post by Alex Martelli on this topic:
987 986 # Re: inconsistent value from __builtins__
988 987 # Von: Alex Martelli <aleaxit@yahoo.com>
989 988 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
990 989 # Gruppen: comp.lang.python
991 990
992 991 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
993 992 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
994 993 # > <type 'dict'>
995 994 # > >>> print type(__builtins__)
996 995 # > <type 'module'>
997 996 # > Is this difference in return value intentional?
998 997
999 998 # Well, it's documented that '__builtins__' can be either a dictionary
1000 999 # or a module, and it's been that way for a long time. Whether it's
1001 1000 # intentional (or sensible), I don't know. In any case, the idea is
1002 1001 # that if you need to access the built-in namespace directly, you
1003 1002 # should start with "import __builtin__" (note, no 's') which will
1004 1003 # definitely give you a module. Yeah, it's somewhat confusing:-(.
1005 1004
1006 1005 # These routines return a properly built module and dict as needed by
1007 1006 # the rest of the code, and can also be used by extension writers to
1008 1007 # generate properly initialized namespaces.
1009 1008 if (user_ns is not None) or (user_module is not None):
1010 1009 self.default_user_namespaces = False
1011 1010 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
1012 1011
1013 1012 # A record of hidden variables we have added to the user namespace, so
1014 1013 # we can list later only variables defined in actual interactive use.
1015 1014 self.user_ns_hidden = {}
1016 1015
1017 1016 # Now that FakeModule produces a real module, we've run into a nasty
1018 1017 # problem: after script execution (via %run), the module where the user
1019 1018 # code ran is deleted. Now that this object is a true module (needed
1020 1019 # so doctest and other tools work correctly), the Python module
1021 1020 # teardown mechanism runs over it, and sets to None every variable
1022 1021 # present in that module. Top-level references to objects from the
1023 1022 # script survive, because the user_ns is updated with them. However,
1024 1023 # calling functions defined in the script that use other things from
1025 1024 # the script will fail, because the function's closure had references
1026 1025 # to the original objects, which are now all None. So we must protect
1027 1026 # these modules from deletion by keeping a cache.
1028 1027 #
1029 1028 # To avoid keeping stale modules around (we only need the one from the
1030 1029 # last run), we use a dict keyed with the full path to the script, so
1031 1030 # only the last version of the module is held in the cache. Note,
1032 1031 # however, that we must cache the module *namespace contents* (their
1033 1032 # __dict__). Because if we try to cache the actual modules, old ones
1034 1033 # (uncached) could be destroyed while still holding references (such as
1035 1034 # those held by GUI objects that tend to be long-lived)>
1036 1035 #
1037 1036 # The %reset command will flush this cache. See the cache_main_mod()
1038 1037 # and clear_main_mod_cache() methods for details on use.
1039 1038
1040 1039 # This is the cache used for 'main' namespaces
1041 1040 self._main_mod_cache = {}
1042 1041
1043 1042 # A table holding all the namespaces IPython deals with, so that
1044 1043 # introspection facilities can search easily.
1045 1044 self.ns_table = {'user_global':self.user_module.__dict__,
1046 1045 'user_local':self.user_ns,
1047 1046 'builtin':builtin_mod.__dict__
1048 1047 }
1049 1048
1050 1049 @property
1051 1050 def user_global_ns(self):
1052 1051 return self.user_module.__dict__
1053 1052
1054 1053 def prepare_user_module(self, user_module=None, user_ns=None):
1055 1054 """Prepare the module and namespace in which user code will be run.
1056 1055
1057 1056 When IPython is started normally, both parameters are None: a new module
1058 1057 is created automatically, and its __dict__ used as the namespace.
1059 1058
1060 1059 If only user_module is provided, its __dict__ is used as the namespace.
1061 1060 If only user_ns is provided, a dummy module is created, and user_ns
1062 1061 becomes the global namespace. If both are provided (as they may be
1063 1062 when embedding), user_ns is the local namespace, and user_module
1064 1063 provides the global namespace.
1065 1064
1066 1065 Parameters
1067 1066 ----------
1068 1067 user_module : module, optional
1069 1068 The current user module in which IPython is being run. If None,
1070 1069 a clean module will be created.
1071 1070 user_ns : dict, optional
1072 1071 A namespace in which to run interactive commands.
1073 1072
1074 1073 Returns
1075 1074 -------
1076 1075 A tuple of user_module and user_ns, each properly initialised.
1077 1076 """
1078 1077 if user_module is None and user_ns is not None:
1079 1078 user_ns.setdefault("__name__", "__main__")
1080 1079 user_module = DummyMod()
1081 1080 user_module.__dict__ = user_ns
1082 1081
1083 1082 if user_module is None:
1084 1083 user_module = types.ModuleType("__main__",
1085 1084 doc="Automatically created module for IPython interactive environment")
1086 1085
1087 1086 # We must ensure that __builtin__ (without the final 's') is always
1088 1087 # available and pointing to the __builtin__ *module*. For more details:
1089 1088 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1090 1089 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1091 1090 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1092 1091
1093 1092 if user_ns is None:
1094 1093 user_ns = user_module.__dict__
1095 1094
1096 1095 return user_module, user_ns
1097 1096
1098 1097 def init_sys_modules(self):
1099 1098 # We need to insert into sys.modules something that looks like a
1100 1099 # module but which accesses the IPython namespace, for shelve and
1101 1100 # pickle to work interactively. Normally they rely on getting
1102 1101 # everything out of __main__, but for embedding purposes each IPython
1103 1102 # instance has its own private namespace, so we can't go shoving
1104 1103 # everything into __main__.
1105 1104
1106 1105 # note, however, that we should only do this for non-embedded
1107 1106 # ipythons, which really mimic the __main__.__dict__ with their own
1108 1107 # namespace. Embedded instances, on the other hand, should not do
1109 1108 # this because they need to manage the user local/global namespaces
1110 1109 # only, but they live within a 'normal' __main__ (meaning, they
1111 1110 # shouldn't overtake the execution environment of the script they're
1112 1111 # embedded in).
1113 1112
1114 1113 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1115 1114 main_name = self.user_module.__name__
1116 1115 sys.modules[main_name] = self.user_module
1117 1116
1118 1117 def init_user_ns(self):
1119 1118 """Initialize all user-visible namespaces to their minimum defaults.
1120 1119
1121 1120 Certain history lists are also initialized here, as they effectively
1122 1121 act as user namespaces.
1123 1122
1124 1123 Notes
1125 1124 -----
1126 1125 All data structures here are only filled in, they are NOT reset by this
1127 1126 method. If they were not empty before, data will simply be added to
1128 1127 therm.
1129 1128 """
1130 1129 # This function works in two parts: first we put a few things in
1131 1130 # user_ns, and we sync that contents into user_ns_hidden so that these
1132 1131 # initial variables aren't shown by %who. After the sync, we add the
1133 1132 # rest of what we *do* want the user to see with %who even on a new
1134 1133 # session (probably nothing, so they really only see their own stuff)
1135 1134
1136 1135 # The user dict must *always* have a __builtin__ reference to the
1137 1136 # Python standard __builtin__ namespace, which must be imported.
1138 1137 # This is so that certain operations in prompt evaluation can be
1139 1138 # reliably executed with builtins. Note that we can NOT use
1140 1139 # __builtins__ (note the 's'), because that can either be a dict or a
1141 1140 # module, and can even mutate at runtime, depending on the context
1142 1141 # (Python makes no guarantees on it). In contrast, __builtin__ is
1143 1142 # always a module object, though it must be explicitly imported.
1144 1143
1145 1144 # For more details:
1146 1145 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1147 1146 ns = dict()
1148 1147
1149 1148 # make global variables for user access to the histories
1150 1149 ns['_ih'] = self.history_manager.input_hist_parsed
1151 1150 ns['_oh'] = self.history_manager.output_hist
1152 1151 ns['_dh'] = self.history_manager.dir_hist
1153 1152
1154 1153 ns['_sh'] = shadowns
1155 1154
1156 1155 # user aliases to input and output histories. These shouldn't show up
1157 1156 # in %who, as they can have very large reprs.
1158 1157 ns['In'] = self.history_manager.input_hist_parsed
1159 1158 ns['Out'] = self.history_manager.output_hist
1160 1159
1161 1160 # Store myself as the public api!!!
1162 1161 ns['get_ipython'] = self.get_ipython
1163 1162
1164 1163 ns['exit'] = self.exiter
1165 1164 ns['quit'] = self.exiter
1166 1165
1167 1166 # Sync what we've added so far to user_ns_hidden so these aren't seen
1168 1167 # by %who
1169 1168 self.user_ns_hidden.update(ns)
1170 1169
1171 1170 # Anything put into ns now would show up in %who. Think twice before
1172 1171 # putting anything here, as we really want %who to show the user their
1173 1172 # stuff, not our variables.
1174 1173
1175 1174 # Finally, update the real user's namespace
1176 1175 self.user_ns.update(ns)
1177 1176
1178 1177 @property
1179 1178 def all_ns_refs(self):
1180 1179 """Get a list of references to all the namespace dictionaries in which
1181 1180 IPython might store a user-created object.
1182 1181
1183 1182 Note that this does not include the displayhook, which also caches
1184 1183 objects from the output."""
1185 1184 return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
1186 1185 [m.__dict__ for m in self._main_mod_cache.values()]
1187 1186
1188 1187 def reset(self, new_session=True):
1189 1188 """Clear all internal namespaces, and attempt to release references to
1190 1189 user objects.
1191 1190
1192 1191 If new_session is True, a new history session will be opened.
1193 1192 """
1194 1193 # Clear histories
1195 1194 self.history_manager.reset(new_session)
1196 1195 # Reset counter used to index all histories
1197 1196 if new_session:
1198 1197 self.execution_count = 1
1199 1198
1200 1199 # Flush cached output items
1201 1200 if self.displayhook.do_full_cache:
1202 1201 self.displayhook.flush()
1203 1202
1204 1203 # The main execution namespaces must be cleared very carefully,
1205 1204 # skipping the deletion of the builtin-related keys, because doing so
1206 1205 # would cause errors in many object's __del__ methods.
1207 1206 if self.user_ns is not self.user_global_ns:
1208 1207 self.user_ns.clear()
1209 1208 ns = self.user_global_ns
1210 1209 drop_keys = set(ns.keys())
1211 1210 drop_keys.discard('__builtin__')
1212 1211 drop_keys.discard('__builtins__')
1213 1212 drop_keys.discard('__name__')
1214 1213 for k in drop_keys:
1215 1214 del ns[k]
1216 1215
1217 1216 self.user_ns_hidden.clear()
1218 1217
1219 1218 # Restore the user namespaces to minimal usability
1220 1219 self.init_user_ns()
1221 1220
1222 1221 # Restore the default and user aliases
1223 1222 self.alias_manager.clear_aliases()
1224 1223 self.alias_manager.init_aliases()
1225 1224
1226 1225 # Flush the private list of module references kept for script
1227 1226 # execution protection
1228 1227 self.clear_main_mod_cache()
1229 1228
1230 1229 def del_var(self, varname, by_name=False):
1231 1230 """Delete a variable from the various namespaces, so that, as
1232 1231 far as possible, we're not keeping any hidden references to it.
1233 1232
1234 1233 Parameters
1235 1234 ----------
1236 1235 varname : str
1237 1236 The name of the variable to delete.
1238 1237 by_name : bool
1239 1238 If True, delete variables with the given name in each
1240 1239 namespace. If False (default), find the variable in the user
1241 1240 namespace, and delete references to it.
1242 1241 """
1243 1242 if varname in ('__builtin__', '__builtins__'):
1244 1243 raise ValueError("Refusing to delete %s" % varname)
1245 1244
1246 1245 ns_refs = self.all_ns_refs
1247 1246
1248 1247 if by_name: # Delete by name
1249 1248 for ns in ns_refs:
1250 1249 try:
1251 1250 del ns[varname]
1252 1251 except KeyError:
1253 1252 pass
1254 1253 else: # Delete by object
1255 1254 try:
1256 1255 obj = self.user_ns[varname]
1257 1256 except KeyError:
1258 1257 raise NameError("name '%s' is not defined" % varname)
1259 1258 # Also check in output history
1260 1259 ns_refs.append(self.history_manager.output_hist)
1261 1260 for ns in ns_refs:
1262 1261 to_delete = [n for n, o in iteritems(ns) if o is obj]
1263 1262 for name in to_delete:
1264 1263 del ns[name]
1265 1264
1266 1265 # displayhook keeps extra references, but not in a dictionary
1267 1266 for name in ('_', '__', '___'):
1268 1267 if getattr(self.displayhook, name) is obj:
1269 1268 setattr(self.displayhook, name, None)
1270 1269
1271 1270 def reset_selective(self, regex=None):
1272 1271 """Clear selective variables from internal namespaces based on a
1273 1272 specified regular expression.
1274 1273
1275 1274 Parameters
1276 1275 ----------
1277 1276 regex : string or compiled pattern, optional
1278 1277 A regular expression pattern that will be used in searching
1279 1278 variable names in the users namespaces.
1280 1279 """
1281 1280 if regex is not None:
1282 1281 try:
1283 1282 m = re.compile(regex)
1284 1283 except TypeError:
1285 1284 raise TypeError('regex must be a string or compiled pattern')
1286 1285 # Search for keys in each namespace that match the given regex
1287 1286 # If a match is found, delete the key/value pair.
1288 1287 for ns in self.all_ns_refs:
1289 1288 for var in ns:
1290 1289 if m.search(var):
1291 1290 del ns[var]
1292 1291
1293 1292 def push(self, variables, interactive=True):
1294 1293 """Inject a group of variables into the IPython user namespace.
1295 1294
1296 1295 Parameters
1297 1296 ----------
1298 1297 variables : dict, str or list/tuple of str
1299 1298 The variables to inject into the user's namespace. If a dict, a
1300 1299 simple update is done. If a str, the string is assumed to have
1301 1300 variable names separated by spaces. A list/tuple of str can also
1302 1301 be used to give the variable names. If just the variable names are
1303 1302 give (list/tuple/str) then the variable values looked up in the
1304 1303 callers frame.
1305 1304 interactive : bool
1306 1305 If True (default), the variables will be listed with the ``who``
1307 1306 magic.
1308 1307 """
1309 1308 vdict = None
1310 1309
1311 1310 # We need a dict of name/value pairs to do namespace updates.
1312 1311 if isinstance(variables, dict):
1313 1312 vdict = variables
1314 1313 elif isinstance(variables, string_types+(list, tuple)):
1315 1314 if isinstance(variables, string_types):
1316 1315 vlist = variables.split()
1317 1316 else:
1318 1317 vlist = variables
1319 1318 vdict = {}
1320 1319 cf = sys._getframe(1)
1321 1320 for name in vlist:
1322 1321 try:
1323 1322 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1324 1323 except:
1325 1324 print('Could not get variable %s from %s' %
1326 1325 (name,cf.f_code.co_name))
1327 1326 else:
1328 1327 raise ValueError('variables must be a dict/str/list/tuple')
1329 1328
1330 1329 # Propagate variables to user namespace
1331 1330 self.user_ns.update(vdict)
1332 1331
1333 1332 # And configure interactive visibility
1334 1333 user_ns_hidden = self.user_ns_hidden
1335 1334 if interactive:
1336 1335 for name in vdict:
1337 1336 user_ns_hidden.pop(name, None)
1338 1337 else:
1339 1338 user_ns_hidden.update(vdict)
1340 1339
1341 1340 def drop_by_id(self, variables):
1342 1341 """Remove a dict of variables from the user namespace, if they are the
1343 1342 same as the values in the dictionary.
1344 1343
1345 1344 This is intended for use by extensions: variables that they've added can
1346 1345 be taken back out if they are unloaded, without removing any that the
1347 1346 user has overwritten.
1348 1347
1349 1348 Parameters
1350 1349 ----------
1351 1350 variables : dict
1352 1351 A dictionary mapping object names (as strings) to the objects.
1353 1352 """
1354 1353 for name, obj in iteritems(variables):
1355 1354 if name in self.user_ns and self.user_ns[name] is obj:
1356 1355 del self.user_ns[name]
1357 1356 self.user_ns_hidden.pop(name, None)
1358 1357
1359 1358 #-------------------------------------------------------------------------
1360 1359 # Things related to object introspection
1361 1360 #-------------------------------------------------------------------------
1362 1361
1363 1362 def _ofind(self, oname, namespaces=None):
1364 1363 """Find an object in the available namespaces.
1365 1364
1366 1365 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1367 1366
1368 1367 Has special code to detect magic functions.
1369 1368 """
1370 1369 oname = oname.strip()
1371 1370 #print '1- oname: <%r>' % oname # dbg
1372 1371 if not oname.startswith(ESC_MAGIC) and \
1373 1372 not oname.startswith(ESC_MAGIC2) and \
1374 1373 not py3compat.isidentifier(oname, dotted=True):
1375 1374 return dict(found=False)
1376 1375
1377 1376 if namespaces is None:
1378 1377 # Namespaces to search in:
1379 1378 # Put them in a list. The order is important so that we
1380 1379 # find things in the same order that Python finds them.
1381 1380 namespaces = [ ('Interactive', self.user_ns),
1382 1381 ('Interactive (global)', self.user_global_ns),
1383 1382 ('Python builtin', builtin_mod.__dict__),
1384 1383 ]
1385 1384
1386 1385 # initialize results to 'null'
1387 1386 found = False; obj = None; ospace = None;
1388 1387 ismagic = False; isalias = False; parent = None
1389 1388
1390 1389 # We need to special-case 'print', which as of python2.6 registers as a
1391 1390 # function but should only be treated as one if print_function was
1392 1391 # loaded with a future import. In this case, just bail.
1393 1392 if (oname == 'print' and not py3compat.PY3 and not \
1394 1393 (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)):
1395 1394 return {'found':found, 'obj':obj, 'namespace':ospace,
1396 1395 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1397 1396
1398 1397 # Look for the given name by splitting it in parts. If the head is
1399 1398 # found, then we look for all the remaining parts as members, and only
1400 1399 # declare success if we can find them all.
1401 1400 oname_parts = oname.split('.')
1402 1401 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1403 1402 for nsname,ns in namespaces:
1404 1403 try:
1405 1404 obj = ns[oname_head]
1406 1405 except KeyError:
1407 1406 continue
1408 1407 else:
1409 1408 #print 'oname_rest:', oname_rest # dbg
1410 1409 for idx, part in enumerate(oname_rest):
1411 1410 try:
1412 1411 parent = obj
1413 1412 # The last part is looked up in a special way to avoid
1414 1413 # descriptor invocation as it may raise or have side
1415 1414 # effects.
1416 1415 if idx == len(oname_rest) - 1:
1417 1416 obj = self._getattr_property(obj, part)
1418 1417 else:
1419 1418 obj = getattr(obj, part)
1420 1419 except:
1421 1420 # Blanket except b/c some badly implemented objects
1422 1421 # allow __getattr__ to raise exceptions other than
1423 1422 # AttributeError, which then crashes IPython.
1424 1423 break
1425 1424 else:
1426 1425 # If we finish the for loop (no break), we got all members
1427 1426 found = True
1428 1427 ospace = nsname
1429 1428 break # namespace loop
1430 1429
1431 1430 # Try to see if it's magic
1432 1431 if not found:
1433 1432 obj = None
1434 1433 if oname.startswith(ESC_MAGIC2):
1435 1434 oname = oname.lstrip(ESC_MAGIC2)
1436 1435 obj = self.find_cell_magic(oname)
1437 1436 elif oname.startswith(ESC_MAGIC):
1438 1437 oname = oname.lstrip(ESC_MAGIC)
1439 1438 obj = self.find_line_magic(oname)
1440 1439 else:
1441 1440 # search without prefix, so run? will find %run?
1442 1441 obj = self.find_line_magic(oname)
1443 1442 if obj is None:
1444 1443 obj = self.find_cell_magic(oname)
1445 1444 if obj is not None:
1446 1445 found = True
1447 1446 ospace = 'IPython internal'
1448 1447 ismagic = True
1449 1448 isalias = isinstance(obj, Alias)
1450 1449
1451 1450 # Last try: special-case some literals like '', [], {}, etc:
1452 1451 if not found and oname_head in ["''",'""','[]','{}','()']:
1453 1452 obj = eval(oname_head)
1454 1453 found = True
1455 1454 ospace = 'Interactive'
1456 1455
1457 1456 return {'found':found, 'obj':obj, 'namespace':ospace,
1458 1457 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1459 1458
1460 1459 @staticmethod
1461 1460 def _getattr_property(obj, attrname):
1462 1461 """Property-aware getattr to use in object finding.
1463 1462
1464 1463 If attrname represents a property, return it unevaluated (in case it has
1465 1464 side effects or raises an error.
1466 1465
1467 1466 """
1468 1467 if not isinstance(obj, type):
1469 1468 try:
1470 1469 # `getattr(type(obj), attrname)` is not guaranteed to return
1471 1470 # `obj`, but does so for property:
1472 1471 #
1473 1472 # property.__get__(self, None, cls) -> self
1474 1473 #
1475 1474 # The universal alternative is to traverse the mro manually
1476 1475 # searching for attrname in class dicts.
1477 1476 attr = getattr(type(obj), attrname)
1478 1477 except AttributeError:
1479 1478 pass
1480 1479 else:
1481 1480 # This relies on the fact that data descriptors (with both
1482 1481 # __get__ & __set__ magic methods) take precedence over
1483 1482 # instance-level attributes:
1484 1483 #
1485 1484 # class A(object):
1486 1485 # @property
1487 1486 # def foobar(self): return 123
1488 1487 # a = A()
1489 1488 # a.__dict__['foobar'] = 345
1490 1489 # a.foobar # == 123
1491 1490 #
1492 1491 # So, a property may be returned right away.
1493 1492 if isinstance(attr, property):
1494 1493 return attr
1495 1494
1496 1495 # Nothing helped, fall back.
1497 1496 return getattr(obj, attrname)
1498 1497
1499 1498 def _object_find(self, oname, namespaces=None):
1500 1499 """Find an object and return a struct with info about it."""
1501 1500 return Struct(self._ofind(oname, namespaces))
1502 1501
1503 1502 def _inspect(self, meth, oname, namespaces=None, **kw):
1504 1503 """Generic interface to the inspector system.
1505 1504
1506 1505 This function is meant to be called by pdef, pdoc & friends.
1507 1506 """
1508 1507 info = self._object_find(oname, namespaces)
1509 1508 docformat = sphinxify if self.sphinxify_docstring else None
1510 1509 if info.found:
1511 1510 pmethod = getattr(self.inspector, meth)
1512 1511 # TODO: only apply format_screen to the plain/text repr of the mime
1513 1512 # bundle.
1514 1513 formatter = format_screen if info.ismagic else docformat
1515 1514 if meth == 'pdoc':
1516 1515 pmethod(info.obj, oname, formatter)
1517 1516 elif meth == 'pinfo':
1518 1517 pmethod(info.obj, oname, formatter, info,
1519 1518 enable_html_pager=self.enable_html_pager, **kw)
1520 1519 else:
1521 1520 pmethod(info.obj, oname)
1522 1521 else:
1523 1522 print('Object `%s` not found.' % oname)
1524 1523 return 'not found' # so callers can take other action
1525 1524
1526 1525 def object_inspect(self, oname, detail_level=0):
1527 1526 """Get object info about oname"""
1528 1527 with self.builtin_trap:
1529 1528 info = self._object_find(oname)
1530 1529 if info.found:
1531 1530 return self.inspector.info(info.obj, oname, info=info,
1532 1531 detail_level=detail_level
1533 1532 )
1534 1533 else:
1535 1534 return oinspect.object_info(name=oname, found=False)
1536 1535
1537 1536 def object_inspect_text(self, oname, detail_level=0):
1538 1537 """Get object info as formatted text"""
1539 1538 return self.object_inspect_mime(oname, detail_level)['text/plain']
1540 1539
1541 1540 def object_inspect_mime(self, oname, detail_level=0):
1542 1541 """Get object info as a mimebundle of formatted representations.
1543 1542
1544 1543 A mimebundle is a dictionary, keyed by mime-type.
1545 1544 It must always have the key `'text/plain'`.
1546 1545 """
1547 1546 with self.builtin_trap:
1548 1547 info = self._object_find(oname)
1549 1548 if info.found:
1550 1549 return self.inspector._get_info(info.obj, oname, info=info,
1551 1550 detail_level=detail_level
1552 1551 )
1553 1552 else:
1554 1553 raise KeyError(oname)
1555 1554
1556 1555 #-------------------------------------------------------------------------
1557 1556 # Things related to history management
1558 1557 #-------------------------------------------------------------------------
1559 1558
1560 1559 def init_history(self):
1561 1560 """Sets up the command history, and starts regular autosaves."""
1562 1561 self.history_manager = HistoryManager(shell=self, parent=self)
1563 1562 self.configurables.append(self.history_manager)
1564 1563
1565 1564 #-------------------------------------------------------------------------
1566 1565 # Things related to exception handling and tracebacks (not debugging)
1567 1566 #-------------------------------------------------------------------------
1568 1567
1569 1568 debugger_cls = Pdb
1570 1569
1571 1570 def init_traceback_handlers(self, custom_exceptions):
1572 1571 # Syntax error handler.
1573 1572 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1574 1573
1575 1574 # The interactive one is initialized with an offset, meaning we always
1576 1575 # want to remove the topmost item in the traceback, which is our own
1577 1576 # internal code. Valid modes: ['Plain','Context','Verbose']
1578 1577 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1579 1578 color_scheme='NoColor',
1580 1579 tb_offset = 1,
1581 1580 check_cache=check_linecache_ipython,
1582 1581 debugger_cls=self.debugger_cls)
1583 1582
1584 1583 # The instance will store a pointer to the system-wide exception hook,
1585 1584 # so that runtime code (such as magics) can access it. This is because
1586 1585 # during the read-eval loop, it may get temporarily overwritten.
1587 1586 self.sys_excepthook = sys.excepthook
1588 1587
1589 1588 # and add any custom exception handlers the user may have specified
1590 1589 self.set_custom_exc(*custom_exceptions)
1591 1590
1592 1591 # Set the exception mode
1593 1592 self.InteractiveTB.set_mode(mode=self.xmode)
1594 1593
1595 1594 def set_custom_exc(self, exc_tuple, handler):
1596 1595 """set_custom_exc(exc_tuple, handler)
1597 1596
1598 1597 Set a custom exception handler, which will be called if any of the
1599 1598 exceptions in exc_tuple occur in the mainloop (specifically, in the
1600 1599 run_code() method).
1601 1600
1602 1601 Parameters
1603 1602 ----------
1604 1603
1605 1604 exc_tuple : tuple of exception classes
1606 1605 A *tuple* of exception classes, for which to call the defined
1607 1606 handler. It is very important that you use a tuple, and NOT A
1608 1607 LIST here, because of the way Python's except statement works. If
1609 1608 you only want to trap a single exception, use a singleton tuple::
1610 1609
1611 1610 exc_tuple == (MyCustomException,)
1612 1611
1613 1612 handler : callable
1614 1613 handler must have the following signature::
1615 1614
1616 1615 def my_handler(self, etype, value, tb, tb_offset=None):
1617 1616 ...
1618 1617 return structured_traceback
1619 1618
1620 1619 Your handler must return a structured traceback (a list of strings),
1621 1620 or None.
1622 1621
1623 1622 This will be made into an instance method (via types.MethodType)
1624 1623 of IPython itself, and it will be called if any of the exceptions
1625 1624 listed in the exc_tuple are caught. If the handler is None, an
1626 1625 internal basic one is used, which just prints basic info.
1627 1626
1628 1627 To protect IPython from crashes, if your handler ever raises an
1629 1628 exception or returns an invalid result, it will be immediately
1630 1629 disabled.
1631 1630
1632 1631 WARNING: by putting in your own exception handler into IPython's main
1633 1632 execution loop, you run a very good chance of nasty crashes. This
1634 1633 facility should only be used if you really know what you are doing."""
1635 1634
1636 1635 assert type(exc_tuple)==type(()) , \
1637 1636 "The custom exceptions must be given AS A TUPLE."
1638 1637
1639 1638 def dummy_handler(self, etype, value, tb, tb_offset=None):
1640 1639 print('*** Simple custom exception handler ***')
1641 1640 print('Exception type :',etype)
1642 1641 print('Exception value:',value)
1643 1642 print('Traceback :',tb)
1644 1643 #print 'Source code :','\n'.join(self.buffer)
1645 1644
1646 1645 def validate_stb(stb):
1647 1646 """validate structured traceback return type
1648 1647
1649 1648 return type of CustomTB *should* be a list of strings, but allow
1650 1649 single strings or None, which are harmless.
1651 1650
1652 1651 This function will *always* return a list of strings,
1653 1652 and will raise a TypeError if stb is inappropriate.
1654 1653 """
1655 1654 msg = "CustomTB must return list of strings, not %r" % stb
1656 1655 if stb is None:
1657 1656 return []
1658 1657 elif isinstance(stb, string_types):
1659 1658 return [stb]
1660 1659 elif not isinstance(stb, list):
1661 1660 raise TypeError(msg)
1662 1661 # it's a list
1663 1662 for line in stb:
1664 1663 # check every element
1665 1664 if not isinstance(line, string_types):
1666 1665 raise TypeError(msg)
1667 1666 return stb
1668 1667
1669 1668 if handler is None:
1670 1669 wrapped = dummy_handler
1671 1670 else:
1672 1671 def wrapped(self,etype,value,tb,tb_offset=None):
1673 1672 """wrap CustomTB handler, to protect IPython from user code
1674 1673
1675 1674 This makes it harder (but not impossible) for custom exception
1676 1675 handlers to crash IPython.
1677 1676 """
1678 1677 try:
1679 1678 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1680 1679 return validate_stb(stb)
1681 1680 except:
1682 1681 # clear custom handler immediately
1683 1682 self.set_custom_exc((), None)
1684 1683 print("Custom TB Handler failed, unregistering", file=sys.stderr)
1685 1684 # show the exception in handler first
1686 1685 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1687 1686 print(self.InteractiveTB.stb2text(stb))
1688 1687 print("The original exception:")
1689 1688 stb = self.InteractiveTB.structured_traceback(
1690 1689 (etype,value,tb), tb_offset=tb_offset
1691 1690 )
1692 1691 return stb
1693 1692
1694 1693 self.CustomTB = types.MethodType(wrapped,self)
1695 1694 self.custom_exceptions = exc_tuple
1696 1695
1697 1696 def excepthook(self, etype, value, tb):
1698 1697 """One more defense for GUI apps that call sys.excepthook.
1699 1698
1700 1699 GUI frameworks like wxPython trap exceptions and call
1701 1700 sys.excepthook themselves. I guess this is a feature that
1702 1701 enables them to keep running after exceptions that would
1703 1702 otherwise kill their mainloop. This is a bother for IPython
1704 1703 which excepts to catch all of the program exceptions with a try:
1705 1704 except: statement.
1706 1705
1707 1706 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1708 1707 any app directly invokes sys.excepthook, it will look to the user like
1709 1708 IPython crashed. In order to work around this, we can disable the
1710 1709 CrashHandler and replace it with this excepthook instead, which prints a
1711 1710 regular traceback using our InteractiveTB. In this fashion, apps which
1712 1711 call sys.excepthook will generate a regular-looking exception from
1713 1712 IPython, and the CrashHandler will only be triggered by real IPython
1714 1713 crashes.
1715 1714
1716 1715 This hook should be used sparingly, only in places which are not likely
1717 1716 to be true IPython errors.
1718 1717 """
1719 1718 self.showtraceback((etype, value, tb), tb_offset=0)
1720 1719
1721 1720 def _get_exc_info(self, exc_tuple=None):
1722 1721 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
1723 1722
1724 1723 Ensures sys.last_type,value,traceback hold the exc_info we found,
1725 1724 from whichever source.
1726 1725
1727 1726 raises ValueError if none of these contain any information
1728 1727 """
1729 1728 if exc_tuple is None:
1730 1729 etype, value, tb = sys.exc_info()
1731 1730 else:
1732 1731 etype, value, tb = exc_tuple
1733 1732
1734 1733 if etype is None:
1735 1734 if hasattr(sys, 'last_type'):
1736 1735 etype, value, tb = sys.last_type, sys.last_value, \
1737 1736 sys.last_traceback
1738 1737
1739 1738 if etype is None:
1740 1739 raise ValueError("No exception to find")
1741 1740
1742 1741 # Now store the exception info in sys.last_type etc.
1743 1742 # WARNING: these variables are somewhat deprecated and not
1744 1743 # necessarily safe to use in a threaded environment, but tools
1745 1744 # like pdb depend on their existence, so let's set them. If we
1746 1745 # find problems in the field, we'll need to revisit their use.
1747 1746 sys.last_type = etype
1748 1747 sys.last_value = value
1749 1748 sys.last_traceback = tb
1750 1749
1751 1750 return etype, value, tb
1752 1751
1753 1752 def show_usage_error(self, exc):
1754 1753 """Show a short message for UsageErrors
1755 1754
1756 1755 These are special exceptions that shouldn't show a traceback.
1757 1756 """
1758 1757 print("UsageError: %s" % exc, file=sys.stderr)
1759 1758
1760 1759 def get_exception_only(self, exc_tuple=None):
1761 1760 """
1762 1761 Return as a string (ending with a newline) the exception that
1763 1762 just occurred, without any traceback.
1764 1763 """
1765 1764 etype, value, tb = self._get_exc_info(exc_tuple)
1766 1765 msg = traceback.format_exception_only(etype, value)
1767 1766 return ''.join(msg)
1768 1767
1769 1768 def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None,
1770 1769 exception_only=False):
1771 1770 """Display the exception that just occurred.
1772 1771
1773 1772 If nothing is known about the exception, this is the method which
1774 1773 should be used throughout the code for presenting user tracebacks,
1775 1774 rather than directly invoking the InteractiveTB object.
1776 1775
1777 1776 A specific showsyntaxerror() also exists, but this method can take
1778 1777 care of calling it if needed, so unless you are explicitly catching a
1779 1778 SyntaxError exception, don't try to analyze the stack manually and
1780 1779 simply call this method."""
1781 1780
1782 1781 try:
1783 1782 try:
1784 1783 etype, value, tb = self._get_exc_info(exc_tuple)
1785 1784 except ValueError:
1786 1785 print('No traceback available to show.', file=sys.stderr)
1787 1786 return
1788 1787
1789 1788 if issubclass(etype, SyntaxError):
1790 1789 # Though this won't be called by syntax errors in the input
1791 1790 # line, there may be SyntaxError cases with imported code.
1792 1791 self.showsyntaxerror(filename)
1793 1792 elif etype is UsageError:
1794 1793 self.show_usage_error(value)
1795 1794 else:
1796 1795 if exception_only:
1797 1796 stb = ['An exception has occurred, use %tb to see '
1798 1797 'the full traceback.\n']
1799 1798 stb.extend(self.InteractiveTB.get_exception_only(etype,
1800 1799 value))
1801 1800 else:
1802 1801 try:
1803 1802 # Exception classes can customise their traceback - we
1804 1803 # use this in IPython.parallel for exceptions occurring
1805 1804 # in the engines. This should return a list of strings.
1806 1805 stb = value._render_traceback_()
1807 1806 except Exception:
1808 1807 stb = self.InteractiveTB.structured_traceback(etype,
1809 1808 value, tb, tb_offset=tb_offset)
1810 1809
1811 1810 self._showtraceback(etype, value, stb)
1812 1811 if self.call_pdb:
1813 1812 # drop into debugger
1814 1813 self.debugger(force=True)
1815 1814 return
1816 1815
1817 1816 # Actually show the traceback
1818 1817 self._showtraceback(etype, value, stb)
1819 1818
1820 1819 except KeyboardInterrupt:
1821 1820 print('\n' + self.get_exception_only(), file=sys.stderr)
1822 1821
1823 1822 def _showtraceback(self, etype, evalue, stb):
1824 1823 """Actually show a traceback.
1825 1824
1826 1825 Subclasses may override this method to put the traceback on a different
1827 1826 place, like a side channel.
1828 1827 """
1829 1828 print(self.InteractiveTB.stb2text(stb))
1830 1829
1831 1830 def showsyntaxerror(self, filename=None):
1832 1831 """Display the syntax error that just occurred.
1833 1832
1834 1833 This doesn't display a stack trace because there isn't one.
1835 1834
1836 1835 If a filename is given, it is stuffed in the exception instead
1837 1836 of what was there before (because Python's parser always uses
1838 1837 "<string>" when reading from a string).
1839 1838 """
1840 1839 etype, value, last_traceback = self._get_exc_info()
1841 1840
1842 1841 if filename and issubclass(etype, SyntaxError):
1843 1842 try:
1844 1843 value.filename = filename
1845 1844 except:
1846 1845 # Not the format we expect; leave it alone
1847 1846 pass
1848 1847
1849 1848 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1850 1849 self._showtraceback(etype, value, stb)
1851 1850
1852 1851 # This is overridden in TerminalInteractiveShell to show a message about
1853 1852 # the %paste magic.
1854 1853 def showindentationerror(self):
1855 1854 """Called by run_cell when there's an IndentationError in code entered
1856 1855 at the prompt.
1857 1856
1858 1857 This is overridden in TerminalInteractiveShell to show a message about
1859 1858 the %paste magic."""
1860 1859 self.showsyntaxerror()
1861 1860
1862 1861 #-------------------------------------------------------------------------
1863 1862 # Things related to readline
1864 1863 #-------------------------------------------------------------------------
1865 1864
1866 1865 def init_readline(self):
1867 1866 """DEPRECATED
1868 1867
1869 1868 Moved to terminal subclass, here only to simplify the init logic."""
1870 1869 # Set a number of methods that depend on readline to be no-op
1871 1870 warnings.warn('`init_readline` is no-op since IPython 5.0 and is Deprecated',
1872 1871 DeprecationWarning, stacklevel=2)
1873 1872 self.set_custom_completer = no_op
1874 1873
1875 1874 @skip_doctest
1876 1875 def set_next_input(self, s, replace=False):
1877 1876 """ Sets the 'default' input string for the next command line.
1878 1877
1879 1878 Example::
1880 1879
1881 1880 In [1]: _ip.set_next_input("Hello Word")
1882 1881 In [2]: Hello Word_ # cursor is here
1883 1882 """
1884 1883 self.rl_next_input = py3compat.cast_bytes_py2(s)
1885 1884
1886 1885 def _indent_current_str(self):
1887 1886 """return the current level of indentation as a string"""
1888 1887 return self.input_splitter.indent_spaces * ' '
1889 1888
1890 1889 #-------------------------------------------------------------------------
1891 1890 # Things related to text completion
1892 1891 #-------------------------------------------------------------------------
1893 1892
1894 1893 def init_completer(self):
1895 1894 """Initialize the completion machinery.
1896 1895
1897 1896 This creates completion machinery that can be used by client code,
1898 1897 either interactively in-process (typically triggered by the readline
1899 1898 library), programmatically (such as in test suites) or out-of-process
1900 1899 (typically over the network by remote frontends).
1901 1900 """
1902 1901 from IPython.core.completer import IPCompleter
1903 1902 from IPython.core.completerlib import (module_completer,
1904 1903 magic_run_completer, cd_completer, reset_completer)
1905 1904
1906 1905 self.Completer = IPCompleter(shell=self,
1907 1906 namespace=self.user_ns,
1908 1907 global_namespace=self.user_global_ns,
1909 1908 use_readline=False,
1910 1909 parent=self,
1911 1910 )
1912 1911 self.configurables.append(self.Completer)
1913 1912
1914 1913 # Add custom completers to the basic ones built into IPCompleter
1915 1914 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1916 1915 self.strdispatchers['complete_command'] = sdisp
1917 1916 self.Completer.custom_completers = sdisp
1918 1917
1919 1918 self.set_hook('complete_command', module_completer, str_key = 'import')
1920 1919 self.set_hook('complete_command', module_completer, str_key = 'from')
1921 1920 self.set_hook('complete_command', module_completer, str_key = '%aimport')
1922 1921 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1923 1922 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1924 1923 self.set_hook('complete_command', reset_completer, str_key = '%reset')
1925 1924
1926 1925
1927 1926 @skip_doctest_py2
1928 1927 def complete(self, text, line=None, cursor_pos=None):
1929 1928 """Return the completed text and a list of completions.
1930 1929
1931 1930 Parameters
1932 1931 ----------
1933 1932
1934 1933 text : string
1935 1934 A string of text to be completed on. It can be given as empty and
1936 1935 instead a line/position pair are given. In this case, the
1937 1936 completer itself will split the line like readline does.
1938 1937
1939 1938 line : string, optional
1940 1939 The complete line that text is part of.
1941 1940
1942 1941 cursor_pos : int, optional
1943 1942 The position of the cursor on the input line.
1944 1943
1945 1944 Returns
1946 1945 -------
1947 1946 text : string
1948 1947 The actual text that was completed.
1949 1948
1950 1949 matches : list
1951 1950 A sorted list with all possible completions.
1952 1951
1953 1952 The optional arguments allow the completion to take more context into
1954 1953 account, and are part of the low-level completion API.
1955 1954
1956 1955 This is a wrapper around the completion mechanism, similar to what
1957 1956 readline does at the command line when the TAB key is hit. By
1958 1957 exposing it as a method, it can be used by other non-readline
1959 1958 environments (such as GUIs) for text completion.
1960 1959
1961 1960 Simple usage example:
1962 1961
1963 1962 In [1]: x = 'hello'
1964 1963
1965 1964 In [2]: _ip.complete('x.l')
1966 1965 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1967 1966 """
1968 1967
1969 1968 # Inject names into __builtin__ so we can complete on the added names.
1970 1969 with self.builtin_trap:
1971 1970 return self.Completer.complete(text, line, cursor_pos)
1972 1971
1973 1972 def set_custom_completer(self, completer, pos=0):
1974 1973 """Adds a new custom completer function.
1975 1974
1976 1975 The position argument (defaults to 0) is the index in the completers
1977 1976 list where you want the completer to be inserted."""
1978 1977
1979 1978 newcomp = types.MethodType(completer,self.Completer)
1980 1979 self.Completer.matchers.insert(pos,newcomp)
1981 1980
1982 1981 def set_completer_frame(self, frame=None):
1983 1982 """Set the frame of the completer."""
1984 1983 if frame:
1985 1984 self.Completer.namespace = frame.f_locals
1986 1985 self.Completer.global_namespace = frame.f_globals
1987 1986 else:
1988 1987 self.Completer.namespace = self.user_ns
1989 1988 self.Completer.global_namespace = self.user_global_ns
1990 1989
1991 1990 #-------------------------------------------------------------------------
1992 1991 # Things related to magics
1993 1992 #-------------------------------------------------------------------------
1994 1993
1995 1994 def init_magics(self):
1996 1995 from IPython.core import magics as m
1997 1996 self.magics_manager = magic.MagicsManager(shell=self,
1998 1997 parent=self,
1999 1998 user_magics=m.UserMagics(self))
2000 1999 self.configurables.append(self.magics_manager)
2001 2000
2002 2001 # Expose as public API from the magics manager
2003 2002 self.register_magics = self.magics_manager.register
2004 2003
2005 2004 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
2006 2005 m.ConfigMagics, m.DisplayMagics, m.ExecutionMagics,
2007 2006 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2008 2007 m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics,
2009 2008 )
2010 2009
2011 2010 # Register Magic Aliases
2012 2011 mman = self.magics_manager
2013 2012 # FIXME: magic aliases should be defined by the Magics classes
2014 2013 # or in MagicsManager, not here
2015 2014 mman.register_alias('ed', 'edit')
2016 2015 mman.register_alias('hist', 'history')
2017 2016 mman.register_alias('rep', 'recall')
2018 2017 mman.register_alias('SVG', 'svg', 'cell')
2019 2018 mman.register_alias('HTML', 'html', 'cell')
2020 2019 mman.register_alias('file', 'writefile', 'cell')
2021 2020
2022 2021 # FIXME: Move the color initialization to the DisplayHook, which
2023 2022 # should be split into a prompt manager and displayhook. We probably
2024 2023 # even need a centralize colors management object.
2025 2024 self.magic('colors %s' % self.colors)
2026 2025
2027 2026 # Defined here so that it's included in the documentation
2028 2027 @functools.wraps(magic.MagicsManager.register_function)
2029 2028 def register_magic_function(self, func, magic_kind='line', magic_name=None):
2030 2029 self.magics_manager.register_function(func,
2031 2030 magic_kind=magic_kind, magic_name=magic_name)
2032 2031
2033 2032 def run_line_magic(self, magic_name, line):
2034 2033 """Execute the given line magic.
2035 2034
2036 2035 Parameters
2037 2036 ----------
2038 2037 magic_name : str
2039 2038 Name of the desired magic function, without '%' prefix.
2040 2039
2041 2040 line : str
2042 2041 The rest of the input line as a single string.
2043 2042 """
2044 2043 fn = self.find_line_magic(magic_name)
2045 2044 if fn is None:
2046 2045 cm = self.find_cell_magic(magic_name)
2047 2046 etpl = "Line magic function `%%%s` not found%s."
2048 2047 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2049 2048 'did you mean that instead?)' % magic_name )
2050 2049 error(etpl % (magic_name, extra))
2051 2050 else:
2052 2051 # Note: this is the distance in the stack to the user's frame.
2053 2052 # This will need to be updated if the internal calling logic gets
2054 2053 # refactored, or else we'll be expanding the wrong variables.
2055 2054 stack_depth = 2
2056 2055 magic_arg_s = self.var_expand(line, stack_depth)
2057 2056 # Put magic args in a list so we can call with f(*a) syntax
2058 2057 args = [magic_arg_s]
2059 2058 kwargs = {}
2060 2059 # Grab local namespace if we need it:
2061 2060 if getattr(fn, "needs_local_scope", False):
2062 2061 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2063 2062 with self.builtin_trap:
2064 2063 result = fn(*args,**kwargs)
2065 2064 return result
2066 2065
2067 2066 def run_cell_magic(self, magic_name, line, cell):
2068 2067 """Execute the given cell magic.
2069 2068
2070 2069 Parameters
2071 2070 ----------
2072 2071 magic_name : str
2073 2072 Name of the desired magic function, without '%' prefix.
2074 2073
2075 2074 line : str
2076 2075 The rest of the first input line as a single string.
2077 2076
2078 2077 cell : str
2079 2078 The body of the cell as a (possibly multiline) string.
2080 2079 """
2081 2080 fn = self.find_cell_magic(magic_name)
2082 2081 if fn is None:
2083 2082 lm = self.find_line_magic(magic_name)
2084 2083 etpl = "Cell magic `%%{0}` not found{1}."
2085 2084 extra = '' if lm is None else (' (But line magic `%{0}` exists, '
2086 2085 'did you mean that instead?)'.format(magic_name))
2087 2086 error(etpl.format(magic_name, extra))
2088 2087 elif cell == '':
2089 2088 message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
2090 2089 if self.find_line_magic(magic_name) is not None:
2091 2090 message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
2092 2091 raise UsageError(message)
2093 2092 else:
2094 2093 # Note: this is the distance in the stack to the user's frame.
2095 2094 # This will need to be updated if the internal calling logic gets
2096 2095 # refactored, or else we'll be expanding the wrong variables.
2097 2096 stack_depth = 2
2098 2097 magic_arg_s = self.var_expand(line, stack_depth)
2099 2098 with self.builtin_trap:
2100 2099 result = fn(magic_arg_s, cell)
2101 2100 return result
2102 2101
2103 2102 def find_line_magic(self, magic_name):
2104 2103 """Find and return a line magic by name.
2105 2104
2106 2105 Returns None if the magic isn't found."""
2107 2106 return self.magics_manager.magics['line'].get(magic_name)
2108 2107
2109 2108 def find_cell_magic(self, magic_name):
2110 2109 """Find and return a cell magic by name.
2111 2110
2112 2111 Returns None if the magic isn't found."""
2113 2112 return self.magics_manager.magics['cell'].get(magic_name)
2114 2113
2115 2114 def find_magic(self, magic_name, magic_kind='line'):
2116 2115 """Find and return a magic of the given type by name.
2117 2116
2118 2117 Returns None if the magic isn't found."""
2119 2118 return self.magics_manager.magics[magic_kind].get(magic_name)
2120 2119
2121 2120 def magic(self, arg_s):
2122 2121 """DEPRECATED. Use run_line_magic() instead.
2123 2122
2124 2123 Call a magic function by name.
2125 2124
2126 2125 Input: a string containing the name of the magic function to call and
2127 2126 any additional arguments to be passed to the magic.
2128 2127
2129 2128 magic('name -opt foo bar') is equivalent to typing at the ipython
2130 2129 prompt:
2131 2130
2132 2131 In[1]: %name -opt foo bar
2133 2132
2134 2133 To call a magic without arguments, simply use magic('name').
2135 2134
2136 2135 This provides a proper Python function to call IPython's magics in any
2137 2136 valid Python code you can type at the interpreter, including loops and
2138 2137 compound statements.
2139 2138 """
2140 2139 # TODO: should we issue a loud deprecation warning here?
2141 2140 magic_name, _, magic_arg_s = arg_s.partition(' ')
2142 2141 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2143 2142 return self.run_line_magic(magic_name, magic_arg_s)
2144 2143
2145 2144 #-------------------------------------------------------------------------
2146 2145 # Things related to macros
2147 2146 #-------------------------------------------------------------------------
2148 2147
2149 2148 def define_macro(self, name, themacro):
2150 2149 """Define a new macro
2151 2150
2152 2151 Parameters
2153 2152 ----------
2154 2153 name : str
2155 2154 The name of the macro.
2156 2155 themacro : str or Macro
2157 2156 The action to do upon invoking the macro. If a string, a new
2158 2157 Macro object is created by passing the string to it.
2159 2158 """
2160 2159
2161 2160 from IPython.core import macro
2162 2161
2163 2162 if isinstance(themacro, string_types):
2164 2163 themacro = macro.Macro(themacro)
2165 2164 if not isinstance(themacro, macro.Macro):
2166 2165 raise ValueError('A macro must be a string or a Macro instance.')
2167 2166 self.user_ns[name] = themacro
2168 2167
2169 2168 #-------------------------------------------------------------------------
2170 2169 # Things related to the running of system commands
2171 2170 #-------------------------------------------------------------------------
2172 2171
2173 2172 def system_piped(self, cmd):
2174 2173 """Call the given cmd in a subprocess, piping stdout/err
2175 2174
2176 2175 Parameters
2177 2176 ----------
2178 2177 cmd : str
2179 2178 Command to execute (can not end in '&', as background processes are
2180 2179 not supported. Should not be a command that expects input
2181 2180 other than simple text.
2182 2181 """
2183 2182 if cmd.rstrip().endswith('&'):
2184 2183 # this is *far* from a rigorous test
2185 2184 # We do not support backgrounding processes because we either use
2186 2185 # pexpect or pipes to read from. Users can always just call
2187 2186 # os.system() or use ip.system=ip.system_raw
2188 2187 # if they really want a background process.
2189 2188 raise OSError("Background processes not supported.")
2190 2189
2191 2190 # we explicitly do NOT return the subprocess status code, because
2192 2191 # a non-None value would trigger :func:`sys.displayhook` calls.
2193 2192 # Instead, we store the exit_code in user_ns.
2194 2193 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2195 2194
2196 2195 def system_raw(self, cmd):
2197 2196 """Call the given cmd in a subprocess using os.system on Windows or
2198 2197 subprocess.call using the system shell on other platforms.
2199 2198
2200 2199 Parameters
2201 2200 ----------
2202 2201 cmd : str
2203 2202 Command to execute.
2204 2203 """
2205 2204 cmd = self.var_expand(cmd, depth=1)
2206 2205 # protect os.system from UNC paths on Windows, which it can't handle:
2207 2206 if sys.platform == 'win32':
2208 2207 from IPython.utils._process_win32 import AvoidUNCPath
2209 2208 with AvoidUNCPath() as path:
2210 2209 if path is not None:
2211 2210 cmd = '"pushd %s &&"%s' % (path, cmd)
2212 2211 cmd = py3compat.unicode_to_str(cmd)
2213 2212 try:
2214 2213 ec = os.system(cmd)
2215 2214 except KeyboardInterrupt:
2216 2215 print('\n' + self.get_exception_only(), file=sys.stderr)
2217 2216 ec = -2
2218 2217 else:
2219 2218 cmd = py3compat.unicode_to_str(cmd)
2220 2219 # For posix the result of the subprocess.call() below is an exit
2221 2220 # code, which by convention is zero for success, positive for
2222 2221 # program failure. Exit codes above 128 are reserved for signals,
2223 2222 # and the formula for converting a signal to an exit code is usually
2224 2223 # signal_number+128. To more easily differentiate between exit
2225 2224 # codes and signals, ipython uses negative numbers. For instance
2226 2225 # since control-c is signal 2 but exit code 130, ipython's
2227 2226 # _exit_code variable will read -2. Note that some shells like
2228 2227 # csh and fish don't follow sh/bash conventions for exit codes.
2229 2228 executable = os.environ.get('SHELL', None)
2230 2229 try:
2231 2230 # Use env shell instead of default /bin/sh
2232 2231 ec = subprocess.call(cmd, shell=True, executable=executable)
2233 2232 except KeyboardInterrupt:
2234 2233 # intercept control-C; a long traceback is not useful here
2235 2234 print('\n' + self.get_exception_only(), file=sys.stderr)
2236 2235 ec = 130
2237 2236 if ec > 128:
2238 2237 ec = -(ec - 128)
2239 2238
2240 2239 # We explicitly do NOT return the subprocess status code, because
2241 2240 # a non-None value would trigger :func:`sys.displayhook` calls.
2242 2241 # Instead, we store the exit_code in user_ns. Note the semantics
2243 2242 # of _exit_code: for control-c, _exit_code == -signal.SIGNIT,
2244 2243 # but raising SystemExit(_exit_code) will give status 254!
2245 2244 self.user_ns['_exit_code'] = ec
2246 2245
2247 2246 # use piped system by default, because it is better behaved
2248 2247 system = system_piped
2249 2248
2250 2249 def getoutput(self, cmd, split=True, depth=0):
2251 2250 """Get output (possibly including stderr) from a subprocess.
2252 2251
2253 2252 Parameters
2254 2253 ----------
2255 2254 cmd : str
2256 2255 Command to execute (can not end in '&', as background processes are
2257 2256 not supported.
2258 2257 split : bool, optional
2259 2258 If True, split the output into an IPython SList. Otherwise, an
2260 2259 IPython LSString is returned. These are objects similar to normal
2261 2260 lists and strings, with a few convenience attributes for easier
2262 2261 manipulation of line-based output. You can use '?' on them for
2263 2262 details.
2264 2263 depth : int, optional
2265 2264 How many frames above the caller are the local variables which should
2266 2265 be expanded in the command string? The default (0) assumes that the
2267 2266 expansion variables are in the stack frame calling this function.
2268 2267 """
2269 2268 if cmd.rstrip().endswith('&'):
2270 2269 # this is *far* from a rigorous test
2271 2270 raise OSError("Background processes not supported.")
2272 2271 out = getoutput(self.var_expand(cmd, depth=depth+1))
2273 2272 if split:
2274 2273 out = SList(out.splitlines())
2275 2274 else:
2276 2275 out = LSString(out)
2277 2276 return out
2278 2277
2279 2278 #-------------------------------------------------------------------------
2280 2279 # Things related to aliases
2281 2280 #-------------------------------------------------------------------------
2282 2281
2283 2282 def init_alias(self):
2284 2283 self.alias_manager = AliasManager(shell=self, parent=self)
2285 2284 self.configurables.append(self.alias_manager)
2286 2285
2287 2286 #-------------------------------------------------------------------------
2288 2287 # Things related to extensions
2289 2288 #-------------------------------------------------------------------------
2290 2289
2291 2290 def init_extension_manager(self):
2292 2291 self.extension_manager = ExtensionManager(shell=self, parent=self)
2293 2292 self.configurables.append(self.extension_manager)
2294 2293
2295 2294 #-------------------------------------------------------------------------
2296 2295 # Things related to payloads
2297 2296 #-------------------------------------------------------------------------
2298 2297
2299 2298 def init_payload(self):
2300 2299 self.payload_manager = PayloadManager(parent=self)
2301 2300 self.configurables.append(self.payload_manager)
2302 2301
2303 2302 #-------------------------------------------------------------------------
2304 2303 # Things related to the prefilter
2305 2304 #-------------------------------------------------------------------------
2306 2305
2307 2306 def init_prefilter(self):
2308 2307 self.prefilter_manager = PrefilterManager(shell=self, parent=self)
2309 2308 self.configurables.append(self.prefilter_manager)
2310 2309 # Ultimately this will be refactored in the new interpreter code, but
2311 2310 # for now, we should expose the main prefilter method (there's legacy
2312 2311 # code out there that may rely on this).
2313 2312 self.prefilter = self.prefilter_manager.prefilter_lines
2314 2313
2315 2314 def auto_rewrite_input(self, cmd):
2316 2315 """Print to the screen the rewritten form of the user's command.
2317 2316
2318 2317 This shows visual feedback by rewriting input lines that cause
2319 2318 automatic calling to kick in, like::
2320 2319
2321 2320 /f x
2322 2321
2323 2322 into::
2324 2323
2325 2324 ------> f(x)
2326 2325
2327 2326 after the user's input prompt. This helps the user understand that the
2328 2327 input line was transformed automatically by IPython.
2329 2328 """
2330 2329 if not self.show_rewritten_input:
2331 2330 return
2332 2331
2333 2332 # This is overridden in TerminalInteractiveShell to use fancy prompts
2334 2333 print("------> " + cmd)
2335 2334
2336 2335 #-------------------------------------------------------------------------
2337 2336 # Things related to extracting values/expressions from kernel and user_ns
2338 2337 #-------------------------------------------------------------------------
2339 2338
2340 2339 def _user_obj_error(self):
2341 2340 """return simple exception dict
2342 2341
2343 2342 for use in user_expressions
2344 2343 """
2345 2344
2346 2345 etype, evalue, tb = self._get_exc_info()
2347 2346 stb = self.InteractiveTB.get_exception_only(etype, evalue)
2348 2347
2349 2348 exc_info = {
2350 2349 u'status' : 'error',
2351 2350 u'traceback' : stb,
2352 2351 u'ename' : unicode_type(etype.__name__),
2353 2352 u'evalue' : py3compat.safe_unicode(evalue),
2354 2353 }
2355 2354
2356 2355 return exc_info
2357 2356
2358 2357 def _format_user_obj(self, obj):
2359 2358 """format a user object to display dict
2360 2359
2361 2360 for use in user_expressions
2362 2361 """
2363 2362
2364 2363 data, md = self.display_formatter.format(obj)
2365 2364 value = {
2366 2365 'status' : 'ok',
2367 2366 'data' : data,
2368 2367 'metadata' : md,
2369 2368 }
2370 2369 return value
2371 2370
2372 2371 def user_expressions(self, expressions):
2373 2372 """Evaluate a dict of expressions in the user's namespace.
2374 2373
2375 2374 Parameters
2376 2375 ----------
2377 2376 expressions : dict
2378 2377 A dict with string keys and string values. The expression values
2379 2378 should be valid Python expressions, each of which will be evaluated
2380 2379 in the user namespace.
2381 2380
2382 2381 Returns
2383 2382 -------
2384 2383 A dict, keyed like the input expressions dict, with the rich mime-typed
2385 2384 display_data of each value.
2386 2385 """
2387 2386 out = {}
2388 2387 user_ns = self.user_ns
2389 2388 global_ns = self.user_global_ns
2390 2389
2391 2390 for key, expr in iteritems(expressions):
2392 2391 try:
2393 2392 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2394 2393 except:
2395 2394 value = self._user_obj_error()
2396 2395 out[key] = value
2397 2396 return out
2398 2397
2399 2398 #-------------------------------------------------------------------------
2400 2399 # Things related to the running of code
2401 2400 #-------------------------------------------------------------------------
2402 2401
2403 2402 def ex(self, cmd):
2404 2403 """Execute a normal python statement in user namespace."""
2405 2404 with self.builtin_trap:
2406 2405 exec(cmd, self.user_global_ns, self.user_ns)
2407 2406
2408 2407 def ev(self, expr):
2409 2408 """Evaluate python expression expr in user namespace.
2410 2409
2411 2410 Returns the result of evaluation
2412 2411 """
2413 2412 with self.builtin_trap:
2414 2413 return eval(expr, self.user_global_ns, self.user_ns)
2415 2414
2416 2415 def safe_execfile(self, fname, *where, **kw):
2417 2416 """A safe version of the builtin execfile().
2418 2417
2419 2418 This version will never throw an exception, but instead print
2420 2419 helpful error messages to the screen. This only works on pure
2421 2420 Python files with the .py extension.
2422 2421
2423 2422 Parameters
2424 2423 ----------
2425 2424 fname : string
2426 2425 The name of the file to be executed.
2427 2426 where : tuple
2428 2427 One or two namespaces, passed to execfile() as (globals,locals).
2429 2428 If only one is given, it is passed as both.
2430 2429 exit_ignore : bool (False)
2431 2430 If True, then silence SystemExit for non-zero status (it is always
2432 2431 silenced for zero status, as it is so common).
2433 2432 raise_exceptions : bool (False)
2434 2433 If True raise exceptions everywhere. Meant for testing.
2435 2434 shell_futures : bool (False)
2436 2435 If True, the code will share future statements with the interactive
2437 2436 shell. It will both be affected by previous __future__ imports, and
2438 2437 any __future__ imports in the code will affect the shell. If False,
2439 2438 __future__ imports are not shared in either direction.
2440 2439
2441 2440 """
2442 2441 kw.setdefault('exit_ignore', False)
2443 2442 kw.setdefault('raise_exceptions', False)
2444 2443 kw.setdefault('shell_futures', False)
2445 2444
2446 2445 fname = os.path.abspath(os.path.expanduser(fname))
2447 2446
2448 2447 # Make sure we can open the file
2449 2448 try:
2450 2449 with open(fname):
2451 2450 pass
2452 2451 except:
2453 2452 warn('Could not open file <%s> for safe execution.' % fname)
2454 2453 return
2455 2454
2456 2455 # Find things also in current directory. This is needed to mimic the
2457 2456 # behavior of running a script from the system command line, where
2458 2457 # Python inserts the script's directory into sys.path
2459 2458 dname = os.path.dirname(fname)
2460 2459
2461 2460 with prepended_to_syspath(dname), self.builtin_trap:
2462 2461 try:
2463 2462 glob, loc = (where + (None, ))[:2]
2464 2463 py3compat.execfile(
2465 2464 fname, glob, loc,
2466 2465 self.compile if kw['shell_futures'] else None)
2467 2466 except SystemExit as status:
2468 2467 # If the call was made with 0 or None exit status (sys.exit(0)
2469 2468 # or sys.exit() ), don't bother showing a traceback, as both of
2470 2469 # these are considered normal by the OS:
2471 2470 # > python -c'import sys;sys.exit(0)'; echo $?
2472 2471 # 0
2473 2472 # > python -c'import sys;sys.exit()'; echo $?
2474 2473 # 0
2475 2474 # For other exit status, we show the exception unless
2476 2475 # explicitly silenced, but only in short form.
2477 2476 if status.code:
2478 2477 if kw['raise_exceptions']:
2479 2478 raise
2480 2479 if not kw['exit_ignore']:
2481 2480 self.showtraceback(exception_only=True)
2482 2481 except:
2483 2482 if kw['raise_exceptions']:
2484 2483 raise
2485 2484 # tb offset is 2 because we wrap execfile
2486 2485 self.showtraceback(tb_offset=2)
2487 2486
2488 2487 def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False):
2489 2488 """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.
2490 2489
2491 2490 Parameters
2492 2491 ----------
2493 2492 fname : str
2494 2493 The name of the file to execute. The filename must have a
2495 2494 .ipy or .ipynb extension.
2496 2495 shell_futures : bool (False)
2497 2496 If True, the code will share future statements with the interactive
2498 2497 shell. It will both be affected by previous __future__ imports, and
2499 2498 any __future__ imports in the code will affect the shell. If False,
2500 2499 __future__ imports are not shared in either direction.
2501 2500 raise_exceptions : bool (False)
2502 2501 If True raise exceptions everywhere. Meant for testing.
2503 2502 """
2504 2503 fname = os.path.abspath(os.path.expanduser(fname))
2505 2504
2506 2505 # Make sure we can open the file
2507 2506 try:
2508 2507 with open(fname):
2509 2508 pass
2510 2509 except:
2511 2510 warn('Could not open file <%s> for safe execution.' % fname)
2512 2511 return
2513 2512
2514 2513 # Find things also in current directory. This is needed to mimic the
2515 2514 # behavior of running a script from the system command line, where
2516 2515 # Python inserts the script's directory into sys.path
2517 2516 dname = os.path.dirname(fname)
2518 2517
2519 2518 def get_cells():
2520 2519 """generator for sequence of code blocks to run"""
2521 2520 if fname.endswith('.ipynb'):
2522 2521 from nbformat import read
2523 2522 with io_open(fname) as f:
2524 2523 nb = read(f, as_version=4)
2525 2524 if not nb.cells:
2526 2525 return
2527 2526 for cell in nb.cells:
2528 2527 if cell.cell_type == 'code':
2529 2528 yield cell.source
2530 2529 else:
2531 2530 with open(fname) as f:
2532 2531 yield f.read()
2533 2532
2534 2533 with prepended_to_syspath(dname):
2535 2534 try:
2536 2535 for cell in get_cells():
2537 2536 result = self.run_cell(cell, silent=True, shell_futures=shell_futures)
2538 2537 if raise_exceptions:
2539 2538 result.raise_error()
2540 2539 elif not result.success:
2541 2540 break
2542 2541 except:
2543 2542 if raise_exceptions:
2544 2543 raise
2545 2544 self.showtraceback()
2546 2545 warn('Unknown failure executing file: <%s>' % fname)
2547 2546
2548 2547 def safe_run_module(self, mod_name, where):
2549 2548 """A safe version of runpy.run_module().
2550 2549
2551 2550 This version will never throw an exception, but instead print
2552 2551 helpful error messages to the screen.
2553 2552
2554 2553 `SystemExit` exceptions with status code 0 or None are ignored.
2555 2554
2556 2555 Parameters
2557 2556 ----------
2558 2557 mod_name : string
2559 2558 The name of the module to be executed.
2560 2559 where : dict
2561 2560 The globals namespace.
2562 2561 """
2563 2562 try:
2564 2563 try:
2565 2564 where.update(
2566 2565 runpy.run_module(str(mod_name), run_name="__main__",
2567 2566 alter_sys=True)
2568 2567 )
2569 2568 except SystemExit as status:
2570 2569 if status.code:
2571 2570 raise
2572 2571 except:
2573 2572 self.showtraceback()
2574 2573 warn('Unknown failure executing module: <%s>' % mod_name)
2575 2574
2576 2575 def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
2577 2576 """Run a complete IPython cell.
2578 2577
2579 2578 Parameters
2580 2579 ----------
2581 2580 raw_cell : str
2582 2581 The code (including IPython code such as %magic functions) to run.
2583 2582 store_history : bool
2584 2583 If True, the raw and translated cell will be stored in IPython's
2585 2584 history. For user code calling back into IPython's machinery, this
2586 2585 should be set to False.
2587 2586 silent : bool
2588 2587 If True, avoid side-effects, such as implicit displayhooks and
2589 2588 and logging. silent=True forces store_history=False.
2590 2589 shell_futures : bool
2591 2590 If True, the code will share future statements with the interactive
2592 2591 shell. It will both be affected by previous __future__ imports, and
2593 2592 any __future__ imports in the code will affect the shell. If False,
2594 2593 __future__ imports are not shared in either direction.
2595 2594
2596 2595 Returns
2597 2596 -------
2598 2597 result : :class:`ExecutionResult`
2599 2598 """
2600 2599 result = ExecutionResult()
2601 2600
2602 2601 if (not raw_cell) or raw_cell.isspace():
2603 2602 self.last_execution_succeeded = True
2604 2603 return result
2605 2604
2606 2605 if silent:
2607 2606 store_history = False
2608 2607
2609 2608 if store_history:
2610 2609 result.execution_count = self.execution_count
2611 2610
2612 2611 def error_before_exec(value):
2613 2612 result.error_before_exec = value
2614 2613 self.last_execution_succeeded = False
2615 2614 return result
2616 2615
2617 2616 self.events.trigger('pre_execute')
2618 2617 if not silent:
2619 2618 self.events.trigger('pre_run_cell')
2620 2619
2621 2620 # If any of our input transformation (input_transformer_manager or
2622 2621 # prefilter_manager) raises an exception, we store it in this variable
2623 2622 # so that we can display the error after logging the input and storing
2624 2623 # it in the history.
2625 2624 preprocessing_exc_tuple = None
2626 2625 try:
2627 2626 # Static input transformations
2628 2627 cell = self.input_transformer_manager.transform_cell(raw_cell)
2629 2628 except SyntaxError:
2630 2629 preprocessing_exc_tuple = sys.exc_info()
2631 2630 cell = raw_cell # cell has to exist so it can be stored/logged
2632 2631 else:
2633 2632 if len(cell.splitlines()) == 1:
2634 2633 # Dynamic transformations - only applied for single line commands
2635 2634 with self.builtin_trap:
2636 2635 try:
2637 2636 # use prefilter_lines to handle trailing newlines
2638 2637 # restore trailing newline for ast.parse
2639 2638 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2640 2639 except Exception:
2641 2640 # don't allow prefilter errors to crash IPython
2642 2641 preprocessing_exc_tuple = sys.exc_info()
2643 2642
2644 2643 # Store raw and processed history
2645 2644 if store_history:
2646 2645 self.history_manager.store_inputs(self.execution_count,
2647 2646 cell, raw_cell)
2648 2647 if not silent:
2649 2648 self.logger.log(cell, raw_cell)
2650 2649
2651 2650 # Display the exception if input processing failed.
2652 2651 if preprocessing_exc_tuple is not None:
2653 2652 self.showtraceback(preprocessing_exc_tuple)
2654 2653 if store_history:
2655 2654 self.execution_count += 1
2656 2655 return error_before_exec(preprocessing_exc_tuple[2])
2657 2656
2658 2657 # Our own compiler remembers the __future__ environment. If we want to
2659 2658 # run code with a separate __future__ environment, use the default
2660 2659 # compiler
2661 2660 compiler = self.compile if shell_futures else CachingCompiler()
2662 2661
2663 2662 with self.builtin_trap:
2664 2663 cell_name = self.compile.cache(cell, self.execution_count)
2665 2664
2666 2665 with self.display_trap:
2667 2666 # Compile to bytecode
2668 2667 try:
2669 2668 code_ast = compiler.ast_parse(cell, filename=cell_name)
2670 2669 except self.custom_exceptions as e:
2671 2670 etype, value, tb = sys.exc_info()
2672 2671 self.CustomTB(etype, value, tb)
2673 2672 return error_before_exec(e)
2674 2673 except IndentationError as e:
2675 2674 self.showindentationerror()
2676 2675 if store_history:
2677 2676 self.execution_count += 1
2678 2677 return error_before_exec(e)
2679 2678 except (OverflowError, SyntaxError, ValueError, TypeError,
2680 2679 MemoryError) as e:
2681 2680 self.showsyntaxerror()
2682 2681 if store_history:
2683 2682 self.execution_count += 1
2684 2683 return error_before_exec(e)
2685 2684
2686 2685 # Apply AST transformations
2687 2686 try:
2688 2687 code_ast = self.transform_ast(code_ast)
2689 2688 except InputRejected as e:
2690 2689 self.showtraceback()
2691 2690 if store_history:
2692 2691 self.execution_count += 1
2693 2692 return error_before_exec(e)
2694 2693
2695 2694 # Give the displayhook a reference to our ExecutionResult so it
2696 2695 # can fill in the output value.
2697 2696 self.displayhook.exec_result = result
2698 2697
2699 2698 # Execute the user code
2700 2699 interactivity = "none" if silent else self.ast_node_interactivity
2701 2700 has_raised = self.run_ast_nodes(code_ast.body, cell_name,
2702 2701 interactivity=interactivity, compiler=compiler, result=result)
2703 2702
2704 2703 self.last_execution_succeeded = not has_raised
2705 2704
2706 2705 # Reset this so later displayed values do not modify the
2707 2706 # ExecutionResult
2708 2707 self.displayhook.exec_result = None
2709 2708
2710 2709 self.events.trigger('post_execute')
2711 2710 if not silent:
2712 2711 self.events.trigger('post_run_cell')
2713 2712
2714 2713 if store_history:
2715 2714 # Write output to the database. Does nothing unless
2716 2715 # history output logging is enabled.
2717 2716 self.history_manager.store_output(self.execution_count)
2718 2717 # Each cell is a *single* input, regardless of how many lines it has
2719 2718 self.execution_count += 1
2720 2719
2721 2720 return result
2722 2721
2723 2722 def transform_ast(self, node):
2724 2723 """Apply the AST transformations from self.ast_transformers
2725 2724
2726 2725 Parameters
2727 2726 ----------
2728 2727 node : ast.Node
2729 2728 The root node to be transformed. Typically called with the ast.Module
2730 2729 produced by parsing user input.
2731 2730
2732 2731 Returns
2733 2732 -------
2734 2733 An ast.Node corresponding to the node it was called with. Note that it
2735 2734 may also modify the passed object, so don't rely on references to the
2736 2735 original AST.
2737 2736 """
2738 2737 for transformer in self.ast_transformers:
2739 2738 try:
2740 2739 node = transformer.visit(node)
2741 2740 except InputRejected:
2742 2741 # User-supplied AST transformers can reject an input by raising
2743 2742 # an InputRejected. Short-circuit in this case so that we
2744 2743 # don't unregister the transform.
2745 2744 raise
2746 2745 except Exception:
2747 2746 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
2748 2747 self.ast_transformers.remove(transformer)
2749 2748
2750 2749 if self.ast_transformers:
2751 2750 ast.fix_missing_locations(node)
2752 2751 return node
2753 2752
2754 2753
2755 2754 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr',
2756 2755 compiler=compile, result=None):
2757 2756 """Run a sequence of AST nodes. The execution mode depends on the
2758 2757 interactivity parameter.
2759 2758
2760 2759 Parameters
2761 2760 ----------
2762 2761 nodelist : list
2763 2762 A sequence of AST nodes to run.
2764 2763 cell_name : str
2765 2764 Will be passed to the compiler as the filename of the cell. Typically
2766 2765 the value returned by ip.compile.cache(cell).
2767 2766 interactivity : str
2768 2767 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2769 2768 run interactively (displaying output from expressions). 'last_expr'
2770 2769 will run the last node interactively only if it is an expression (i.e.
2771 2770 expressions in loops or other blocks are not displayed. Other values
2772 2771 for this parameter will raise a ValueError.
2773 2772 compiler : callable
2774 2773 A function with the same interface as the built-in compile(), to turn
2775 2774 the AST nodes into code objects. Default is the built-in compile().
2776 2775 result : ExecutionResult, optional
2777 2776 An object to store exceptions that occur during execution.
2778 2777
2779 2778 Returns
2780 2779 -------
2781 2780 True if an exception occurred while running code, False if it finished
2782 2781 running.
2783 2782 """
2784 2783 if not nodelist:
2785 2784 return
2786 2785
2787 2786 if interactivity == 'last_expr':
2788 2787 if isinstance(nodelist[-1], ast.Expr):
2789 2788 interactivity = "last"
2790 2789 else:
2791 2790 interactivity = "none"
2792 2791
2793 2792 if interactivity == 'none':
2794 2793 to_run_exec, to_run_interactive = nodelist, []
2795 2794 elif interactivity == 'last':
2796 2795 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2797 2796 elif interactivity == 'all':
2798 2797 to_run_exec, to_run_interactive = [], nodelist
2799 2798 else:
2800 2799 raise ValueError("Interactivity was %r" % interactivity)
2801 2800
2802 2801 try:
2803 2802 for i, node in enumerate(to_run_exec):
2804 2803 mod = ast.Module([node])
2805 2804 code = compiler(mod, cell_name, "exec")
2806 2805 if self.run_code(code, result):
2807 2806 return True
2808 2807
2809 2808 for i, node in enumerate(to_run_interactive):
2810 2809 mod = ast.Interactive([node])
2811 2810 code = compiler(mod, cell_name, "single")
2812 2811 if self.run_code(code, result):
2813 2812 return True
2814 2813
2815 2814 # Flush softspace
2816 2815 if softspace(sys.stdout, 0):
2817 2816 print()
2818 2817
2819 2818 except:
2820 2819 # It's possible to have exceptions raised here, typically by
2821 2820 # compilation of odd code (such as a naked 'return' outside a
2822 2821 # function) that did parse but isn't valid. Typically the exception
2823 2822 # is a SyntaxError, but it's safest just to catch anything and show
2824 2823 # the user a traceback.
2825 2824
2826 2825 # We do only one try/except outside the loop to minimize the impact
2827 2826 # on runtime, and also because if any node in the node list is
2828 2827 # broken, we should stop execution completely.
2829 2828 if result:
2830 2829 result.error_before_exec = sys.exc_info()[1]
2831 2830 self.showtraceback()
2832 2831 return True
2833 2832
2834 2833 return False
2835 2834
2836 2835 def run_code(self, code_obj, result=None):
2837 2836 """Execute a code object.
2838 2837
2839 2838 When an exception occurs, self.showtraceback() is called to display a
2840 2839 traceback.
2841 2840
2842 2841 Parameters
2843 2842 ----------
2844 2843 code_obj : code object
2845 2844 A compiled code object, to be executed
2846 2845 result : ExecutionResult, optional
2847 2846 An object to store exceptions that occur during execution.
2848 2847
2849 2848 Returns
2850 2849 -------
2851 2850 False : successful execution.
2852 2851 True : an error occurred.
2853 2852 """
2854 2853 # Set our own excepthook in case the user code tries to call it
2855 2854 # directly, so that the IPython crash handler doesn't get triggered
2856 2855 old_excepthook, sys.excepthook = sys.excepthook, self.excepthook
2857 2856
2858 2857 # we save the original sys.excepthook in the instance, in case config
2859 2858 # code (such as magics) needs access to it.
2860 2859 self.sys_excepthook = old_excepthook
2861 2860 outflag = 1 # happens in more places, so it's easier as default
2862 2861 try:
2863 2862 try:
2864 2863 self.hooks.pre_run_code_hook()
2865 2864 #rprint('Running code', repr(code_obj)) # dbg
2866 2865 exec(code_obj, self.user_global_ns, self.user_ns)
2867 2866 finally:
2868 2867 # Reset our crash handler in place
2869 2868 sys.excepthook = old_excepthook
2870 2869 except SystemExit as e:
2871 2870 if result is not None:
2872 2871 result.error_in_exec = e
2873 2872 self.showtraceback(exception_only=True)
2874 2873 warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
2875 2874 except self.custom_exceptions:
2876 2875 etype, value, tb = sys.exc_info()
2877 2876 if result is not None:
2878 2877 result.error_in_exec = value
2879 2878 self.CustomTB(etype, value, tb)
2880 2879 except:
2881 2880 if result is not None:
2882 2881 result.error_in_exec = sys.exc_info()[1]
2883 2882 self.showtraceback()
2884 2883 else:
2885 2884 outflag = 0
2886 2885 return outflag
2887 2886
2888 2887 # For backwards compatibility
2889 2888 runcode = run_code
2890 2889
2891 2890 #-------------------------------------------------------------------------
2892 2891 # Things related to GUI support and pylab
2893 2892 #-------------------------------------------------------------------------
2894 2893
2895 2894 def enable_gui(self, gui=None):
2896 2895 raise NotImplementedError('Implement enable_gui in a subclass')
2897 2896
2898 2897 def enable_matplotlib(self, gui=None):
2899 2898 """Enable interactive matplotlib and inline figure support.
2900 2899
2901 2900 This takes the following steps:
2902 2901
2903 2902 1. select the appropriate eventloop and matplotlib backend
2904 2903 2. set up matplotlib for interactive use with that backend
2905 2904 3. configure formatters for inline figure display
2906 2905 4. enable the selected gui eventloop
2907 2906
2908 2907 Parameters
2909 2908 ----------
2910 2909 gui : optional, string
2911 2910 If given, dictates the choice of matplotlib GUI backend to use
2912 2911 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2913 2912 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2914 2913 matplotlib (as dictated by the matplotlib build-time options plus the
2915 2914 user's matplotlibrc configuration file). Note that not all backends
2916 2915 make sense in all contexts, for example a terminal ipython can't
2917 2916 display figures inline.
2918 2917 """
2919 2918 from IPython.core import pylabtools as pt
2920 2919 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
2921 2920
2922 2921 if gui != 'inline':
2923 2922 # If we have our first gui selection, store it
2924 2923 if self.pylab_gui_select is None:
2925 2924 self.pylab_gui_select = gui
2926 2925 # Otherwise if they are different
2927 2926 elif gui != self.pylab_gui_select:
2928 2927 print ('Warning: Cannot change to a different GUI toolkit: %s.'
2929 2928 ' Using %s instead.' % (gui, self.pylab_gui_select))
2930 2929 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
2931 2930
2932 2931 pt.activate_matplotlib(backend)
2933 2932 pt.configure_inline_support(self, backend)
2934 2933
2935 2934 # Now we must activate the gui pylab wants to use, and fix %run to take
2936 2935 # plot updates into account
2937 2936 self.enable_gui(gui)
2938 2937 self.magics_manager.registry['ExecutionMagics'].default_runner = \
2939 2938 pt.mpl_runner(self.safe_execfile)
2940 2939
2941 2940 return gui, backend
2942 2941
2943 2942 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
2944 2943 """Activate pylab support at runtime.
2945 2944
2946 2945 This turns on support for matplotlib, preloads into the interactive
2947 2946 namespace all of numpy and pylab, and configures IPython to correctly
2948 2947 interact with the GUI event loop. The GUI backend to be used can be
2949 2948 optionally selected with the optional ``gui`` argument.
2950 2949
2951 2950 This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
2952 2951
2953 2952 Parameters
2954 2953 ----------
2955 2954 gui : optional, string
2956 2955 If given, dictates the choice of matplotlib GUI backend to use
2957 2956 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2958 2957 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2959 2958 matplotlib (as dictated by the matplotlib build-time options plus the
2960 2959 user's matplotlibrc configuration file). Note that not all backends
2961 2960 make sense in all contexts, for example a terminal ipython can't
2962 2961 display figures inline.
2963 2962 import_all : optional, bool, default: True
2964 2963 Whether to do `from numpy import *` and `from pylab import *`
2965 2964 in addition to module imports.
2966 2965 welcome_message : deprecated
2967 2966 This argument is ignored, no welcome message will be displayed.
2968 2967 """
2969 2968 from IPython.core.pylabtools import import_pylab
2970 2969
2971 2970 gui, backend = self.enable_matplotlib(gui)
2972 2971
2973 2972 # We want to prevent the loading of pylab to pollute the user's
2974 2973 # namespace as shown by the %who* magics, so we execute the activation
2975 2974 # code in an empty namespace, and we update *both* user_ns and
2976 2975 # user_ns_hidden with this information.
2977 2976 ns = {}
2978 2977 import_pylab(ns, import_all)
2979 2978 # warn about clobbered names
2980 2979 ignored = {"__builtins__"}
2981 2980 both = set(ns).intersection(self.user_ns).difference(ignored)
2982 2981 clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
2983 2982 self.user_ns.update(ns)
2984 2983 self.user_ns_hidden.update(ns)
2985 2984 return gui, backend, clobbered
2986 2985
2987 2986 #-------------------------------------------------------------------------
2988 2987 # Utilities
2989 2988 #-------------------------------------------------------------------------
2990 2989
2991 2990 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
2992 2991 """Expand python variables in a string.
2993 2992
2994 2993 The depth argument indicates how many frames above the caller should
2995 2994 be walked to look for the local namespace where to expand variables.
2996 2995
2997 2996 The global namespace for expansion is always the user's interactive
2998 2997 namespace.
2999 2998 """
3000 2999 ns = self.user_ns.copy()
3001 3000 try:
3002 3001 frame = sys._getframe(depth+1)
3003 3002 except ValueError:
3004 3003 # This is thrown if there aren't that many frames on the stack,
3005 3004 # e.g. if a script called run_line_magic() directly.
3006 3005 pass
3007 3006 else:
3008 3007 ns.update(frame.f_locals)
3009 3008
3010 3009 try:
3011 3010 # We have to use .vformat() here, because 'self' is a valid and common
3012 3011 # name, and expanding **ns for .format() would make it collide with
3013 3012 # the 'self' argument of the method.
3014 3013 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
3015 3014 except Exception:
3016 3015 # if formatter couldn't format, just let it go untransformed
3017 3016 pass
3018 3017 return cmd
3019 3018
3020 3019 def mktempfile(self, data=None, prefix='ipython_edit_'):
3021 3020 """Make a new tempfile and return its filename.
3022 3021
3023 3022 This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp),
3024 3023 but it registers the created filename internally so ipython cleans it up
3025 3024 at exit time.
3026 3025
3027 3026 Optional inputs:
3028 3027
3029 3028 - data(None): if data is given, it gets written out to the temp file
3030 3029 immediately, and the file is closed again."""
3031 3030
3032 3031 dirname = tempfile.mkdtemp(prefix=prefix)
3033 3032 self.tempdirs.append(dirname)
3034 3033
3035 3034 handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname)
3036 3035 os.close(handle) # On Windows, there can only be one open handle on a file
3037 3036 self.tempfiles.append(filename)
3038 3037
3039 3038 if data:
3040 3039 tmp_file = open(filename,'w')
3041 3040 tmp_file.write(data)
3042 3041 tmp_file.close()
3043 3042 return filename
3044 3043
3045 3044 @undoc
3046 3045 def write(self,data):
3047 3046 """DEPRECATED: Write a string to the default output"""
3048 3047 warn('InteractiveShell.write() is deprecated, use sys.stdout instead',
3049 3048 DeprecationWarning, stacklevel=2)
3050 3049 sys.stdout.write(data)
3051 3050
3052 3051 @undoc
3053 3052 def write_err(self,data):
3054 3053 """DEPRECATED: Write a string to the default error output"""
3055 3054 warn('InteractiveShell.write_err() is deprecated, use sys.stderr instead',
3056 3055 DeprecationWarning, stacklevel=2)
3057 3056 sys.stderr.write(data)
3058 3057
3059 3058 def ask_yes_no(self, prompt, default=None, interrupt=None):
3060 3059 if self.quiet:
3061 3060 return True
3062 3061 return ask_yes_no(prompt,default,interrupt)
3063 3062
3064 3063 def show_usage(self):
3065 3064 """Show a usage message"""
3066 3065 page.page(IPython.core.usage.interactive_usage)
3067 3066
3068 3067 def extract_input_lines(self, range_str, raw=False):
3069 3068 """Return as a string a set of input history slices.
3070 3069
3071 3070 Parameters
3072 3071 ----------
3073 3072 range_str : string
3074 3073 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
3075 3074 since this function is for use by magic functions which get their
3076 3075 arguments as strings. The number before the / is the session
3077 3076 number: ~n goes n back from the current session.
3078 3077
3079 3078 raw : bool, optional
3080 3079 By default, the processed input is used. If this is true, the raw
3081 3080 input history is used instead.
3082 3081
3083 3082 Notes
3084 3083 -----
3085 3084
3086 3085 Slices can be described with two notations:
3087 3086
3088 3087 * ``N:M`` -> standard python form, means including items N...(M-1).
3089 3088 * ``N-M`` -> include items N..M (closed endpoint).
3090 3089 """
3091 3090 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
3092 3091 return "\n".join(x for _, _, x in lines)
3093 3092
3094 3093 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False):
3095 3094 """Get a code string from history, file, url, or a string or macro.
3096 3095
3097 3096 This is mainly used by magic functions.
3098 3097
3099 3098 Parameters
3100 3099 ----------
3101 3100
3102 3101 target : str
3103 3102
3104 3103 A string specifying code to retrieve. This will be tried respectively
3105 3104 as: ranges of input history (see %history for syntax), url,
3106 3105 corresponding .py file, filename, or an expression evaluating to a
3107 3106 string or Macro in the user namespace.
3108 3107
3109 3108 raw : bool
3110 3109 If true (default), retrieve raw history. Has no effect on the other
3111 3110 retrieval mechanisms.
3112 3111
3113 3112 py_only : bool (default False)
3114 3113 Only try to fetch python code, do not try alternative methods to decode file
3115 3114 if unicode fails.
3116 3115
3117 3116 Returns
3118 3117 -------
3119 3118 A string of code.
3120 3119
3121 3120 ValueError is raised if nothing is found, and TypeError if it evaluates
3122 3121 to an object of another type. In each case, .args[0] is a printable
3123 3122 message.
3124 3123 """
3125 3124 code = self.extract_input_lines(target, raw=raw) # Grab history
3126 3125 if code:
3127 3126 return code
3128 3127 try:
3129 3128 if target.startswith(('http://', 'https://')):
3130 3129 return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie)
3131 3130 except UnicodeDecodeError:
3132 3131 if not py_only :
3133 3132 # Deferred import
3134 3133 try:
3135 3134 from urllib.request import urlopen # Py3
3136 3135 except ImportError:
3137 3136 from urllib import urlopen
3138 3137 response = urlopen(target)
3139 3138 return response.read().decode('latin1')
3140 3139 raise ValueError(("'%s' seem to be unreadable.") % target)
3141 3140
3142 3141 potential_target = [target]
3143 3142 try :
3144 3143 potential_target.insert(0,get_py_filename(target))
3145 3144 except IOError:
3146 3145 pass
3147 3146
3148 3147 for tgt in potential_target :
3149 3148 if os.path.isfile(tgt): # Read file
3150 3149 try :
3151 3150 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
3152 3151 except UnicodeDecodeError :
3153 3152 if not py_only :
3154 3153 with io_open(tgt,'r', encoding='latin1') as f :
3155 3154 return f.read()
3156 3155 raise ValueError(("'%s' seem to be unreadable.") % target)
3157 3156 elif os.path.isdir(os.path.expanduser(tgt)):
3158 3157 raise ValueError("'%s' is a directory, not a regular file." % target)
3159 3158
3160 3159 if search_ns:
3161 3160 # Inspect namespace to load object source
3162 3161 object_info = self.object_inspect(target, detail_level=1)
3163 3162 if object_info['found'] and object_info['source']:
3164 3163 return object_info['source']
3165 3164
3166 3165 try: # User namespace
3167 3166 codeobj = eval(target, self.user_ns)
3168 3167 except Exception:
3169 3168 raise ValueError(("'%s' was not found in history, as a file, url, "
3170 3169 "nor in the user namespace.") % target)
3171 3170
3172 3171 if isinstance(codeobj, string_types):
3173 3172 return codeobj
3174 3173 elif isinstance(codeobj, Macro):
3175 3174 return codeobj.value
3176 3175
3177 3176 raise TypeError("%s is neither a string nor a macro." % target,
3178 3177 codeobj)
3179 3178
3180 3179 #-------------------------------------------------------------------------
3181 3180 # Things related to IPython exiting
3182 3181 #-------------------------------------------------------------------------
3183 3182 def atexit_operations(self):
3184 3183 """This will be executed at the time of exit.
3185 3184
3186 3185 Cleanup operations and saving of persistent data that is done
3187 3186 unconditionally by IPython should be performed here.
3188 3187
3189 3188 For things that may depend on startup flags or platform specifics (such
3190 3189 as having readline or not), register a separate atexit function in the
3191 3190 code that has the appropriate information, rather than trying to
3192 3191 clutter
3193 3192 """
3194 3193 # Close the history session (this stores the end time and line count)
3195 3194 # this must be *before* the tempfile cleanup, in case of temporary
3196 3195 # history db
3197 3196 self.history_manager.end_session()
3198 3197
3199 3198 # Cleanup all tempfiles and folders left around
3200 3199 for tfile in self.tempfiles:
3201 3200 try:
3202 3201 os.unlink(tfile)
3203 3202 except OSError:
3204 3203 pass
3205 3204
3206 3205 for tdir in self.tempdirs:
3207 3206 try:
3208 3207 os.rmdir(tdir)
3209 3208 except OSError:
3210 3209 pass
3211 3210
3212 3211 # Clear all user namespaces to release all references cleanly.
3213 3212 self.reset(new_session=False)
3214 3213
3215 3214 # Run user hooks
3216 3215 self.hooks.shutdown_hook()
3217 3216
3218 3217 def cleanup(self):
3219 3218 self.restore_sys_module_state()
3220 3219
3221 3220
3222 3221 # Overridden in terminal subclass to change prompts
3223 3222 def switch_doctest_mode(self, mode):
3224 3223 pass
3225 3224
3226 3225
3227 3226 class InteractiveShellABC(with_metaclass(abc.ABCMeta, object)):
3228 3227 """An abstract base class for InteractiveShell."""
3229 3228
3230 3229 InteractiveShellABC.register(InteractiveShell)
@@ -1,807 +1,806 b''
1 1 # encoding: utf-8
2 2 """Tests for the IPython tab-completion machinery."""
3 3
4 4 # Copyright (c) IPython Development Team.
5 5 # Distributed under the terms of the Modified BSD License.
6 6
7 7 import os
8 8 import sys
9 9 import unittest
10 10
11 11 from contextlib import contextmanager
12 12
13 13 import nose.tools as nt
14 14
15 15 from traitlets.config.loader import Config
16 16 from IPython import get_ipython
17 17 from IPython.core import completer
18 18 from IPython.external.decorators import knownfailureif
19 19 from IPython.utils.tempdir import TemporaryDirectory, TemporaryWorkingDirectory
20 20 from IPython.utils.generics import complete_object
21 21 from IPython.utils.py3compat import string_types, unicode_type
22 22 from IPython.testing import decorators as dec
23 23
24 24 #-----------------------------------------------------------------------------
25 25 # Test functions
26 26 #-----------------------------------------------------------------------------
27 27
28 28 @contextmanager
29 29 def greedy_completion():
30 30 ip = get_ipython()
31 31 greedy_original = ip.Completer.greedy
32 32 try:
33 33 ip.Completer.greedy = True
34 34 yield
35 35 finally:
36 36 ip.Completer.greedy = greedy_original
37 37
38 38 def test_protect_filename():
39 39 if sys.platform == 'win32':
40 40 pairs = [('abc','abc'),
41 41 (' abc','" abc"'),
42 42 ('a bc','"a bc"'),
43 43 ('a bc','"a bc"'),
44 44 (' bc','" bc"'),
45 45 ]
46 46 else:
47 47 pairs = [('abc','abc'),
48 48 (' abc',r'\ abc'),
49 49 ('a bc',r'a\ bc'),
50 50 ('a bc',r'a\ \ bc'),
51 51 (' bc',r'\ \ bc'),
52 52 # On posix, we also protect parens and other special characters.
53 53 ('a(bc',r'a\(bc'),
54 54 ('a)bc',r'a\)bc'),
55 55 ('a( )bc',r'a\(\ \)bc'),
56 56 ('a[1]bc', r'a\[1\]bc'),
57 57 ('a{1}bc', r'a\{1\}bc'),
58 58 ('a#bc', r'a\#bc'),
59 59 ('a?bc', r'a\?bc'),
60 60 ('a=bc', r'a\=bc'),
61 61 ('a\\bc', r'a\\bc'),
62 62 ('a|bc', r'a\|bc'),
63 63 ('a;bc', r'a\;bc'),
64 64 ('a:bc', r'a\:bc'),
65 65 ("a'bc", r"a\'bc"),
66 66 ('a*bc', r'a\*bc'),
67 67 ('a"bc', r'a\"bc'),
68 68 ('a^bc', r'a\^bc'),
69 69 ('a&bc', r'a\&bc'),
70 70 ]
71 71 # run the actual tests
72 72 for s1, s2 in pairs:
73 73 s1p = completer.protect_filename(s1)
74 74 nt.assert_equal(s1p, s2)
75 75
76 76
77 77 def check_line_split(splitter, test_specs):
78 78 for part1, part2, split in test_specs:
79 79 cursor_pos = len(part1)
80 80 line = part1+part2
81 81 out = splitter.split_line(line, cursor_pos)
82 82 nt.assert_equal(out, split)
83 83
84 84
85 85 def test_line_split():
86 86 """Basic line splitter test with default specs."""
87 87 sp = completer.CompletionSplitter()
88 88 # The format of the test specs is: part1, part2, expected answer. Parts 1
89 89 # and 2 are joined into the 'line' sent to the splitter, as if the cursor
90 90 # was at the end of part1. So an empty part2 represents someone hitting
91 91 # tab at the end of the line, the most common case.
92 92 t = [('run some/scrip', '', 'some/scrip'),
93 93 ('run scripts/er', 'ror.py foo', 'scripts/er'),
94 94 ('echo $HOM', '', 'HOM'),
95 95 ('print sys.pa', '', 'sys.pa'),
96 96 ('print(sys.pa', '', 'sys.pa'),
97 97 ("execfile('scripts/er", '', 'scripts/er'),
98 98 ('a[x.', '', 'x.'),
99 99 ('a[x.', 'y', 'x.'),
100 100 ('cd "some_file/', '', 'some_file/'),
101 101 ]
102 102 check_line_split(sp, t)
103 103 # Ensure splitting works OK with unicode by re-running the tests with
104 104 # all inputs turned into unicode
105 105 check_line_split(sp, [ map(unicode_type, p) for p in t] )
106 106
107 107
108 108 def test_custom_completion_error():
109 109 """Test that errors from custom attribute completers are silenced."""
110 110 ip = get_ipython()
111 111 class A(object): pass
112 112 ip.user_ns['a'] = A()
113 113
114 114 @complete_object.when_type(A)
115 115 def complete_A(a, existing_completions):
116 116 raise TypeError("this should be silenced")
117 117
118 118 ip.complete("a.")
119 119
120 120
121 121 def test_unicode_completions():
122 122 ip = get_ipython()
123 123 # Some strings that trigger different types of completion. Check them both
124 124 # in str and unicode forms
125 125 s = ['ru', '%ru', 'cd /', 'floa', 'float(x)/']
126 126 for t in s + list(map(unicode_type, s)):
127 127 # We don't need to check exact completion values (they may change
128 128 # depending on the state of the namespace, but at least no exceptions
129 129 # should be thrown and the return value should be a pair of text, list
130 130 # values.
131 131 text, matches = ip.complete(t)
132 132 nt.assert_true(isinstance(text, string_types))
133 133 nt.assert_true(isinstance(matches, list))
134 134
135 @dec.onlyif(sys.version_info[0] >= 3, 'This test only applies in Py>=3')
136 135 def test_latex_completions():
137 136 from IPython.core.latex_symbols import latex_symbols
138 137 import random
139 138 ip = get_ipython()
140 139 # Test some random unicode symbols
141 140 keys = random.sample(latex_symbols.keys(), 10)
142 141 for k in keys:
143 142 text, matches = ip.complete(k)
144 143 nt.assert_equal(len(matches),1)
145 144 nt.assert_equal(text, k)
146 145 nt.assert_equal(matches[0], latex_symbols[k])
147 146 # Test a more complex line
148 147 text, matches = ip.complete(u'print(\\alpha')
149 148 nt.assert_equals(text, u'\\alpha')
150 149 nt.assert_equals(matches[0], latex_symbols['\\alpha'])
151 150 # Test multiple matching latex symbols
152 151 text, matches = ip.complete(u'\\al')
153 152 nt.assert_in('\\alpha', matches)
154 153 nt.assert_in('\\aleph', matches)
155 154
156 155
157 156
158 157
159 158 @dec.onlyif(sys.version_info[0] >= 3, 'This test only apply on python3')
160 159 def test_back_latex_completion():
161 160 ip = get_ipython()
162 161
163 162 # do not return more than 1 matches fro \beta, only the latex one.
164 163 name, matches = ip.complete('\\Ξ²')
165 164 nt.assert_equal(len(matches), 1)
166 165 nt.assert_equal(matches[0], '\\beta')
167 166
168 167 @dec.onlyif(sys.version_info[0] >= 3, 'This test only apply on python3')
169 168 def test_back_unicode_completion():
170 169 ip = get_ipython()
171 170
172 171 name, matches = ip.complete('\\β…€')
173 172 nt.assert_equal(len(matches), 1)
174 173 nt.assert_equal(matches[0], '\\ROMAN NUMERAL FIVE')
175 174
176 175
177 176 @dec.onlyif(sys.version_info[0] >= 3, 'This test only apply on python3')
178 177 def test_forward_unicode_completion():
179 178 ip = get_ipython()
180 179
181 180 name, matches = ip.complete('\\ROMAN NUMERAL FIVE')
182 181 nt.assert_equal(len(matches), 1)
183 182 nt.assert_equal(matches[0], 'β…€')
184 183
185 184 @dec.onlyif(sys.version_info[0] >= 3, 'This test only apply on python3')
186 185 @dec.knownfailureif(sys.platform == 'win32', 'Fails if there is a C:\\j... path')
187 186 def test_no_ascii_back_completion():
188 187 ip = get_ipython()
189 188 with TemporaryWorkingDirectory(): # Avoid any filename completions
190 189 # single ascii letter that don't have yet completions
191 190 for letter in 'jJ' :
192 191 name, matches = ip.complete('\\'+letter)
193 192 nt.assert_equal(matches, [])
194 193
195 194
196 195
197 196
198 197 class CompletionSplitterTestCase(unittest.TestCase):
199 198 def setUp(self):
200 199 self.sp = completer.CompletionSplitter()
201 200
202 201 def test_delim_setting(self):
203 202 self.sp.delims = ' '
204 203 nt.assert_equal(self.sp.delims, ' ')
205 204 nt.assert_equal(self.sp._delim_expr, '[\ ]')
206 205
207 206 def test_spaces(self):
208 207 """Test with only spaces as split chars."""
209 208 self.sp.delims = ' '
210 209 t = [('foo', '', 'foo'),
211 210 ('run foo', '', 'foo'),
212 211 ('run foo', 'bar', 'foo'),
213 212 ]
214 213 check_line_split(self.sp, t)
215 214
216 215
217 216 def test_has_open_quotes1():
218 217 for s in ["'", "'''", "'hi' '"]:
219 218 nt.assert_equal(completer.has_open_quotes(s), "'")
220 219
221 220
222 221 def test_has_open_quotes2():
223 222 for s in ['"', '"""', '"hi" "']:
224 223 nt.assert_equal(completer.has_open_quotes(s), '"')
225 224
226 225
227 226 def test_has_open_quotes3():
228 227 for s in ["''", "''' '''", "'hi' 'ipython'"]:
229 228 nt.assert_false(completer.has_open_quotes(s))
230 229
231 230
232 231 def test_has_open_quotes4():
233 232 for s in ['""', '""" """', '"hi" "ipython"']:
234 233 nt.assert_false(completer.has_open_quotes(s))
235 234
236 235
237 236 @knownfailureif(sys.platform == 'win32', "abspath completions fail on Windows")
238 237 def test_abspath_file_completions():
239 238 ip = get_ipython()
240 239 with TemporaryDirectory() as tmpdir:
241 240 prefix = os.path.join(tmpdir, 'foo')
242 241 suffixes = ['1', '2']
243 242 names = [prefix+s for s in suffixes]
244 243 for n in names:
245 244 open(n, 'w').close()
246 245
247 246 # Check simple completion
248 247 c = ip.complete(prefix)[1]
249 248 nt.assert_equal(c, names)
250 249
251 250 # Now check with a function call
252 251 cmd = 'a = f("%s' % prefix
253 252 c = ip.complete(prefix, cmd)[1]
254 253 comp = [prefix+s for s in suffixes]
255 254 nt.assert_equal(c, comp)
256 255
257 256
258 257 def test_local_file_completions():
259 258 ip = get_ipython()
260 259 with TemporaryWorkingDirectory():
261 260 prefix = './foo'
262 261 suffixes = ['1', '2']
263 262 names = [prefix+s for s in suffixes]
264 263 for n in names:
265 264 open(n, 'w').close()
266 265
267 266 # Check simple completion
268 267 c = ip.complete(prefix)[1]
269 268 nt.assert_equal(c, names)
270 269
271 270 # Now check with a function call
272 271 cmd = 'a = f("%s' % prefix
273 272 c = ip.complete(prefix, cmd)[1]
274 273 comp = set(prefix+s for s in suffixes)
275 274 nt.assert_true(comp.issubset(set(c)))
276 275
277 276
278 277 def test_greedy_completions():
279 278 ip = get_ipython()
280 279 ip.ex('a=list(range(5))')
281 280 _,c = ip.complete('.',line='a[0].')
282 281 nt.assert_false('.real' in c,
283 282 "Shouldn't have completed on a[0]: %s"%c)
284 283 with greedy_completion():
285 284 def _(line, cursor_pos, expect, message):
286 285 _,c = ip.complete('.', line=line, cursor_pos=cursor_pos)
287 286 nt.assert_in(expect, c, message%c)
288 287
289 288 yield _, 'a[0].', 5, 'a[0].real', "Should have completed on a[0].: %s"
290 289 yield _, 'a[0].r', 6, 'a[0].real', "Should have completed on a[0].r: %s"
291 290
292 291 if sys.version_info > (3,4):
293 292 yield _, 'a[0].from_', 10, 'a[0].from_bytes', "Should have completed on a[0].from_: %s"
294 293
295 294
296 295
297 296 def test_omit__names():
298 297 # also happens to test IPCompleter as a configurable
299 298 ip = get_ipython()
300 299 ip._hidden_attr = 1
301 300 ip._x = {}
302 301 c = ip.Completer
303 302 ip.ex('ip=get_ipython()')
304 303 cfg = Config()
305 304 cfg.IPCompleter.omit__names = 0
306 305 c.update_config(cfg)
307 306 s,matches = c.complete('ip.')
308 307 nt.assert_in('ip.__str__', matches)
309 308 nt.assert_in('ip._hidden_attr', matches)
310 309 cfg = Config()
311 310 cfg.IPCompleter.omit__names = 1
312 311 c.update_config(cfg)
313 312 s,matches = c.complete('ip.')
314 313 nt.assert_not_in('ip.__str__', matches)
315 314 nt.assert_in('ip._hidden_attr', matches)
316 315 cfg = Config()
317 316 cfg.IPCompleter.omit__names = 2
318 317 c.update_config(cfg)
319 318 s,matches = c.complete('ip.')
320 319 nt.assert_not_in('ip.__str__', matches)
321 320 nt.assert_not_in('ip._hidden_attr', matches)
322 321 s,matches = c.complete('ip._x.')
323 322 nt.assert_in('ip._x.keys', matches)
324 323 del ip._hidden_attr
325 324
326 325
327 326 def test_limit_to__all__False_ok():
328 327 ip = get_ipython()
329 328 c = ip.Completer
330 329 ip.ex('class D: x=24')
331 330 ip.ex('d=D()')
332 331 cfg = Config()
333 332 cfg.IPCompleter.limit_to__all__ = False
334 333 c.update_config(cfg)
335 334 s, matches = c.complete('d.')
336 335 nt.assert_in('d.x', matches)
337 336
338 337
339 338 def test_get__all__entries_ok():
340 339 class A(object):
341 340 __all__ = ['x', 1]
342 341 words = completer.get__all__entries(A())
343 342 nt.assert_equal(words, ['x'])
344 343
345 344
346 345 def test_get__all__entries_no__all__ok():
347 346 class A(object):
348 347 pass
349 348 words = completer.get__all__entries(A())
350 349 nt.assert_equal(words, [])
351 350
352 351
353 352 def test_func_kw_completions():
354 353 ip = get_ipython()
355 354 c = ip.Completer
356 355 ip.ex('def myfunc(a=1,b=2): return a+b')
357 356 s, matches = c.complete(None, 'myfunc(1,b')
358 357 nt.assert_in('b=', matches)
359 358 # Simulate completing with cursor right after b (pos==10):
360 359 s, matches = c.complete(None, 'myfunc(1,b)', 10)
361 360 nt.assert_in('b=', matches)
362 361 s, matches = c.complete(None, 'myfunc(a="escaped\\")string",b')
363 362 nt.assert_in('b=', matches)
364 363 #builtin function
365 364 s, matches = c.complete(None, 'min(k, k')
366 365 nt.assert_in('key=', matches)
367 366
368 367
369 368 def test_default_arguments_from_docstring():
370 369 ip = get_ipython()
371 370 c = ip.Completer
372 371 kwd = c._default_arguments_from_docstring(
373 372 'min(iterable[, key=func]) -> value')
374 373 nt.assert_equal(kwd, ['key'])
375 374 #with cython type etc
376 375 kwd = c._default_arguments_from_docstring(
377 376 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)\n')
378 377 nt.assert_equal(kwd, ['ncall', 'resume', 'nsplit'])
379 378 #white spaces
380 379 kwd = c._default_arguments_from_docstring(
381 380 '\n Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)\n')
382 381 nt.assert_equal(kwd, ['ncall', 'resume', 'nsplit'])
383 382
384 383 def test_line_magics():
385 384 ip = get_ipython()
386 385 c = ip.Completer
387 386 s, matches = c.complete(None, 'lsmag')
388 387 nt.assert_in('%lsmagic', matches)
389 388 s, matches = c.complete(None, '%lsmag')
390 389 nt.assert_in('%lsmagic', matches)
391 390
392 391
393 392 def test_cell_magics():
394 393 from IPython.core.magic import register_cell_magic
395 394
396 395 @register_cell_magic
397 396 def _foo_cellm(line, cell):
398 397 pass
399 398
400 399 ip = get_ipython()
401 400 c = ip.Completer
402 401
403 402 s, matches = c.complete(None, '_foo_ce')
404 403 nt.assert_in('%%_foo_cellm', matches)
405 404 s, matches = c.complete(None, '%%_foo_ce')
406 405 nt.assert_in('%%_foo_cellm', matches)
407 406
408 407
409 408 def test_line_cell_magics():
410 409 from IPython.core.magic import register_line_cell_magic
411 410
412 411 @register_line_cell_magic
413 412 def _bar_cellm(line, cell):
414 413 pass
415 414
416 415 ip = get_ipython()
417 416 c = ip.Completer
418 417
419 418 # The policy here is trickier, see comments in completion code. The
420 419 # returned values depend on whether the user passes %% or not explicitly,
421 420 # and this will show a difference if the same name is both a line and cell
422 421 # magic.
423 422 s, matches = c.complete(None, '_bar_ce')
424 423 nt.assert_in('%_bar_cellm', matches)
425 424 nt.assert_in('%%_bar_cellm', matches)
426 425 s, matches = c.complete(None, '%_bar_ce')
427 426 nt.assert_in('%_bar_cellm', matches)
428 427 nt.assert_in('%%_bar_cellm', matches)
429 428 s, matches = c.complete(None, '%%_bar_ce')
430 429 nt.assert_not_in('%_bar_cellm', matches)
431 430 nt.assert_in('%%_bar_cellm', matches)
432 431
433 432
434 433 def test_magic_completion_order():
435 434
436 435 ip = get_ipython()
437 436 c = ip.Completer
438 437
439 438 # Test ordering of magics and non-magics with the same name
440 439 # We want the non-magic first
441 440
442 441 # Before importing matplotlib, there should only be one option:
443 442
444 443 text, matches = c.complete('mat')
445 444 nt.assert_equal(matches, ["%matplotlib"])
446 445
447 446
448 447 ip.run_cell("matplotlib = 1") # introduce name into namespace
449 448
450 449 # After the import, there should be two options, ordered like this:
451 450 text, matches = c.complete('mat')
452 451 nt.assert_equal(matches, ["matplotlib", "%matplotlib"])
453 452
454 453
455 454 ip.run_cell("timeit = 1") # define a user variable called 'timeit'
456 455
457 456 # Order of user variable and line and cell magics with same name:
458 457 text, matches = c.complete('timeit')
459 458 nt.assert_equal(matches, ["timeit", "%timeit","%%timeit"])
460 459
461 460
462 461 def test_dict_key_completion_string():
463 462 """Test dictionary key completion for string keys"""
464 463 ip = get_ipython()
465 464 complete = ip.Completer.complete
466 465
467 466 ip.user_ns['d'] = {'abc': None}
468 467
469 468 # check completion at different stages
470 469 _, matches = complete(line_buffer="d[")
471 470 nt.assert_in("'abc'", matches)
472 471 nt.assert_not_in("'abc']", matches)
473 472
474 473 _, matches = complete(line_buffer="d['")
475 474 nt.assert_in("abc", matches)
476 475 nt.assert_not_in("abc']", matches)
477 476
478 477 _, matches = complete(line_buffer="d['a")
479 478 nt.assert_in("abc", matches)
480 479 nt.assert_not_in("abc']", matches)
481 480
482 481 # check use of different quoting
483 482 _, matches = complete(line_buffer="d[\"")
484 483 nt.assert_in("abc", matches)
485 484 nt.assert_not_in('abc\"]', matches)
486 485
487 486 _, matches = complete(line_buffer="d[\"a")
488 487 nt.assert_in("abc", matches)
489 488 nt.assert_not_in('abc\"]', matches)
490 489
491 490 # check sensitivity to following context
492 491 _, matches = complete(line_buffer="d[]", cursor_pos=2)
493 492 nt.assert_in("'abc'", matches)
494 493
495 494 _, matches = complete(line_buffer="d['']", cursor_pos=3)
496 495 nt.assert_in("abc", matches)
497 496 nt.assert_not_in("abc'", matches)
498 497 nt.assert_not_in("abc']", matches)
499 498
500 499 # check multiple solutions are correctly returned and that noise is not
501 500 ip.user_ns['d'] = {'abc': None, 'abd': None, 'bad': None, object(): None,
502 501 5: None}
503 502
504 503 _, matches = complete(line_buffer="d['a")
505 504 nt.assert_in("abc", matches)
506 505 nt.assert_in("abd", matches)
507 506 nt.assert_not_in("bad", matches)
508 507 assert not any(m.endswith((']', '"', "'")) for m in matches), matches
509 508
510 509 # check escaping and whitespace
511 510 ip.user_ns['d'] = {'a\nb': None, 'a\'b': None, 'a"b': None, 'a word': None}
512 511 _, matches = complete(line_buffer="d['a")
513 512 nt.assert_in("a\\nb", matches)
514 513 nt.assert_in("a\\'b", matches)
515 514 nt.assert_in("a\"b", matches)
516 515 nt.assert_in("a word", matches)
517 516 assert not any(m.endswith((']', '"', "'")) for m in matches), matches
518 517
519 518 # - can complete on non-initial word of the string
520 519 _, matches = complete(line_buffer="d['a w")
521 520 nt.assert_in("word", matches)
522 521
523 522 # - understands quote escaping
524 523 _, matches = complete(line_buffer="d['a\\'")
525 524 nt.assert_in("b", matches)
526 525
527 526 # - default quoting should work like repr
528 527 _, matches = complete(line_buffer="d[")
529 528 nt.assert_in("\"a'b\"", matches)
530 529
531 530 # - when opening quote with ", possible to match with unescaped apostrophe
532 531 _, matches = complete(line_buffer="d[\"a'")
533 532 nt.assert_in("b", matches)
534 533
535 534 # need to not split at delims that readline won't split at
536 535 if '-' not in ip.Completer.splitter.delims:
537 536 ip.user_ns['d'] = {'before-after': None}
538 537 _, matches = complete(line_buffer="d['before-af")
539 538 nt.assert_in('before-after', matches)
540 539
541 540 def test_dict_key_completion_contexts():
542 541 """Test expression contexts in which dict key completion occurs"""
543 542 ip = get_ipython()
544 543 complete = ip.Completer.complete
545 544 d = {'abc': None}
546 545 ip.user_ns['d'] = d
547 546
548 547 class C:
549 548 data = d
550 549 ip.user_ns['C'] = C
551 550 ip.user_ns['get'] = lambda: d
552 551
553 552 def assert_no_completion(**kwargs):
554 553 _, matches = complete(**kwargs)
555 554 nt.assert_not_in('abc', matches)
556 555 nt.assert_not_in('abc\'', matches)
557 556 nt.assert_not_in('abc\']', matches)
558 557 nt.assert_not_in('\'abc\'', matches)
559 558 nt.assert_not_in('\'abc\']', matches)
560 559
561 560 def assert_completion(**kwargs):
562 561 _, matches = complete(**kwargs)
563 562 nt.assert_in("'abc'", matches)
564 563 nt.assert_not_in("'abc']", matches)
565 564
566 565 # no completion after string closed, even if reopened
567 566 assert_no_completion(line_buffer="d['a'")
568 567 assert_no_completion(line_buffer="d[\"a\"")
569 568 assert_no_completion(line_buffer="d['a' + ")
570 569 assert_no_completion(line_buffer="d['a' + '")
571 570
572 571 # completion in non-trivial expressions
573 572 assert_completion(line_buffer="+ d[")
574 573 assert_completion(line_buffer="(d[")
575 574 assert_completion(line_buffer="C.data[")
576 575
577 576 # greedy flag
578 577 def assert_completion(**kwargs):
579 578 _, matches = complete(**kwargs)
580 579 nt.assert_in("get()['abc']", matches)
581 580
582 581 assert_no_completion(line_buffer="get()[")
583 582 with greedy_completion():
584 583 assert_completion(line_buffer="get()[")
585 584 assert_completion(line_buffer="get()['")
586 585 assert_completion(line_buffer="get()['a")
587 586 assert_completion(line_buffer="get()['ab")
588 587 assert_completion(line_buffer="get()['abc")
589 588
590 589
591 590
592 591 @dec.onlyif(sys.version_info[0] >= 3, 'This test only applies in Py>=3')
593 592 def test_dict_key_completion_bytes():
594 593 """Test handling of bytes in dict key completion"""
595 594 ip = get_ipython()
596 595 complete = ip.Completer.complete
597 596
598 597 ip.user_ns['d'] = {'abc': None, b'abd': None}
599 598
600 599 _, matches = complete(line_buffer="d[")
601 600 nt.assert_in("'abc'", matches)
602 601 nt.assert_in("b'abd'", matches)
603 602
604 603 if False: # not currently implemented
605 604 _, matches = complete(line_buffer="d[b")
606 605 nt.assert_in("b'abd'", matches)
607 606 nt.assert_not_in("b'abc'", matches)
608 607
609 608 _, matches = complete(line_buffer="d[b'")
610 609 nt.assert_in("abd", matches)
611 610 nt.assert_not_in("abc", matches)
612 611
613 612 _, matches = complete(line_buffer="d[B'")
614 613 nt.assert_in("abd", matches)
615 614 nt.assert_not_in("abc", matches)
616 615
617 616 _, matches = complete(line_buffer="d['")
618 617 nt.assert_in("abc", matches)
619 618 nt.assert_not_in("abd", matches)
620 619
621 620
622 621 @dec.onlyif(sys.version_info[0] < 3, 'This test only applies in Py<3')
623 622 def test_dict_key_completion_unicode_py2():
624 623 """Test handling of unicode in dict key completion"""
625 624 ip = get_ipython()
626 625 complete = ip.Completer.complete
627 626
628 627 ip.user_ns['d'] = {u'abc': None,
629 628 u'a\u05d0b': None}
630 629
631 630 _, matches = complete(line_buffer="d[")
632 631 nt.assert_in("u'abc'", matches)
633 632 nt.assert_in("u'a\\u05d0b'", matches)
634 633
635 634 _, matches = complete(line_buffer="d['a")
636 635 nt.assert_in("abc", matches)
637 636 nt.assert_not_in("a\\u05d0b", matches)
638 637
639 638 _, matches = complete(line_buffer="d[u'a")
640 639 nt.assert_in("abc", matches)
641 640 nt.assert_in("a\\u05d0b", matches)
642 641
643 642 _, matches = complete(line_buffer="d[U'a")
644 643 nt.assert_in("abc", matches)
645 644 nt.assert_in("a\\u05d0b", matches)
646 645
647 646 # query using escape
648 647 if sys.platform != 'win32':
649 648 # Known failure on Windows
650 649 _, matches = complete(line_buffer=u"d[u'a\\u05d0")
651 650 nt.assert_in("u05d0b", matches) # tokenized after \\
652 651
653 652 # query using character
654 653 _, matches = complete(line_buffer=u"d[u'a\u05d0")
655 654 nt.assert_in(u"a\u05d0b", matches)
656 655
657 656 with greedy_completion():
658 657 _, matches = complete(line_buffer="d[")
659 658 nt.assert_in("d[u'abc']", matches)
660 659 nt.assert_in("d[u'a\\u05d0b']", matches)
661 660
662 661 _, matches = complete(line_buffer="d['a")
663 662 nt.assert_in("d['abc']", matches)
664 663 nt.assert_not_in("d[u'a\\u05d0b']", matches)
665 664
666 665 _, matches = complete(line_buffer="d[u'a")
667 666 nt.assert_in("d[u'abc']", matches)
668 667 nt.assert_in("d[u'a\\u05d0b']", matches)
669 668
670 669 _, matches = complete(line_buffer="d[U'a")
671 670 nt.assert_in("d[U'abc']", matches)
672 671 nt.assert_in("d[U'a\\u05d0b']", matches)
673 672
674 673 # query using escape
675 674 _, matches = complete(line_buffer=u"d[u'a\\u05d0")
676 675 nt.assert_in("d[u'a\\u05d0b']", matches) # tokenized after \\
677 676
678 677 # query using character
679 678 _, matches = complete(line_buffer=u"d[u'a\u05d0")
680 679 nt.assert_in(u"d[u'a\u05d0b']", matches)
681 680
682 681
683 682 @dec.onlyif(sys.version_info[0] >= 3, 'This test only applies in Py>=3')
684 683 def test_dict_key_completion_unicode_py3():
685 684 """Test handling of unicode in dict key completion"""
686 685 ip = get_ipython()
687 686 complete = ip.Completer.complete
688 687
689 688 ip.user_ns['d'] = {u'a\u05d0': None}
690 689
691 690 # query using escape
692 691 if sys.platform != 'win32':
693 692 # Known failure on Windows
694 693 _, matches = complete(line_buffer="d['a\\u05d0")
695 694 nt.assert_in("u05d0", matches) # tokenized after \\
696 695
697 696 # query using character
698 697 _, matches = complete(line_buffer="d['a\u05d0")
699 698 nt.assert_in(u"a\u05d0", matches)
700 699
701 700 with greedy_completion():
702 701 # query using escape
703 702 _, matches = complete(line_buffer="d['a\\u05d0")
704 703 nt.assert_in("d['a\\u05d0']", matches) # tokenized after \\
705 704
706 705 # query using character
707 706 _, matches = complete(line_buffer="d['a\u05d0")
708 707 nt.assert_in(u"d['a\u05d0']", matches)
709 708
710 709
711 710
712 711 @dec.skip_without('numpy')
713 712 def test_struct_array_key_completion():
714 713 """Test dict key completion applies to numpy struct arrays"""
715 714 import numpy
716 715 ip = get_ipython()
717 716 complete = ip.Completer.complete
718 717 ip.user_ns['d'] = numpy.array([], dtype=[('hello', 'f'), ('world', 'f')])
719 718 _, matches = complete(line_buffer="d['")
720 719 nt.assert_in("hello", matches)
721 720 nt.assert_in("world", matches)
722 721 # complete on the numpy struct itself
723 722 dt = numpy.dtype([('my_head', [('my_dt', '>u4'), ('my_df', '>u4')]),
724 723 ('my_data', '>f4', 5)])
725 724 x = numpy.zeros(2, dtype=dt)
726 725 ip.user_ns['d'] = x[1]
727 726 _, matches = complete(line_buffer="d['")
728 727 nt.assert_in("my_head", matches)
729 728 nt.assert_in("my_data", matches)
730 729 # complete on a nested level
731 730 with greedy_completion():
732 731 ip.user_ns['d'] = numpy.zeros(2, dtype=dt)
733 732 _, matches = complete(line_buffer="d[1]['my_head']['")
734 733 nt.assert_true(any(["my_dt" in m for m in matches]))
735 734 nt.assert_true(any(["my_df" in m for m in matches]))
736 735
737 736
738 737 @dec.skip_without('pandas')
739 738 def test_dataframe_key_completion():
740 739 """Test dict key completion applies to pandas DataFrames"""
741 740 import pandas
742 741 ip = get_ipython()
743 742 complete = ip.Completer.complete
744 743 ip.user_ns['d'] = pandas.DataFrame({'hello': [1], 'world': [2]})
745 744 _, matches = complete(line_buffer="d['")
746 745 nt.assert_in("hello", matches)
747 746 nt.assert_in("world", matches)
748 747
749 748
750 749 def test_dict_key_completion_invalids():
751 750 """Smoke test cases dict key completion can't handle"""
752 751 ip = get_ipython()
753 752 complete = ip.Completer.complete
754 753
755 754 ip.user_ns['no_getitem'] = None
756 755 ip.user_ns['no_keys'] = []
757 756 ip.user_ns['cant_call_keys'] = dict
758 757 ip.user_ns['empty'] = {}
759 758 ip.user_ns['d'] = {'abc': 5}
760 759
761 760 _, matches = complete(line_buffer="no_getitem['")
762 761 _, matches = complete(line_buffer="no_keys['")
763 762 _, matches = complete(line_buffer="cant_call_keys['")
764 763 _, matches = complete(line_buffer="empty['")
765 764 _, matches = complete(line_buffer="name_error['")
766 765 _, matches = complete(line_buffer="d['\\") # incomplete escape
767 766
768 767 class KeyCompletable(object):
769 768 def __init__(self, things=()):
770 769 self.things = things
771 770
772 771 def _ipython_key_completions_(self):
773 772 return list(self.things)
774 773
775 774 def test_object_key_completion():
776 775 ip = get_ipython()
777 776 ip.user_ns['key_completable'] = KeyCompletable(['qwerty', 'qwick'])
778 777
779 778 _, matches = ip.Completer.complete(line_buffer="key_completable['qw")
780 779 nt.assert_in('qwerty', matches)
781 780 nt.assert_in('qwick', matches)
782 781
783 782
784 783 def test_aimport_module_completer():
785 784 ip = get_ipython()
786 785 _, matches = ip.complete('i', '%aimport i')
787 786 nt.assert_in('io', matches)
788 787 nt.assert_not_in('int', matches)
789 788
790 789 def test_nested_import_module_completer():
791 790 ip = get_ipython()
792 791 _, matches = ip.complete(None, 'import IPython.co', 17)
793 792 nt.assert_in('IPython.core', matches)
794 793 nt.assert_not_in('import IPython.core', matches)
795 794 nt.assert_not_in('IPython.display', matches)
796 795
797 796 def test_import_module_completer():
798 797 ip = get_ipython()
799 798 _, matches = ip.complete('i', 'import i')
800 799 nt.assert_in('io', matches)
801 800 nt.assert_not_in('int', matches)
802 801
803 802 def test_from_module_completer():
804 803 ip = get_ipython()
805 804 _, matches = ip.complete('B', 'from io import B', 16)
806 805 nt.assert_in('BytesIO', matches)
807 806 nt.assert_not_in('BaseException', matches)
@@ -1,452 +1,456 b''
1 1 """Tests for the object inspection functionality.
2 2 """
3 3
4 4 # Copyright (c) IPython Development Team.
5 5 # Distributed under the terms of the Modified BSD License.
6 6
7 7 from __future__ import print_function
8 8
9 9 import os
10 10 import re
11 11 import sys
12 12
13 13 import nose.tools as nt
14 14
15 15 from .. import oinspect
16 16 from IPython.core.magic import (Magics, magics_class, line_magic,
17 17 cell_magic, line_cell_magic,
18 18 register_line_magic, register_cell_magic,
19 19 register_line_cell_magic)
20 20 from decorator import decorator
21 21 from IPython.testing.decorators import skipif
22 22 from IPython.testing.tools import AssertPrints
23 23 from IPython.utils.path import compress_user
24 24 from IPython.utils import py3compat
25 25 from IPython.utils.signatures import Signature, Parameter
26 26
27 27
28 28 #-----------------------------------------------------------------------------
29 29 # Globals and constants
30 30 #-----------------------------------------------------------------------------
31 31
32 32 inspector = oinspect.Inspector()
33 33 ip = get_ipython()
34 34
35 35 #-----------------------------------------------------------------------------
36 36 # Local utilities
37 37 #-----------------------------------------------------------------------------
38 38
39 39 # WARNING: since this test checks the line number where a function is
40 40 # defined, if any code is inserted above, the following line will need to be
41 41 # updated. Do NOT insert any whitespace between the next line and the function
42 42 # definition below.
43 43 THIS_LINE_NUMBER = 43 # Put here the actual number of this line
44 def test_find_source_lines():
45 nt.assert_equal(oinspect.find_source_lines(test_find_source_lines),
46 THIS_LINE_NUMBER+1)
44
45 from unittest import TestCase
46
47 class Test(TestCase):
48
49 def test_find_source_lines(self):
50 self.assertEqual(oinspect.find_source_lines(Test.test_find_source_lines),
51 THIS_LINE_NUMBER+6)
47 52
48 53
49 54 # A couple of utilities to ensure these tests work the same from a source or a
50 55 # binary install
51 56 def pyfile(fname):
52 57 return os.path.normcase(re.sub('.py[co]$', '.py', fname))
53 58
54 59
55 60 def match_pyfiles(f1, f2):
56 61 nt.assert_equal(pyfile(f1), pyfile(f2))
57 62
58 63
59 64 def test_find_file():
60 65 match_pyfiles(oinspect.find_file(test_find_file), os.path.abspath(__file__))
61 66
62 67
63 68 def test_find_file_decorated1():
64 69
65 70 @decorator
66 71 def noop1(f):
67 72 def wrapper():
68 73 return f(*a, **kw)
69 74 return wrapper
70 75
71 76 @noop1
72 77 def f(x):
73 78 "My docstring"
74 79
75 80 match_pyfiles(oinspect.find_file(f), os.path.abspath(__file__))
76 81 nt.assert_equal(f.__doc__, "My docstring")
77 82
78 83
79 84 def test_find_file_decorated2():
80 85
81 86 @decorator
82 87 def noop2(f, *a, **kw):
83 88 return f(*a, **kw)
84 89
85 90 @noop2
86 91 @noop2
87 92 @noop2
88 93 def f(x):
89 94 "My docstring 2"
90 95
91 96 match_pyfiles(oinspect.find_file(f), os.path.abspath(__file__))
92 97 nt.assert_equal(f.__doc__, "My docstring 2")
93 98
94 99
95 100 def test_find_file_magic():
96 101 run = ip.find_line_magic('run')
97 102 nt.assert_not_equal(oinspect.find_file(run), None)
98 103
99 104
100 105 # A few generic objects we can then inspect in the tests below
101 106
102 107 class Call(object):
103 108 """This is the class docstring."""
104 109
105 110 def __init__(self, x, y=1):
106 111 """This is the constructor docstring."""
107 112
108 113 def __call__(self, *a, **kw):
109 114 """This is the call docstring."""
110 115
111 116 def method(self, x, z=2):
112 117 """Some method's docstring"""
113 118
114 119 class HasSignature(object):
115 120 """This is the class docstring."""
116 121 __signature__ = Signature([Parameter('test', Parameter.POSITIONAL_OR_KEYWORD)])
117 122
118 123 def __init__(self, *args):
119 124 """This is the init docstring"""
120 125
121 126
122 127 class SimpleClass(object):
123 128 def method(self, x, z=2):
124 129 """Some method's docstring"""
125 130
126 131
127 132 class OldStyle:
128 133 """An old-style class for testing."""
129 134 pass
130 135
131 136
132 137 def f(x, y=2, *a, **kw):
133 138 """A simple function."""
134 139
135 140
136 141 def g(y, z=3, *a, **kw):
137 142 pass # no docstring
138 143
139 144
140 145 @register_line_magic
141 146 def lmagic(line):
142 147 "A line magic"
143 148
144 149
145 150 @register_cell_magic
146 151 def cmagic(line, cell):
147 152 "A cell magic"
148 153
149 154
150 155 @register_line_cell_magic
151 156 def lcmagic(line, cell=None):
152 157 "A line/cell magic"
153 158
154 159
155 160 @magics_class
156 161 class SimpleMagics(Magics):
157 162 @line_magic
158 163 def Clmagic(self, cline):
159 164 "A class-based line magic"
160 165
161 166 @cell_magic
162 167 def Ccmagic(self, cline, ccell):
163 168 "A class-based cell magic"
164 169
165 170 @line_cell_magic
166 171 def Clcmagic(self, cline, ccell=None):
167 172 "A class-based line/cell magic"
168 173
169 174
170 175 class Awkward(object):
171 176 def __getattr__(self, name):
172 177 raise Exception(name)
173 178
174 179 class NoBoolCall:
175 180 """
176 181 callable with `__bool__` raising should still be inspect-able.
177 182 """
178 183
179 184 def __call__(self):
180 185 """does nothing"""
181 186 pass
182 187
183 188 def __bool__(self):
184 189 """just raise NotImplemented"""
185 190 raise NotImplementedError('Must be implemented')
186 191
187 192
188 193 class SerialLiar(object):
189 194 """Attribute accesses always get another copy of the same class.
190 195
191 196 unittest.mock.call does something similar, but it's not ideal for testing
192 197 as the failure mode is to eat all your RAM. This gives up after 10k levels.
193 198 """
194 199 def __init__(self, max_fibbing_twig, lies_told=0):
195 200 if lies_told > 10000:
196 201 raise RuntimeError('Nose too long, honesty is the best policy')
197 202 self.max_fibbing_twig = max_fibbing_twig
198 203 self.lies_told = lies_told
199 204 max_fibbing_twig[0] = max(max_fibbing_twig[0], lies_told)
200 205
201 206 def __getattr__(self, item):
202 207 return SerialLiar(self.max_fibbing_twig, self.lies_told + 1)
203 208
204 209
205 210 def check_calltip(obj, name, call, docstring):
206 211 """Generic check pattern all calltip tests will use"""
207 212 info = inspector.info(obj, name)
208 213 call_line, ds = oinspect.call_tip(info)
209 214 nt.assert_equal(call_line, call)
210 215 nt.assert_equal(ds, docstring)
211 216
212 217 #-----------------------------------------------------------------------------
213 218 # Tests
214 219 #-----------------------------------------------------------------------------
215 220
216 221 def test_calltip_class():
217 222 check_calltip(Call, 'Call', 'Call(x, y=1)', Call.__init__.__doc__)
218 223
219 224
220 225 def test_calltip_instance():
221 226 c = Call(1)
222 227 check_calltip(c, 'c', 'c(*a, **kw)', c.__call__.__doc__)
223 228
224 229
225 230 def test_calltip_method():
226 231 c = Call(1)
227 232 check_calltip(c.method, 'c.method', 'c.method(x, z=2)', c.method.__doc__)
228 233
229 234
230 235 def test_calltip_function():
231 236 check_calltip(f, 'f', 'f(x, y=2, *a, **kw)', f.__doc__)
232 237
233 238
234 239 def test_calltip_function2():
235 240 check_calltip(g, 'g', 'g(y, z=3, *a, **kw)', '<no docstring>')
236 241
237 242
238 243 @skipif(sys.version_info >= (3, 5))
239 244 def test_calltip_builtin():
240 245 check_calltip(sum, 'sum', None, sum.__doc__)
241 246
242 247
243 248 def test_calltip_line_magic():
244 249 check_calltip(lmagic, 'lmagic', 'lmagic(line)', "A line magic")
245 250
246 251
247 252 def test_calltip_cell_magic():
248 253 check_calltip(cmagic, 'cmagic', 'cmagic(line, cell)', "A cell magic")
249 254
250 255
251 256 def test_calltip_line_cell_magic():
252 257 check_calltip(lcmagic, 'lcmagic', 'lcmagic(line, cell=None)',
253 258 "A line/cell magic")
254 259
255 260
256 261 def test_class_magics():
257 262 cm = SimpleMagics(ip)
258 263 ip.register_magics(cm)
259 264 check_calltip(cm.Clmagic, 'Clmagic', 'Clmagic(cline)',
260 265 "A class-based line magic")
261 266 check_calltip(cm.Ccmagic, 'Ccmagic', 'Ccmagic(cline, ccell)',
262 267 "A class-based cell magic")
263 268 check_calltip(cm.Clcmagic, 'Clcmagic', 'Clcmagic(cline, ccell=None)',
264 269 "A class-based line/cell magic")
265 270
266 271
267 272 def test_info():
268 273 "Check that Inspector.info fills out various fields as expected."
269 274 i = inspector.info(Call, oname='Call')
270 275 nt.assert_equal(i['type_name'], 'type')
271 276 expted_class = str(type(type)) # <class 'type'> (Python 3) or <type 'type'>
272 277 nt.assert_equal(i['base_class'], expted_class)
273 278 if sys.version_info > (3,):
274 279 nt.assert_regex(i['string_form'], "<class 'IPython.core.tests.test_oinspect.Call'( at 0x[0-9a-f]{1,9})?>")
275 280 fname = __file__
276 281 if fname.endswith(".pyc"):
277 282 fname = fname[:-1]
278 283 # case-insensitive comparison needed on some filesystems
279 284 # e.g. Windows:
280 285 nt.assert_equal(i['file'].lower(), compress_user(fname).lower())
281 286 nt.assert_equal(i['definition'], None)
282 287 nt.assert_equal(i['docstring'], Call.__doc__)
283 288 nt.assert_equal(i['source'], None)
284 289 nt.assert_true(i['isclass'])
285 290 _self_py2 = '' if py3compat.PY3 else 'self, '
286 291 nt.assert_equal(i['init_definition'], "Call(%sx, y=1)" % _self_py2)
287 292 nt.assert_equal(i['init_docstring'], Call.__init__.__doc__)
288 293
289 294 i = inspector.info(Call, detail_level=1)
290 295 nt.assert_not_equal(i['source'], None)
291 296 nt.assert_equal(i['docstring'], None)
292 297
293 298 c = Call(1)
294 299 c.__doc__ = "Modified instance docstring"
295 300 i = inspector.info(c)
296 301 nt.assert_equal(i['type_name'], 'Call')
297 302 nt.assert_equal(i['docstring'], "Modified instance docstring")
298 303 nt.assert_equal(i['class_docstring'], Call.__doc__)
299 304 nt.assert_equal(i['init_docstring'], Call.__init__.__doc__)
300 305 nt.assert_equal(i['call_docstring'], Call.__call__.__doc__)
301 306
302 307 # Test old-style classes, which for example may not have an __init__ method.
303 308 if not py3compat.PY3:
304 309 i = inspector.info(OldStyle)
305 310 nt.assert_equal(i['type_name'], 'classobj')
306 311
307 312 i = inspector.info(OldStyle())
308 313 nt.assert_equal(i['type_name'], 'instance')
309 314 nt.assert_equal(i['docstring'], OldStyle.__doc__)
310 315
311 316 def test_class_signature():
312 317 info = inspector.info(HasSignature, 'HasSignature')
313 318 nt.assert_equal(info['init_definition'], "HasSignature(test)")
314 319 nt.assert_equal(info['init_docstring'], HasSignature.__init__.__doc__)
315 320
316 321 def test_info_awkward():
317 322 # Just test that this doesn't throw an error.
318 323 inspector.info(Awkward())
319 324
320 325 def test_bool_raise():
321 326 inspector.info(NoBoolCall())
322 327
323 328 def test_info_serialliar():
324 329 fib_tracker = [0]
325 i = inspector.info(SerialLiar(fib_tracker))
330 inspector.info(SerialLiar(fib_tracker))
326 331
327 332 # Nested attribute access should be cut off at 100 levels deep to avoid
328 333 # infinite loops: https://github.com/ipython/ipython/issues/9122
329 334 nt.assert_less(fib_tracker[0], 9000)
330 335
331 336 def test_calldef_none():
332 337 # We should ignore __call__ for all of these.
333 338 for obj in [f, SimpleClass().method, any, str.upper]:
334 339 print(obj)
335 340 i = inspector.info(obj)
336 341 nt.assert_is(i['call_def'], None)
337 342
338 if py3compat.PY3:
339 exec("def f_kwarg(pos, *, kwonly): pass")
343 def f_kwarg(pos, *, kwonly):
344 pass
340 345
341 @skipif(not py3compat.PY3)
342 346 def test_definition_kwonlyargs():
343 347 i = inspector.info(f_kwarg, oname='f_kwarg') # analysis:ignore
344 348 nt.assert_equal(i['definition'], "f_kwarg(pos, *, kwonly)")
345 349
346 350 def test_getdoc():
347 351 class A(object):
348 352 """standard docstring"""
349 353 pass
350 354
351 355 class B(object):
352 356 """standard docstring"""
353 357 def getdoc(self):
354 358 return "custom docstring"
355 359
356 360 class C(object):
357 361 """standard docstring"""
358 362 def getdoc(self):
359 363 return None
360 364
361 365 a = A()
362 366 b = B()
363 367 c = C()
364 368
365 369 nt.assert_equal(oinspect.getdoc(a), "standard docstring")
366 370 nt.assert_equal(oinspect.getdoc(b), "custom docstring")
367 371 nt.assert_equal(oinspect.getdoc(c), "standard docstring")
368 372
369 373
370 374 def test_empty_property_has_no_source():
371 375 i = inspector.info(property(), detail_level=1)
372 376 nt.assert_is(i['source'], None)
373 377
374 378
375 379 def test_property_sources():
376 380 import zlib
377 381
378 382 class A(object):
379 383 @property
380 384 def foo(self):
381 385 return 'bar'
382 386
383 387 foo = foo.setter(lambda self, v: setattr(self, 'bar', v))
384 388
385 389 id = property(id)
386 390 compress = property(zlib.compress)
387 391
388 392 i = inspector.info(A.foo, detail_level=1)
389 393 nt.assert_in('def foo(self):', i['source'])
390 394 nt.assert_in('lambda self, v:', i['source'])
391 395
392 396 i = inspector.info(A.id, detail_level=1)
393 397 nt.assert_in('fget = <function id>', i['source'])
394 398
395 399 i = inspector.info(A.compress, detail_level=1)
396 400 nt.assert_in('fget = <function zlib.compress>', i['source'])
397 401
398 402
399 403 def test_property_docstring_is_in_info_for_detail_level_0():
400 404 class A(object):
401 405 @property
402 406 def foobar(self):
403 407 """This is `foobar` property."""
404 408 pass
405 409
406 410 ip.user_ns['a_obj'] = A()
407 411 nt.assert_equals(
408 412 'This is `foobar` property.',
409 413 ip.object_inspect('a_obj.foobar', detail_level=0)['docstring'])
410 414
411 415 ip.user_ns['a_cls'] = A
412 416 nt.assert_equals(
413 417 'This is `foobar` property.',
414 418 ip.object_inspect('a_cls.foobar', detail_level=0)['docstring'])
415 419
416 420
417 421 def test_pdef():
418 422 # See gh-1914
419 423 def foo(): pass
420 424 inspector.pdef(foo, 'foo')
421 425
422 426
423 427 def test_pinfo_nonascii():
424 428 # See gh-1177
425 429 from . import nonascii2
426 430 ip.user_ns['nonascii2'] = nonascii2
427 431 ip._inspect('pinfo', 'nonascii2', detail_level=1)
428 432
429 433
430 434 def test_pinfo_magic():
431 435 with AssertPrints('Docstring:'):
432 436 ip._inspect('pinfo', 'lsmagic', detail_level=0)
433 437
434 438 with AssertPrints('Source:'):
435 439 ip._inspect('pinfo', 'lsmagic', detail_level=1)
436 440
437 441
438 442 def test_init_colors():
439 443 # ensure colors are not present in signature info
440 444 info = inspector.info(HasSignature)
441 445 init_def = info['init_definition']
442 446 nt.assert_not_in('[0m', init_def)
443 447
444 448
445 449 def test_builtin_init():
446 450 info = inspector.info(list)
447 451 init_def = info['init_definition']
448 452 # Python < 3.4 can't get init definition from builtins,
449 453 # but still exercise the inspection in case of error-raising bugs.
450 454 if sys.version_info >= (3,4):
451 455 nt.assert_is_not_none(init_def)
452 456
@@ -1,1500 +1,1489 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 Verbose and colourful traceback formatting.
4 4
5 5 **ColorTB**
6 6
7 7 I've always found it a bit hard to visually parse tracebacks in Python. The
8 8 ColorTB class is a solution to that problem. It colors the different parts of a
9 9 traceback in a manner similar to what you would expect from a syntax-highlighting
10 10 text editor.
11 11
12 12 Installation instructions for ColorTB::
13 13
14 14 import sys,ultratb
15 15 sys.excepthook = ultratb.ColorTB()
16 16
17 17 **VerboseTB**
18 18
19 19 I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds
20 20 of useful info when a traceback occurs. Ping originally had it spit out HTML
21 21 and intended it for CGI programmers, but why should they have all the fun? I
22 22 altered it to spit out colored text to the terminal. It's a bit overwhelming,
23 23 but kind of neat, and maybe useful for long-running programs that you believe
24 24 are bug-free. If a crash *does* occur in that type of program you want details.
25 25 Give it a shot--you'll love it or you'll hate it.
26 26
27 27 .. note::
28 28
29 29 The Verbose mode prints the variables currently visible where the exception
30 30 happened (shortening their strings if too long). This can potentially be
31 31 very slow, if you happen to have a huge data structure whose string
32 32 representation is complex to compute. Your computer may appear to freeze for
33 33 a while with cpu usage at 100%. If this occurs, you can cancel the traceback
34 34 with Ctrl-C (maybe hitting it more than once).
35 35
36 36 If you encounter this kind of situation often, you may want to use the
37 37 Verbose_novars mode instead of the regular Verbose, which avoids formatting
38 38 variables (but otherwise includes the information and context given by
39 39 Verbose).
40 40
41 41 .. note::
42 42
43 43 The verbose mode print all variables in the stack, which means it can
44 44 potentially leak sensitive information like access keys, or unencryted
45 45 password.
46 46
47 47 Installation instructions for VerboseTB::
48 48
49 49 import sys,ultratb
50 50 sys.excepthook = ultratb.VerboseTB()
51 51
52 52 Note: Much of the code in this module was lifted verbatim from the standard
53 53 library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'.
54 54
55 55 Color schemes
56 56 -------------
57 57
58 58 The colors are defined in the class TBTools through the use of the
59 59 ColorSchemeTable class. Currently the following exist:
60 60
61 61 - NoColor: allows all of this module to be used in any terminal (the color
62 62 escapes are just dummy blank strings).
63 63
64 64 - Linux: is meant to look good in a terminal like the Linux console (black
65 65 or very dark background).
66 66
67 67 - LightBG: similar to Linux but swaps dark/light colors to be more readable
68 68 in light background terminals.
69 69
70 70 - Neutral: a neutral color scheme that should be readable on both light and
71 71 dark background
72 72
73 73 You can implement other color schemes easily, the syntax is fairly
74 74 self-explanatory. Please send back new schemes you develop to the author for
75 75 possible inclusion in future releases.
76 76
77 77 Inheritance diagram:
78 78
79 79 .. inheritance-diagram:: IPython.core.ultratb
80 80 :parts: 3
81 81 """
82 82
83 83 #*****************************************************************************
84 84 # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
85 85 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
86 86 #
87 87 # Distributed under the terms of the BSD License. The full license is in
88 88 # the file COPYING, distributed as part of this software.
89 89 #*****************************************************************************
90 90
91 91 from __future__ import absolute_import
92 92 from __future__ import unicode_literals
93 93 from __future__ import print_function
94 94
95 95 import dis
96 96 import inspect
97 97 import keyword
98 98 import linecache
99 99 import os
100 100 import pydoc
101 101 import re
102 102 import sys
103 103 import time
104 104 import tokenize
105 105 import traceback
106 106 import types
107 107
108 108 try: # Python 2
109 109 generate_tokens = tokenize.generate_tokens
110 110 except AttributeError: # Python 3
111 111 generate_tokens = tokenize.tokenize
112 112
113 113 # For purposes of monkeypatching inspect to fix a bug in it.
114 114 from inspect import getsourcefile, getfile, getmodule, \
115 115 ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode
116 116
117 117 # IPython's own modules
118 118 from IPython import get_ipython
119 119 from IPython.core import debugger
120 120 from IPython.core.display_trap import DisplayTrap
121 121 from IPython.core.excolors import exception_colors
122 122 from IPython.utils import PyColorize
123 123 from IPython.utils import openpy
124 124 from IPython.utils import path as util_path
125 125 from IPython.utils import py3compat
126 126 from IPython.utils import ulinecache
127 127 from IPython.utils.data import uniq_stable
128 128 from IPython.utils.terminal import get_terminal_size
129 129 from logging import info, error
130 130
131 131 import IPython.utils.colorable as colorable
132 132
133 133 # Globals
134 134 # amount of space to put line numbers before verbose tracebacks
135 135 INDENT_SIZE = 8
136 136
137 137 # Default color scheme. This is used, for example, by the traceback
138 138 # formatter. When running in an actual IPython instance, the user's rc.colors
139 139 # value is used, but having a module global makes this functionality available
140 140 # to users of ultratb who are NOT running inside ipython.
141 141 DEFAULT_SCHEME = 'NoColor'
142 142
143 143 # ---------------------------------------------------------------------------
144 144 # Code begins
145 145
146 146 # Utility functions
147 147 def inspect_error():
148 148 """Print a message about internal inspect errors.
149 149
150 150 These are unfortunately quite common."""
151 151
152 152 error('Internal Python error in the inspect module.\n'
153 153 'Below is the traceback from this internal error.\n')
154 154
155 155
156 156 # This function is a monkeypatch we apply to the Python inspect module. We have
157 157 # now found when it's needed (see discussion on issue gh-1456), and we have a
158 158 # test case (IPython.core.tests.test_ultratb.ChangedPyFileTest) that fails if
159 159 # the monkeypatch is not applied. TK, Aug 2012.
160 160 def findsource(object):
161 161 """Return the entire source file and starting line number for an object.
162 162
163 163 The argument may be a module, class, method, function, traceback, frame,
164 164 or code object. The source code is returned as a list of all the lines
165 165 in the file and the line number indexes a line in that list. An IOError
166 166 is raised if the source code cannot be retrieved.
167 167
168 168 FIXED version with which we monkeypatch the stdlib to work around a bug."""
169 169
170 170 file = getsourcefile(object) or getfile(object)
171 171 # If the object is a frame, then trying to get the globals dict from its
172 172 # module won't work. Instead, the frame object itself has the globals
173 173 # dictionary.
174 174 globals_dict = None
175 175 if inspect.isframe(object):
176 176 # XXX: can this ever be false?
177 177 globals_dict = object.f_globals
178 178 else:
179 179 module = getmodule(object, file)
180 180 if module:
181 181 globals_dict = module.__dict__
182 182 lines = linecache.getlines(file, globals_dict)
183 183 if not lines:
184 184 raise IOError('could not get source code')
185 185
186 186 if ismodule(object):
187 187 return lines, 0
188 188
189 189 if isclass(object):
190 190 name = object.__name__
191 191 pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
192 192 # make some effort to find the best matching class definition:
193 193 # use the one with the least indentation, which is the one
194 194 # that's most probably not inside a function definition.
195 195 candidates = []
196 196 for i in range(len(lines)):
197 197 match = pat.match(lines[i])
198 198 if match:
199 199 # if it's at toplevel, it's already the best one
200 200 if lines[i][0] == 'c':
201 201 return lines, i
202 202 # else add whitespace to candidate list
203 203 candidates.append((match.group(1), i))
204 204 if candidates:
205 205 # this will sort by whitespace, and by line number,
206 206 # less whitespace first
207 207 candidates.sort()
208 208 return lines, candidates[0][1]
209 209 else:
210 210 raise IOError('could not find class definition')
211 211
212 212 if ismethod(object):
213 213 object = object.__func__
214 214 if isfunction(object):
215 215 object = object.__code__
216 216 if istraceback(object):
217 217 object = object.tb_frame
218 218 if isframe(object):
219 219 object = object.f_code
220 220 if iscode(object):
221 221 if not hasattr(object, 'co_firstlineno'):
222 222 raise IOError('could not find function definition')
223 223 pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
224 224 pmatch = pat.match
225 225 # fperez - fix: sometimes, co_firstlineno can give a number larger than
226 226 # the length of lines, which causes an error. Safeguard against that.
227 227 lnum = min(object.co_firstlineno, len(lines)) - 1
228 228 while lnum > 0:
229 229 if pmatch(lines[lnum]):
230 230 break
231 231 lnum -= 1
232 232
233 233 return lines, lnum
234 234 raise IOError('could not find code object')
235 235
236 236
237 237 # This is a patched version of inspect.getargs that applies the (unmerged)
238 238 # patch for http://bugs.python.org/issue14611 by Stefano Taschini. This fixes
239 239 # https://github.com/ipython/ipython/issues/8205 and
240 240 # https://github.com/ipython/ipython/issues/8293
241 241 def getargs(co):
242 242 """Get information about the arguments accepted by a code object.
243 243
244 244 Three things are returned: (args, varargs, varkw), where 'args' is
245 245 a list of argument names (possibly containing nested lists), and
246 246 'varargs' and 'varkw' are the names of the * and ** arguments or None."""
247 247 if not iscode(co):
248 248 raise TypeError('{!r} is not a code object'.format(co))
249 249
250 250 nargs = co.co_argcount
251 251 names = co.co_varnames
252 252 args = list(names[:nargs])
253 253 step = 0
254 254
255 255 # The following acrobatics are for anonymous (tuple) arguments.
256 256 for i in range(nargs):
257 257 if args[i][:1] in ('', '.'):
258 258 stack, remain, count = [], [], []
259 259 while step < len(co.co_code):
260 260 op = ord(co.co_code[step])
261 261 step = step + 1
262 262 if op >= dis.HAVE_ARGUMENT:
263 263 opname = dis.opname[op]
264 264 value = ord(co.co_code[step]) + ord(co.co_code[step+1])*256
265 265 step = step + 2
266 266 if opname in ('UNPACK_TUPLE', 'UNPACK_SEQUENCE'):
267 267 remain.append(value)
268 268 count.append(value)
269 269 elif opname in ('STORE_FAST', 'STORE_DEREF'):
270 270 if op in dis.haslocal:
271 271 stack.append(co.co_varnames[value])
272 272 elif op in dis.hasfree:
273 273 stack.append((co.co_cellvars + co.co_freevars)[value])
274 274 # Special case for sublists of length 1: def foo((bar))
275 275 # doesn't generate the UNPACK_TUPLE bytecode, so if
276 276 # `remain` is empty here, we have such a sublist.
277 277 if not remain:
278 278 stack[0] = [stack[0]]
279 279 break
280 280 else:
281 281 remain[-1] = remain[-1] - 1
282 282 while remain[-1] == 0:
283 283 remain.pop()
284 284 size = count.pop()
285 285 stack[-size:] = [stack[-size:]]
286 286 if not remain:
287 287 break
288 288 remain[-1] = remain[-1] - 1
289 289 if not remain:
290 290 break
291 291 args[i] = stack[0]
292 292
293 293 varargs = None
294 294 if co.co_flags & inspect.CO_VARARGS:
295 295 varargs = co.co_varnames[nargs]
296 296 nargs = nargs + 1
297 297 varkw = None
298 298 if co.co_flags & inspect.CO_VARKEYWORDS:
299 299 varkw = co.co_varnames[nargs]
300 300 return inspect.Arguments(args, varargs, varkw)
301 301
302 302
303 303 # Monkeypatch inspect to apply our bugfix.
304 304 def with_patch_inspect(f):
305 305 """decorator for monkeypatching inspect.findsource"""
306 306
307 307 def wrapped(*args, **kwargs):
308 308 save_findsource = inspect.findsource
309 309 save_getargs = inspect.getargs
310 310 inspect.findsource = findsource
311 311 inspect.getargs = getargs
312 312 try:
313 313 return f(*args, **kwargs)
314 314 finally:
315 315 inspect.findsource = save_findsource
316 316 inspect.getargs = save_getargs
317 317
318 318 return wrapped
319 319
320 320
321 321 if py3compat.PY3:
322 322 fixed_getargvalues = inspect.getargvalues
323 323 else:
324 324 # Fixes for https://github.com/ipython/ipython/issues/8293
325 325 # and https://github.com/ipython/ipython/issues/8205.
326 326 # The relevant bug is caused by failure to correctly handle anonymous tuple
327 327 # unpacking, which only exists in Python 2.
328 328 fixed_getargvalues = with_patch_inspect(inspect.getargvalues)
329 329
330 330
331 331 def fix_frame_records_filenames(records):
332 332 """Try to fix the filenames in each record from inspect.getinnerframes().
333 333
334 334 Particularly, modules loaded from within zip files have useless filenames
335 335 attached to their code object, and inspect.getinnerframes() just uses it.
336 336 """
337 337 fixed_records = []
338 338 for frame, filename, line_no, func_name, lines, index in records:
339 339 # Look inside the frame's globals dictionary for __file__,
340 340 # which should be better. However, keep Cython filenames since
341 341 # we prefer the source filenames over the compiled .so file.
342 342 filename = py3compat.cast_unicode_py2(filename, "utf-8")
343 343 if not filename.endswith(('.pyx', '.pxd', '.pxi')):
344 344 better_fn = frame.f_globals.get('__file__', None)
345 345 if isinstance(better_fn, str):
346 346 # Check the type just in case someone did something weird with
347 347 # __file__. It might also be None if the error occurred during
348 348 # import.
349 349 filename = better_fn
350 350 fixed_records.append((frame, filename, line_no, func_name, lines, index))
351 351 return fixed_records
352 352
353 353
354 354 @with_patch_inspect
355 355 def _fixed_getinnerframes(etb, context=1, tb_offset=0):
356 356 LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5
357 357
358 358 records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
359 359 # If the error is at the console, don't build any context, since it would
360 360 # otherwise produce 5 blank lines printed out (there is no file at the
361 361 # console)
362 362 rec_check = records[tb_offset:]
363 363 try:
364 364 rname = rec_check[0][1]
365 365 if rname == '<ipython console>' or rname.endswith('<string>'):
366 366 return rec_check
367 367 except IndexError:
368 368 pass
369 369
370 370 aux = traceback.extract_tb(etb)
371 371 assert len(records) == len(aux)
372 372 for i, (file, lnum, _, _) in zip(range(len(records)), aux):
373 373 maybeStart = lnum - 1 - context // 2
374 374 start = max(maybeStart, 0)
375 375 end = start + context
376 376 lines = ulinecache.getlines(file)[start:end]
377 377 buf = list(records[i])
378 378 buf[LNUM_POS] = lnum
379 379 buf[INDEX_POS] = lnum - 1 - start
380 380 buf[LINES_POS] = lines
381 381 records[i] = tuple(buf)
382 382 return records[tb_offset:]
383 383
384 384 # Helper function -- largely belongs to VerboseTB, but we need the same
385 385 # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they
386 386 # can be recognized properly by ipython.el's py-traceback-line-re
387 387 # (SyntaxErrors have to be treated specially because they have no traceback)
388 388
389 _parser = PyColorize.Parser()
390
391 389
392 390 def _format_traceback_lines(lnum, index, lines, Colors, lvals=None, scheme=None):
393 391 numbers_width = INDENT_SIZE - 1
394 392 res = []
395 393 i = lnum - index
396 394
397 # This lets us get fully syntax-highlighted tracebacks.
398 if scheme is None:
399 ipinst = get_ipython()
400 if ipinst is not None:
401 scheme = ipinst.colors
402 else:
403 scheme = DEFAULT_SCHEME
404
405 _line_format = _parser.format2
395 _line_format = PyColorize.Parser(style=scheme).format2
406 396
407 397 for line in lines:
408 398 line = py3compat.cast_unicode(line)
409 399
410 new_line, err = _line_format(line, 'str', scheme)
400 new_line, err = _line_format(line, 'str')
411 401 if not err: line = new_line
412 402
413 403 if i == lnum:
414 404 # This is the line with the error
415 405 pad = numbers_width - len(str(i))
416 406 num = '%s%s' % (debugger.make_arrow(pad), str(lnum))
417 407 line = '%s%s%s %s%s' % (Colors.linenoEm, num,
418 408 Colors.line, line, Colors.Normal)
419 409 else:
420 410 num = '%*s' % (numbers_width, i)
421 411 line = '%s%s%s %s' % (Colors.lineno, num,
422 412 Colors.Normal, line)
423 413
424 414 res.append(line)
425 415 if lvals and i == lnum:
426 416 res.append(lvals + '\n')
427 417 i = i + 1
428 418 return res
429 419
430 420 def is_recursion_error(etype, value, records):
431 421 try:
432 422 # RecursionError is new in Python 3.5
433 423 recursion_error_type = RecursionError
434 424 except NameError:
435 425 recursion_error_type = RuntimeError
436 426
437 427 # The default recursion limit is 1000, but some of that will be taken up
438 428 # by stack frames in IPython itself. >500 frames probably indicates
439 429 # a recursion error.
440 430 return (etype is recursion_error_type) \
441 431 and "recursion" in str(value).lower() \
442 432 and len(records) > 500
443 433
444 434 def find_recursion(etype, value, records):
445 435 """Identify the repeating stack frames from a RecursionError traceback
446 436
447 437 'records' is a list as returned by VerboseTB.get_records()
448 438
449 439 Returns (last_unique, repeat_length)
450 440 """
451 441 # This involves a bit of guesswork - we want to show enough of the traceback
452 442 # to indicate where the recursion is occurring. We guess that the innermost
453 443 # quarter of the traceback (250 frames by default) is repeats, and find the
454 444 # first frame (from in to out) that looks different.
455 445 if not is_recursion_error(etype, value, records):
456 446 return len(records), 0
457 447
458 448 # Select filename, lineno, func_name to track frames with
459 449 records = [r[1:4] for r in records]
460 450 inner_frames = records[-(len(records)//4):]
461 451 frames_repeated = set(inner_frames)
462 452
463 453 last_seen_at = {}
464 454 longest_repeat = 0
465 455 i = len(records)
466 456 for frame in reversed(records):
467 457 i -= 1
468 458 if frame not in frames_repeated:
469 459 last_unique = i
470 460 break
471 461
472 462 if frame in last_seen_at:
473 463 distance = last_seen_at[frame] - i
474 464 longest_repeat = max(longest_repeat, distance)
475 465
476 466 last_seen_at[frame] = i
477 467 else:
478 468 last_unique = 0 # The whole traceback was recursion
479 469
480 470 return last_unique, longest_repeat
481 471
482 472 #---------------------------------------------------------------------------
483 473 # Module classes
484 474 class TBTools(colorable.Colorable):
485 475 """Basic tools used by all traceback printer classes."""
486 476
487 477 # Number of frames to skip when reporting tracebacks
488 478 tb_offset = 0
489 479
490 480 def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None, config=None):
491 481 # Whether to call the interactive pdb debugger after printing
492 482 # tracebacks or not
493 483 super(TBTools, self).__init__(parent=parent, config=config)
494 484 self.call_pdb = call_pdb
495 485
496 486 # Output stream to write to. Note that we store the original value in
497 487 # a private attribute and then make the public ostream a property, so
498 488 # that we can delay accessing sys.stdout until runtime. The way
499 489 # things are written now, the sys.stdout object is dynamically managed
500 490 # so a reference to it should NEVER be stored statically. This
501 491 # property approach confines this detail to a single location, and all
502 492 # subclasses can simply access self.ostream for writing.
503 493 self._ostream = ostream
504 494
505 495 # Create color table
506 496 self.color_scheme_table = exception_colors()
507 497
508 498 self.set_colors(color_scheme)
509 499 self.old_scheme = color_scheme # save initial value for toggles
510 500
511 501 if call_pdb:
512 502 self.pdb = debugger.Pdb()
513 503 else:
514 504 self.pdb = None
515 505
516 506 def _get_ostream(self):
517 507 """Output stream that exceptions are written to.
518 508
519 509 Valid values are:
520 510
521 511 - None: the default, which means that IPython will dynamically resolve
522 512 to sys.stdout. This ensures compatibility with most tools, including
523 513 Windows (where plain stdout doesn't recognize ANSI escapes).
524 514
525 515 - Any object with 'write' and 'flush' attributes.
526 516 """
527 517 return sys.stdout if self._ostream is None else self._ostream
528 518
529 519 def _set_ostream(self, val):
530 520 assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush'))
531 521 self._ostream = val
532 522
533 523 ostream = property(_get_ostream, _set_ostream)
534 524
535 525 def set_colors(self, *args, **kw):
536 526 """Shorthand access to the color table scheme selector method."""
537 527
538 528 # Set own color table
539 529 self.color_scheme_table.set_active_scheme(*args, **kw)
540 530 # for convenience, set Colors to the active scheme
541 531 self.Colors = self.color_scheme_table.active_colors
542 532 # Also set colors of debugger
543 533 if hasattr(self, 'pdb') and self.pdb is not None:
544 534 self.pdb.set_colors(*args, **kw)
545 535
546 536 def color_toggle(self):
547 537 """Toggle between the currently active color scheme and NoColor."""
548 538
549 539 if self.color_scheme_table.active_scheme_name == 'NoColor':
550 540 self.color_scheme_table.set_active_scheme(self.old_scheme)
551 541 self.Colors = self.color_scheme_table.active_colors
552 542 else:
553 543 self.old_scheme = self.color_scheme_table.active_scheme_name
554 544 self.color_scheme_table.set_active_scheme('NoColor')
555 545 self.Colors = self.color_scheme_table.active_colors
556 546
557 547 def stb2text(self, stb):
558 548 """Convert a structured traceback (a list) to a string."""
559 549 return '\n'.join(stb)
560 550
561 551 def text(self, etype, value, tb, tb_offset=None, context=5):
562 552 """Return formatted traceback.
563 553
564 554 Subclasses may override this if they add extra arguments.
565 555 """
566 556 tb_list = self.structured_traceback(etype, value, tb,
567 557 tb_offset, context)
568 558 return self.stb2text(tb_list)
569 559
570 560 def structured_traceback(self, etype, evalue, tb, tb_offset=None,
571 561 context=5, mode=None):
572 562 """Return a list of traceback frames.
573 563
574 564 Must be implemented by each class.
575 565 """
576 566 raise NotImplementedError()
577 567
578 568
579 569 #---------------------------------------------------------------------------
580 570 class ListTB(TBTools):
581 571 """Print traceback information from a traceback list, with optional color.
582 572
583 573 Calling requires 3 arguments: (etype, evalue, elist)
584 574 as would be obtained by::
585 575
586 576 etype, evalue, tb = sys.exc_info()
587 577 if tb:
588 578 elist = traceback.extract_tb(tb)
589 579 else:
590 580 elist = None
591 581
592 582 It can thus be used by programs which need to process the traceback before
593 583 printing (such as console replacements based on the code module from the
594 584 standard library).
595 585
596 586 Because they are meant to be called without a full traceback (only a
597 587 list), instances of this class can't call the interactive pdb debugger."""
598 588
599 589 def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None):
600 590 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
601 591 ostream=ostream, parent=parent)
602 592
603 593 def __call__(self, etype, value, elist):
604 594 self.ostream.flush()
605 595 self.ostream.write(self.text(etype, value, elist))
606 596 self.ostream.write('\n')
607 597
608 598 def structured_traceback(self, etype, value, elist, tb_offset=None,
609 599 context=5):
610 600 """Return a color formatted string with the traceback info.
611 601
612 602 Parameters
613 603 ----------
614 604 etype : exception type
615 605 Type of the exception raised.
616 606
617 607 value : object
618 608 Data stored in the exception
619 609
620 610 elist : list
621 611 List of frames, see class docstring for details.
622 612
623 613 tb_offset : int, optional
624 614 Number of frames in the traceback to skip. If not given, the
625 615 instance value is used (set in constructor).
626 616
627 617 context : int, optional
628 618 Number of lines of context information to print.
629 619
630 620 Returns
631 621 -------
632 622 String with formatted exception.
633 623 """
634 624 tb_offset = self.tb_offset if tb_offset is None else tb_offset
635 625 Colors = self.Colors
636 626 out_list = []
637 627 if elist:
638 628
639 629 if tb_offset and len(elist) > tb_offset:
640 630 elist = elist[tb_offset:]
641 631
642 632 out_list.append('Traceback %s(most recent call last)%s:' %
643 633 (Colors.normalEm, Colors.Normal) + '\n')
644 634 out_list.extend(self._format_list(elist))
645 635 # The exception info should be a single entry in the list.
646 636 lines = ''.join(self._format_exception_only(etype, value))
647 637 out_list.append(lines)
648 638
649 639 # Note: this code originally read:
650 640
651 641 ## for line in lines[:-1]:
652 642 ## out_list.append(" "+line)
653 643 ## out_list.append(lines[-1])
654 644
655 645 # This means it was indenting everything but the last line by a little
656 646 # bit. I've disabled this for now, but if we see ugliness somewhere we
657 647 # can restore it.
658 648
659 649 return out_list
660 650
661 651 def _format_list(self, extracted_list):
662 652 """Format a list of traceback entry tuples for printing.
663 653
664 654 Given a list of tuples as returned by extract_tb() or
665 655 extract_stack(), return a list of strings ready for printing.
666 656 Each string in the resulting list corresponds to the item with the
667 657 same index in the argument list. Each string ends in a newline;
668 658 the strings may contain internal newlines as well, for those items
669 659 whose source text line is not None.
670 660
671 661 Lifted almost verbatim from traceback.py
672 662 """
673 663
674 664 Colors = self.Colors
675 665 list = []
676 666 for filename, lineno, name, line in extracted_list[:-1]:
677 667 item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
678 668 (Colors.filename, py3compat.cast_unicode_py2(filename, "utf-8"), Colors.Normal,
679 669 Colors.lineno, lineno, Colors.Normal,
680 670 Colors.name, py3compat.cast_unicode_py2(name, "utf-8"), Colors.Normal)
681 671 if line:
682 672 item += ' %s\n' % line.strip()
683 673 list.append(item)
684 674 # Emphasize the last entry
685 675 filename, lineno, name, line = extracted_list[-1]
686 676 item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
687 677 (Colors.normalEm,
688 678 Colors.filenameEm, py3compat.cast_unicode_py2(filename, "utf-8"), Colors.normalEm,
689 679 Colors.linenoEm, lineno, Colors.normalEm,
690 680 Colors.nameEm, py3compat.cast_unicode_py2(name, "utf-8"), Colors.normalEm,
691 681 Colors.Normal)
692 682 if line:
693 683 item += '%s %s%s\n' % (Colors.line, line.strip(),
694 684 Colors.Normal)
695 685 list.append(item)
696 686 return list
697 687
698 688 def _format_exception_only(self, etype, value):
699 689 """Format the exception part of a traceback.
700 690
701 691 The arguments are the exception type and value such as given by
702 692 sys.exc_info()[:2]. The return value is a list of strings, each ending
703 693 in a newline. Normally, the list contains a single string; however,
704 694 for SyntaxError exceptions, it contains several lines that (when
705 695 printed) display detailed information about where the syntax error
706 696 occurred. The message indicating which exception occurred is the
707 697 always last string in the list.
708 698
709 699 Also lifted nearly verbatim from traceback.py
710 700 """
711 701 have_filedata = False
712 702 Colors = self.Colors
713 703 list = []
714 704 stype = py3compat.cast_unicode(Colors.excName + etype.__name__ + Colors.Normal)
715 705 if value is None:
716 706 # Not sure if this can still happen in Python 2.6 and above
717 707 list.append(stype + '\n')
718 708 else:
719 709 if issubclass(etype, SyntaxError):
720 710 have_filedata = True
721 711 if not value.filename: value.filename = "<string>"
722 712 if value.lineno:
723 713 lineno = value.lineno
724 714 textline = ulinecache.getline(value.filename, value.lineno)
725 715 else:
726 716 lineno = 'unknown'
727 717 textline = ''
728 718 list.append('%s File %s"%s"%s, line %s%s%s\n' % \
729 719 (Colors.normalEm,
730 720 Colors.filenameEm, py3compat.cast_unicode(value.filename), Colors.normalEm,
731 721 Colors.linenoEm, lineno, Colors.Normal ))
732 722 if textline == '':
733 723 textline = py3compat.cast_unicode(value.text, "utf-8")
734 724
735 725 if textline is not None:
736 726 i = 0
737 727 while i < len(textline) and textline[i].isspace():
738 728 i += 1
739 729 list.append('%s %s%s\n' % (Colors.line,
740 730 textline.strip(),
741 731 Colors.Normal))
742 732 if value.offset is not None:
743 733 s = ' '
744 734 for c in textline[i:value.offset - 1]:
745 735 if c.isspace():
746 736 s += c
747 737 else:
748 738 s += ' '
749 739 list.append('%s%s^%s\n' % (Colors.caret, s,
750 740 Colors.Normal))
751 741
752 742 try:
753 743 s = value.msg
754 744 except Exception:
755 745 s = self._some_str(value)
756 746 if s:
757 747 list.append('%s%s:%s %s\n' % (stype, Colors.excName,
758 748 Colors.Normal, s))
759 749 else:
760 750 list.append('%s\n' % stype)
761 751
762 752 # sync with user hooks
763 753 if have_filedata:
764 754 ipinst = get_ipython()
765 755 if ipinst is not None:
766 756 ipinst.hooks.synchronize_with_editor(value.filename, value.lineno, 0)
767 757
768 758 return list
769 759
770 760 def get_exception_only(self, etype, value):
771 761 """Only print the exception type and message, without a traceback.
772 762
773 763 Parameters
774 764 ----------
775 765 etype : exception type
776 766 value : exception value
777 767 """
778 768 return ListTB.structured_traceback(self, etype, value, [])
779 769
780 770 def show_exception_only(self, etype, evalue):
781 771 """Only print the exception type and message, without a traceback.
782 772
783 773 Parameters
784 774 ----------
785 775 etype : exception type
786 776 value : exception value
787 777 """
788 778 # This method needs to use __call__ from *this* class, not the one from
789 779 # a subclass whose signature or behavior may be different
790 780 ostream = self.ostream
791 781 ostream.flush()
792 782 ostream.write('\n'.join(self.get_exception_only(etype, evalue)))
793 783 ostream.flush()
794 784
795 785 def _some_str(self, value):
796 786 # Lifted from traceback.py
797 787 try:
798 788 return py3compat.cast_unicode(str(value))
799 789 except:
800 790 return u'<unprintable %s object>' % type(value).__name__
801 791
802 792
803 793 #----------------------------------------------------------------------------
804 794 class VerboseTB(TBTools):
805 795 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
806 796 of HTML. Requires inspect and pydoc. Crazy, man.
807 797
808 798 Modified version which optionally strips the topmost entries from the
809 799 traceback, to be used with alternate interpreters (because their own code
810 800 would appear in the traceback)."""
811 801
812 802 def __init__(self, color_scheme='Linux', call_pdb=False, ostream=None,
813 803 tb_offset=0, long_header=False, include_vars=True,
814 804 check_cache=None, debugger_cls = None):
815 805 """Specify traceback offset, headers and color scheme.
816 806
817 807 Define how many frames to drop from the tracebacks. Calling it with
818 808 tb_offset=1 allows use of this handler in interpreters which will have
819 809 their own code at the top of the traceback (VerboseTB will first
820 810 remove that frame before printing the traceback info)."""
821 811 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
822 812 ostream=ostream)
823 813 self.tb_offset = tb_offset
824 814 self.long_header = long_header
825 815 self.include_vars = include_vars
826 816 # By default we use linecache.checkcache, but the user can provide a
827 817 # different check_cache implementation. This is used by the IPython
828 818 # kernel to provide tracebacks for interactive code that is cached,
829 819 # by a compiler instance that flushes the linecache but preserves its
830 820 # own code cache.
831 821 if check_cache is None:
832 822 check_cache = linecache.checkcache
833 823 self.check_cache = check_cache
834 824
835 825 self.debugger_cls = debugger_cls or debugger.Pdb
836 826
837 827 def format_records(self, records, last_unique, recursion_repeat):
838 828 """Format the stack frames of the traceback"""
839 829 frames = []
840 830 for r in records[:last_unique+recursion_repeat+1]:
841 831 #print '*** record:',file,lnum,func,lines,index # dbg
842 832 frames.append(self.format_record(*r))
843 833
844 834 if recursion_repeat:
845 835 frames.append('... last %d frames repeated, from the frame below ...\n' % recursion_repeat)
846 836 frames.append(self.format_record(*records[last_unique+recursion_repeat+1]))
847 837
848 838 return frames
849 839
850 840 def format_record(self, frame, file, lnum, func, lines, index):
851 841 """Format a single stack frame"""
852 842 Colors = self.Colors # just a shorthand + quicker name lookup
853 843 ColorsNormal = Colors.Normal # used a lot
854 844 col_scheme = self.color_scheme_table.active_scheme_name
855 845 indent = ' ' * INDENT_SIZE
856 846 em_normal = '%s\n%s%s' % (Colors.valEm, indent, ColorsNormal)
857 847 undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
858 848 tpl_link = '%s%%s%s' % (Colors.filenameEm, ColorsNormal)
859 849 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
860 850 ColorsNormal)
861 851 tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
862 852 (Colors.vName, Colors.valEm, ColorsNormal)
863 853 tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
864 854 tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
865 855 Colors.vName, ColorsNormal)
866 856 tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
867 857
868 858 tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal)
869 859 tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm, Colors.line,
870 860 ColorsNormal)
871 861
872 862 abspath = os.path.abspath
873 863
874 864
875 865 if not file:
876 866 file = '?'
877 867 elif file.startswith(str("<")) and file.endswith(str(">")):
878 868 # Not a real filename, no problem...
879 869 pass
880 870 elif not os.path.isabs(file):
881 871 # Try to make the filename absolute by trying all
882 872 # sys.path entries (which is also what linecache does)
883 873 for dirname in sys.path:
884 874 try:
885 875 fullname = os.path.join(dirname, file)
886 876 if os.path.isfile(fullname):
887 877 file = os.path.abspath(fullname)
888 878 break
889 879 except Exception:
890 880 # Just in case that sys.path contains very
891 881 # strange entries...
892 882 pass
893 883
894 884 file = py3compat.cast_unicode(file, util_path.fs_encoding)
895 885 link = tpl_link % file
896 886 args, varargs, varkw, locals = fixed_getargvalues(frame)
897 887
898 888 if func == '?':
899 889 call = ''
900 890 else:
901 891 # Decide whether to include variable details or not
902 892 var_repr = self.include_vars and eqrepr or nullrepr
903 893 try:
904 894 call = tpl_call % (func, inspect.formatargvalues(args,
905 895 varargs, varkw,
906 896 locals, formatvalue=var_repr))
907 897 except KeyError:
908 898 # This happens in situations like errors inside generator
909 899 # expressions, where local variables are listed in the
910 900 # line, but can't be extracted from the frame. I'm not
911 901 # 100% sure this isn't actually a bug in inspect itself,
912 902 # but since there's no info for us to compute with, the
913 903 # best we can do is report the failure and move on. Here
914 904 # we must *not* call any traceback construction again,
915 905 # because that would mess up use of %debug later on. So we
916 906 # simply report the failure and move on. The only
917 907 # limitation will be that this frame won't have locals
918 908 # listed in the call signature. Quite subtle problem...
919 909 # I can't think of a good way to validate this in a unit
920 910 # test, but running a script consisting of:
921 911 # dict( (k,v.strip()) for (k,v) in range(10) )
922 912 # will illustrate the error, if this exception catch is
923 913 # disabled.
924 914 call = tpl_call_fail % func
925 915
926 916 # Don't attempt to tokenize binary files.
927 917 if file.endswith(('.so', '.pyd', '.dll')):
928 918 return '%s %s\n' % (link, call)
929 919
930 920 elif file.endswith(('.pyc', '.pyo')):
931 921 # Look up the corresponding source file.
932 922 try:
933 923 file = openpy.source_from_cache(file)
934 924 except ValueError:
935 925 # Failed to get the source file for some reason
936 926 # E.g. https://github.com/ipython/ipython/issues/9486
937 927 return '%s %s\n' % (link, call)
938 928
939 929 def linereader(file=file, lnum=[lnum], getline=ulinecache.getline):
940 930 line = getline(file, lnum[0])
941 931 lnum[0] += 1
942 932 return line
943 933
944 934 # Build the list of names on this line of code where the exception
945 935 # occurred.
946 936 try:
947 937 names = []
948 938 name_cont = False
949 939
950 940 for token_type, token, start, end, line in generate_tokens(linereader):
951 941 # build composite names
952 942 if token_type == tokenize.NAME and token not in keyword.kwlist:
953 943 if name_cont:
954 944 # Continuation of a dotted name
955 945 try:
956 946 names[-1].append(token)
957 947 except IndexError:
958 948 names.append([token])
959 949 name_cont = False
960 950 else:
961 951 # Regular new names. We append everything, the caller
962 952 # will be responsible for pruning the list later. It's
963 953 # very tricky to try to prune as we go, b/c composite
964 954 # names can fool us. The pruning at the end is easy
965 955 # to do (or the caller can print a list with repeated
966 956 # names if so desired.
967 957 names.append([token])
968 958 elif token == '.':
969 959 name_cont = True
970 960 elif token_type == tokenize.NEWLINE:
971 961 break
972 962
973 963 except (IndexError, UnicodeDecodeError, SyntaxError):
974 964 # signals exit of tokenizer
975 965 # SyntaxError can occur if the file is not actually Python
976 966 # - see gh-6300
977 967 pass
978 968 except tokenize.TokenError as msg:
979 969 _m = ("An unexpected error occurred while tokenizing input\n"
980 970 "The following traceback may be corrupted or invalid\n"
981 971 "The error message is: %s\n" % msg)
982 972 error(_m)
983 973
984 974 # Join composite names (e.g. "dict.fromkeys")
985 975 names = ['.'.join(n) for n in names]
986 976 # prune names list of duplicates, but keep the right order
987 977 unique_names = uniq_stable(names)
988 978
989 979 # Start loop over vars
990 980 lvals = []
991 981 if self.include_vars:
992 982 for name_full in unique_names:
993 983 name_base = name_full.split('.', 1)[0]
994 984 if name_base in frame.f_code.co_varnames:
995 985 if name_base in locals:
996 986 try:
997 987 value = repr(eval(name_full, locals))
998 988 except:
999 989 value = undefined
1000 990 else:
1001 991 value = undefined
1002 992 name = tpl_local_var % name_full
1003 993 else:
1004 994 if name_base in frame.f_globals:
1005 995 try:
1006 996 value = repr(eval(name_full, frame.f_globals))
1007 997 except:
1008 998 value = undefined
1009 999 else:
1010 1000 value = undefined
1011 1001 name = tpl_global_var % name_full
1012 1002 lvals.append(tpl_name_val % (name, value))
1013 1003 if lvals:
1014 1004 lvals = '%s%s' % (indent, em_normal.join(lvals))
1015 1005 else:
1016 1006 lvals = ''
1017 1007
1018 1008 level = '%s %s\n' % (link, call)
1019 1009
1020 1010 if index is None:
1021 1011 return level
1022 1012 else:
1023 1013 return '%s%s' % (level, ''.join(
1024 1014 _format_traceback_lines(lnum, index, lines, Colors, lvals,
1025 1015 col_scheme)))
1026 1016
1027 1017 def prepare_chained_exception_message(self, cause):
1028 1018 direct_cause = "\nThe above exception was the direct cause of the following exception:\n"
1029 1019 exception_during_handling = "\nDuring handling of the above exception, another exception occurred:\n"
1030 1020
1031 1021 if cause:
1032 1022 message = [[direct_cause]]
1033 1023 else:
1034 1024 message = [[exception_during_handling]]
1035 1025 return message
1036 1026
1037 1027 def prepare_header(self, etype, long_version=False):
1038 1028 colors = self.Colors # just a shorthand + quicker name lookup
1039 1029 colorsnormal = colors.Normal # used a lot
1040 1030 exc = '%s%s%s' % (colors.excName, etype, colorsnormal)
1041 1031 width = min(75, get_terminal_size()[0])
1042 1032 if long_version:
1043 1033 # Header with the exception type, python version, and date
1044 1034 pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
1045 1035 date = time.ctime(time.time())
1046 1036
1047 1037 head = '%s%s%s\n%s%s%s\n%s' % (colors.topline, '-' * width, colorsnormal,
1048 1038 exc, ' ' * (width - len(str(etype)) - len(pyver)),
1049 1039 pyver, date.rjust(width) )
1050 1040 head += "\nA problem occurred executing Python code. Here is the sequence of function" \
1051 1041 "\ncalls leading up to the error, with the most recent (innermost) call last."
1052 1042 else:
1053 1043 # Simplified header
1054 1044 head = '%s%s' % (exc, 'Traceback (most recent call last)'. \
1055 1045 rjust(width - len(str(etype))) )
1056 1046
1057 1047 return head
1058 1048
1059 1049 def format_exception(self, etype, evalue):
1060 1050 colors = self.Colors # just a shorthand + quicker name lookup
1061 1051 colorsnormal = colors.Normal # used a lot
1062 1052 indent = ' ' * INDENT_SIZE
1063 1053 # Get (safely) a string form of the exception info
1064 1054 try:
1065 1055 etype_str, evalue_str = map(str, (etype, evalue))
1066 1056 except:
1067 1057 # User exception is improperly defined.
1068 1058 etype, evalue = str, sys.exc_info()[:2]
1069 1059 etype_str, evalue_str = map(str, (etype, evalue))
1070 1060 # ... and format it
1071 1061 exception = ['%s%s%s: %s' % (colors.excName, etype_str,
1072 1062 colorsnormal, py3compat.cast_unicode(evalue_str))]
1073 1063
1074 1064 if (not py3compat.PY3) and type(evalue) is types.InstanceType:
1075 1065 try:
1076 1066 names = [w for w in dir(evalue) if isinstance(w, py3compat.string_types)]
1077 1067 except:
1078 1068 # Every now and then, an object with funny internals blows up
1079 1069 # when dir() is called on it. We do the best we can to report
1080 1070 # the problem and continue
1081 1071 _m = '%sException reporting error (object with broken dir())%s:'
1082 1072 exception.append(_m % (colors.excName, colorsnormal))
1083 1073 etype_str, evalue_str = map(str, sys.exc_info()[:2])
1084 1074 exception.append('%s%s%s: %s' % (colors.excName, etype_str,
1085 1075 colorsnormal, py3compat.cast_unicode(evalue_str)))
1086 1076 names = []
1087 1077 for name in names:
1088 1078 value = text_repr(getattr(evalue, name))
1089 1079 exception.append('\n%s%s = %s' % (indent, name, value))
1090 1080
1091 1081 return exception
1092 1082
1093 1083 def format_exception_as_a_whole(self, etype, evalue, etb, number_of_lines_of_context, tb_offset):
1094 1084 """Formats the header, traceback and exception message for a single exception.
1095 1085
1096 1086 This may be called multiple times by Python 3 exception chaining
1097 1087 (PEP 3134).
1098 1088 """
1099 1089 # some locals
1100 1090 orig_etype = etype
1101 1091 try:
1102 1092 etype = etype.__name__
1103 1093 except AttributeError:
1104 1094 pass
1105 1095
1106 1096 tb_offset = self.tb_offset if tb_offset is None else tb_offset
1107 1097 head = self.prepare_header(etype, self.long_header)
1108 1098 records = self.get_records(etb, number_of_lines_of_context, tb_offset)
1109 1099
1110 1100 if records is None:
1111 1101 return ""
1112 1102
1113 1103 last_unique, recursion_repeat = find_recursion(orig_etype, evalue, records)
1114 1104
1115 1105 frames = self.format_records(records, last_unique, recursion_repeat)
1116 1106
1117 1107 formatted_exception = self.format_exception(etype, evalue)
1118 1108 if records:
1119 1109 filepath, lnum = records[-1][1:3]
1120 1110 filepath = os.path.abspath(filepath)
1121 1111 ipinst = get_ipython()
1122 1112 if ipinst is not None:
1123 1113 ipinst.hooks.synchronize_with_editor(filepath, lnum, 0)
1124 1114
1125 1115 return [[head] + frames + [''.join(formatted_exception[0])]]
1126 1116
1127 1117 def get_records(self, etb, number_of_lines_of_context, tb_offset):
1128 1118 try:
1129 1119 # Try the default getinnerframes and Alex's: Alex's fixes some
1130 1120 # problems, but it generates empty tracebacks for console errors
1131 1121 # (5 blanks lines) where none should be returned.
1132 1122 return _fixed_getinnerframes(etb, number_of_lines_of_context, tb_offset)
1133 1123 except UnicodeDecodeError:
1134 1124 # This can occur if a file's encoding magic comment is wrong.
1135 1125 # I can't see a way to recover without duplicating a bunch of code
1136 1126 # from the stdlib traceback module. --TK
1137 1127 error('\nUnicodeDecodeError while processing traceback.\n')
1138 1128 return None
1139 1129 except:
1140 1130 # FIXME: I've been getting many crash reports from python 2.3
1141 1131 # users, traceable to inspect.py. If I can find a small test-case
1142 1132 # to reproduce this, I should either write a better workaround or
1143 1133 # file a bug report against inspect (if that's the real problem).
1144 1134 # So far, I haven't been able to find an isolated example to
1145 1135 # reproduce the problem.
1146 1136 inspect_error()
1147 1137 traceback.print_exc(file=self.ostream)
1148 1138 info('\nUnfortunately, your original traceback can not be constructed.\n')
1149 1139 return None
1150 1140
1151 1141 def get_parts_of_chained_exception(self, evalue):
1152 1142 def get_chained_exception(exception_value):
1153 1143 cause = getattr(exception_value, '__cause__', None)
1154 1144 if cause:
1155 1145 return cause
1156 1146 if getattr(exception_value, '__suppress_context__', False):
1157 1147 return None
1158 1148 return getattr(exception_value, '__context__', None)
1159 1149
1160 1150 chained_evalue = get_chained_exception(evalue)
1161 1151
1162 1152 if chained_evalue:
1163 1153 return chained_evalue.__class__, chained_evalue, chained_evalue.__traceback__
1164 1154
1165 1155 def structured_traceback(self, etype, evalue, etb, tb_offset=None,
1166 1156 number_of_lines_of_context=5):
1167 1157 """Return a nice text document describing the traceback."""
1168 1158
1169 1159 formatted_exception = self.format_exception_as_a_whole(etype, evalue, etb, number_of_lines_of_context,
1170 1160 tb_offset)
1171 1161
1172 1162 colors = self.Colors # just a shorthand + quicker name lookup
1173 1163 colorsnormal = colors.Normal # used a lot
1174 1164 head = '%s%s%s' % (colors.topline, '-' * min(75, get_terminal_size()[0]), colorsnormal)
1175 1165 structured_traceback_parts = [head]
1176 1166 if py3compat.PY3:
1177 1167 chained_exceptions_tb_offset = 0
1178 1168 lines_of_context = 3
1179 1169 formatted_exceptions = formatted_exception
1180 1170 exception = self.get_parts_of_chained_exception(evalue)
1181 1171 if exception:
1182 1172 formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__)
1183 1173 etype, evalue, etb = exception
1184 1174 else:
1185 1175 evalue = None
1186 1176 chained_exc_ids = set()
1187 1177 while evalue:
1188 1178 formatted_exceptions += self.format_exception_as_a_whole(etype, evalue, etb, lines_of_context,
1189 1179 chained_exceptions_tb_offset)
1190 1180 exception = self.get_parts_of_chained_exception(evalue)
1191 1181
1192 1182 if exception and not id(exception[1]) in chained_exc_ids:
1193 1183 chained_exc_ids.add(id(exception[1])) # trace exception to avoid infinite 'cause' loop
1194 1184 formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__)
1195 1185 etype, evalue, etb = exception
1196 1186 else:
1197 1187 evalue = None
1198 1188
1199 1189 # we want to see exceptions in a reversed order:
1200 1190 # the first exception should be on top
1201 1191 for formatted_exception in reversed(formatted_exceptions):
1202 1192 structured_traceback_parts += formatted_exception
1203 1193 else:
1204 1194 structured_traceback_parts += formatted_exception[0]
1205 1195
1206 1196 return structured_traceback_parts
1207 1197
1208 1198 def debugger(self, force=False):
1209 1199 """Call up the pdb debugger if desired, always clean up the tb
1210 1200 reference.
1211 1201
1212 1202 Keywords:
1213 1203
1214 1204 - force(False): by default, this routine checks the instance call_pdb
1215 1205 flag and does not actually invoke the debugger if the flag is false.
1216 1206 The 'force' option forces the debugger to activate even if the flag
1217 1207 is false.
1218 1208
1219 1209 If the call_pdb flag is set, the pdb interactive debugger is
1220 1210 invoked. In all cases, the self.tb reference to the current traceback
1221 1211 is deleted to prevent lingering references which hamper memory
1222 1212 management.
1223 1213
1224 1214 Note that each call to pdb() does an 'import readline', so if your app
1225 1215 requires a special setup for the readline completers, you'll have to
1226 1216 fix that by hand after invoking the exception handler."""
1227 1217
1228 1218 if force or self.call_pdb:
1229 1219 if self.pdb is None:
1230 self.pdb = self.debugger_cls(
1231 self.color_scheme_table.active_scheme_name)
1220 self.pdb = self.debugger_cls()
1232 1221 # the system displayhook may have changed, restore the original
1233 1222 # for pdb
1234 1223 display_trap = DisplayTrap(hook=sys.__displayhook__)
1235 1224 with display_trap:
1236 1225 self.pdb.reset()
1237 1226 # Find the right frame so we don't pop up inside ipython itself
1238 1227 if hasattr(self, 'tb') and self.tb is not None:
1239 1228 etb = self.tb
1240 1229 else:
1241 1230 etb = self.tb = sys.last_traceback
1242 1231 while self.tb is not None and self.tb.tb_next is not None:
1243 1232 self.tb = self.tb.tb_next
1244 1233 if etb and etb.tb_next:
1245 1234 etb = etb.tb_next
1246 1235 self.pdb.botframe = etb.tb_frame
1247 1236 self.pdb.interaction(self.tb.tb_frame, self.tb)
1248 1237
1249 1238 if hasattr(self, 'tb'):
1250 1239 del self.tb
1251 1240
1252 1241 def handler(self, info=None):
1253 1242 (etype, evalue, etb) = info or sys.exc_info()
1254 1243 self.tb = etb
1255 1244 ostream = self.ostream
1256 1245 ostream.flush()
1257 1246 ostream.write(self.text(etype, evalue, etb))
1258 1247 ostream.write('\n')
1259 1248 ostream.flush()
1260 1249
1261 1250 # Changed so an instance can just be called as VerboseTB_inst() and print
1262 1251 # out the right info on its own.
1263 1252 def __call__(self, etype=None, evalue=None, etb=None):
1264 1253 """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
1265 1254 if etb is None:
1266 1255 self.handler()
1267 1256 else:
1268 1257 self.handler((etype, evalue, etb))
1269 1258 try:
1270 1259 self.debugger()
1271 1260 except KeyboardInterrupt:
1272 1261 print("\nKeyboardInterrupt")
1273 1262
1274 1263
1275 1264 #----------------------------------------------------------------------------
1276 1265 class FormattedTB(VerboseTB, ListTB):
1277 1266 """Subclass ListTB but allow calling with a traceback.
1278 1267
1279 1268 It can thus be used as a sys.excepthook for Python > 2.1.
1280 1269
1281 1270 Also adds 'Context' and 'Verbose' modes, not available in ListTB.
1282 1271
1283 1272 Allows a tb_offset to be specified. This is useful for situations where
1284 1273 one needs to remove a number of topmost frames from the traceback (such as
1285 1274 occurs with python programs that themselves execute other python code,
1286 1275 like Python shells). """
1287 1276
1288 1277 def __init__(self, mode='Plain', color_scheme='Linux', call_pdb=False,
1289 1278 ostream=None,
1290 1279 tb_offset=0, long_header=False, include_vars=False,
1291 1280 check_cache=None, debugger_cls=None):
1292 1281
1293 1282 # NEVER change the order of this list. Put new modes at the end:
1294 1283 self.valid_modes = ['Plain', 'Context', 'Verbose']
1295 1284 self.verbose_modes = self.valid_modes[1:3]
1296 1285
1297 1286 VerboseTB.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
1298 1287 ostream=ostream, tb_offset=tb_offset,
1299 1288 long_header=long_header, include_vars=include_vars,
1300 1289 check_cache=check_cache, debugger_cls=debugger_cls)
1301 1290
1302 1291 # Different types of tracebacks are joined with different separators to
1303 1292 # form a single string. They are taken from this dict
1304 1293 self._join_chars = dict(Plain='', Context='\n', Verbose='\n')
1305 1294 # set_mode also sets the tb_join_char attribute
1306 1295 self.set_mode(mode)
1307 1296
1308 1297 def _extract_tb(self, tb):
1309 1298 if tb:
1310 1299 return traceback.extract_tb(tb)
1311 1300 else:
1312 1301 return None
1313 1302
1314 1303 def structured_traceback(self, etype, value, tb, tb_offset=None, number_of_lines_of_context=5):
1315 1304 tb_offset = self.tb_offset if tb_offset is None else tb_offset
1316 1305 mode = self.mode
1317 1306 if mode in self.verbose_modes:
1318 1307 # Verbose modes need a full traceback
1319 1308 return VerboseTB.structured_traceback(
1320 1309 self, etype, value, tb, tb_offset, number_of_lines_of_context
1321 1310 )
1322 1311 else:
1323 1312 # We must check the source cache because otherwise we can print
1324 1313 # out-of-date source code.
1325 1314 self.check_cache()
1326 1315 # Now we can extract and format the exception
1327 1316 elist = self._extract_tb(tb)
1328 1317 return ListTB.structured_traceback(
1329 1318 self, etype, value, elist, tb_offset, number_of_lines_of_context
1330 1319 )
1331 1320
1332 1321 def stb2text(self, stb):
1333 1322 """Convert a structured traceback (a list) to a string."""
1334 1323 return self.tb_join_char.join(stb)
1335 1324
1336 1325
1337 1326 def set_mode(self, mode=None):
1338 1327 """Switch to the desired mode.
1339 1328
1340 1329 If mode is not specified, cycles through the available modes."""
1341 1330
1342 1331 if not mode:
1343 1332 new_idx = (self.valid_modes.index(self.mode) + 1 ) % \
1344 1333 len(self.valid_modes)
1345 1334 self.mode = self.valid_modes[new_idx]
1346 1335 elif mode not in self.valid_modes:
1347 1336 raise ValueError('Unrecognized mode in FormattedTB: <' + mode + '>\n'
1348 1337 'Valid modes: ' + str(self.valid_modes))
1349 1338 else:
1350 1339 self.mode = mode
1351 1340 # include variable details only in 'Verbose' mode
1352 1341 self.include_vars = (self.mode == self.valid_modes[2])
1353 1342 # Set the join character for generating text tracebacks
1354 1343 self.tb_join_char = self._join_chars[self.mode]
1355 1344
1356 1345 # some convenient shortcuts
1357 1346 def plain(self):
1358 1347 self.set_mode(self.valid_modes[0])
1359 1348
1360 1349 def context(self):
1361 1350 self.set_mode(self.valid_modes[1])
1362 1351
1363 1352 def verbose(self):
1364 1353 self.set_mode(self.valid_modes[2])
1365 1354
1366 1355
1367 1356 #----------------------------------------------------------------------------
1368 1357 class AutoFormattedTB(FormattedTB):
1369 1358 """A traceback printer which can be called on the fly.
1370 1359
1371 1360 It will find out about exceptions by itself.
1372 1361
1373 1362 A brief example::
1374 1363
1375 1364 AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
1376 1365 try:
1377 1366 ...
1378 1367 except:
1379 1368 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
1380 1369 """
1381 1370
1382 1371 def __call__(self, etype=None, evalue=None, etb=None,
1383 1372 out=None, tb_offset=None):
1384 1373 """Print out a formatted exception traceback.
1385 1374
1386 1375 Optional arguments:
1387 1376 - out: an open file-like object to direct output to.
1388 1377
1389 1378 - tb_offset: the number of frames to skip over in the stack, on a
1390 1379 per-call basis (this overrides temporarily the instance's tb_offset
1391 1380 given at initialization time. """
1392 1381
1393 1382 if out is None:
1394 1383 out = self.ostream
1395 1384 out.flush()
1396 1385 out.write(self.text(etype, evalue, etb, tb_offset))
1397 1386 out.write('\n')
1398 1387 out.flush()
1399 1388 # FIXME: we should remove the auto pdb behavior from here and leave
1400 1389 # that to the clients.
1401 1390 try:
1402 1391 self.debugger()
1403 1392 except KeyboardInterrupt:
1404 1393 print("\nKeyboardInterrupt")
1405 1394
1406 1395 def structured_traceback(self, etype=None, value=None, tb=None,
1407 1396 tb_offset=None, number_of_lines_of_context=5):
1408 1397 if etype is None:
1409 1398 etype, value, tb = sys.exc_info()
1410 1399 self.tb = tb
1411 1400 return FormattedTB.structured_traceback(
1412 1401 self, etype, value, tb, tb_offset, number_of_lines_of_context)
1413 1402
1414 1403
1415 1404 #---------------------------------------------------------------------------
1416 1405
1417 1406 # A simple class to preserve Nathan's original functionality.
1418 1407 class ColorTB(FormattedTB):
1419 1408 """Shorthand to initialize a FormattedTB in Linux colors mode."""
1420 1409
1421 1410 def __init__(self, color_scheme='Linux', call_pdb=0, **kwargs):
1422 1411 FormattedTB.__init__(self, color_scheme=color_scheme,
1423 1412 call_pdb=call_pdb, **kwargs)
1424 1413
1425 1414
1426 1415 class SyntaxTB(ListTB):
1427 1416 """Extension which holds some state: the last exception value"""
1428 1417
1429 1418 def __init__(self, color_scheme='NoColor'):
1430 1419 ListTB.__init__(self, color_scheme)
1431 1420 self.last_syntax_error = None
1432 1421
1433 1422 def __call__(self, etype, value, elist):
1434 1423 self.last_syntax_error = value
1435 1424
1436 1425 ListTB.__call__(self, etype, value, elist)
1437 1426
1438 1427 def structured_traceback(self, etype, value, elist, tb_offset=None,
1439 1428 context=5):
1440 1429 # If the source file has been edited, the line in the syntax error can
1441 1430 # be wrong (retrieved from an outdated cache). This replaces it with
1442 1431 # the current value.
1443 1432 if isinstance(value, SyntaxError) \
1444 1433 and isinstance(value.filename, py3compat.string_types) \
1445 1434 and isinstance(value.lineno, int):
1446 1435 linecache.checkcache(value.filename)
1447 1436 newtext = ulinecache.getline(value.filename, value.lineno)
1448 1437 if newtext:
1449 1438 value.text = newtext
1450 1439 self.last_syntax_error = value
1451 1440 return super(SyntaxTB, self).structured_traceback(etype, value, elist,
1452 1441 tb_offset=tb_offset, context=context)
1453 1442
1454 1443 def clear_err_state(self):
1455 1444 """Return the current error state and clear it"""
1456 1445 e = self.last_syntax_error
1457 1446 self.last_syntax_error = None
1458 1447 return e
1459 1448
1460 1449 def stb2text(self, stb):
1461 1450 """Convert a structured traceback (a list) to a string."""
1462 1451 return ''.join(stb)
1463 1452
1464 1453
1465 1454 # some internal-use functions
1466 1455 def text_repr(value):
1467 1456 """Hopefully pretty robust repr equivalent."""
1468 1457 # this is pretty horrible but should always return *something*
1469 1458 try:
1470 1459 return pydoc.text.repr(value)
1471 1460 except KeyboardInterrupt:
1472 1461 raise
1473 1462 except:
1474 1463 try:
1475 1464 return repr(value)
1476 1465 except KeyboardInterrupt:
1477 1466 raise
1478 1467 except:
1479 1468 try:
1480 1469 # all still in an except block so we catch
1481 1470 # getattr raising
1482 1471 name = getattr(value, '__name__', None)
1483 1472 if name:
1484 1473 # ick, recursion
1485 1474 return text_repr(name)
1486 1475 klass = getattr(value, '__class__', None)
1487 1476 if klass:
1488 1477 return '%s instance' % text_repr(klass)
1489 1478 except KeyboardInterrupt:
1490 1479 raise
1491 1480 except:
1492 1481 return 'UNRECOVERABLE REPR FAILURE'
1493 1482
1494 1483
1495 1484 def eqrepr(value, repr=text_repr):
1496 1485 return '=%s' % repr(value)
1497 1486
1498 1487
1499 1488 def nullrepr(value, repr=text_repr):
1500 1489 return ''
@@ -1,382 +1,332 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 Class and program to colorize python source code for ANSI terminals.
4 4
5 5 Based on an HTML code highlighter by Jurgen Hermann found at:
6 6 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52298
7 7
8 8 Modifications by Fernando Perez (fperez@colorado.edu).
9 9
10 10 Information on the original HTML highlighter follows:
11 11
12 12 MoinMoin - Python Source Parser
13 13
14 14 Title: Colorize Python source using the built-in tokenizer
15 15
16 16 Submitter: Jurgen Hermann
17 17 Last Updated:2001/04/06
18 18
19 19 Version no:1.2
20 20
21 21 Description:
22 22
23 23 This code is part of MoinMoin (http://moin.sourceforge.net/) and converts
24 24 Python source code to HTML markup, rendering comments, keywords,
25 25 operators, numeric and string literals in different colors.
26 26
27 27 It shows how to use the built-in keyword, token and tokenize modules to
28 28 scan Python source code and re-emit it with no changes to its original
29 29 formatting (which is the hard part).
30 30 """
31 31 from __future__ import print_function
32 32 from __future__ import absolute_import
33 33 from __future__ import unicode_literals
34 34
35 35 __all__ = ['ANSICodeColors','Parser']
36 36
37 37 _scheme_default = 'Linux'
38 38
39 39
40 40 # Imports
41 41 import keyword
42 42 import os
43 43 import sys
44 44 import token
45 45 import tokenize
46 46
47 47 try:
48 48 generate_tokens = tokenize.generate_tokens
49 49 except AttributeError:
50 50 # Python 3. Note that we use the undocumented _tokenize because it expects
51 51 # strings, not bytes. See also Python issue #9969.
52 52 generate_tokens = tokenize._tokenize
53 53
54 54 from IPython.utils.coloransi import TermColors, InputTermColors ,ColorScheme, ColorSchemeTable
55 55 from IPython.utils.py3compat import PY3
56 56
57 57 from .colorable import Colorable
58 58
59 59 if PY3:
60 60 from io import StringIO
61 61 else:
62 62 from StringIO import StringIO
63 63
64 64 #############################################################################
65 65 ### Python Source Parser (does Hilighting)
66 66 #############################################################################
67 67
68 68 _KEYWORD = token.NT_OFFSET + 1
69 69 _TEXT = token.NT_OFFSET + 2
70 70
71 71 #****************************************************************************
72 72 # Builtin color schemes
73 73
74 74 Colors = TermColors # just a shorthand
75 75
76 76 # Build a few color schemes
77 77 NoColor = ColorScheme(
78 78 'NoColor',{
79 79 'header' : Colors.NoColor,
80 80 token.NUMBER : Colors.NoColor,
81 81 token.OP : Colors.NoColor,
82 82 token.STRING : Colors.NoColor,
83 83 tokenize.COMMENT : Colors.NoColor,
84 84 token.NAME : Colors.NoColor,
85 85 token.ERRORTOKEN : Colors.NoColor,
86 86
87 87 _KEYWORD : Colors.NoColor,
88 88 _TEXT : Colors.NoColor,
89 89
90 90 'in_prompt' : InputTermColors.NoColor, # Input prompt
91 91 'in_number' : InputTermColors.NoColor, # Input prompt number
92 92 'in_prompt2' : InputTermColors.NoColor, # Continuation prompt
93 93 'in_normal' : InputTermColors.NoColor, # color off (usu. Colors.Normal)
94 94
95 95 'out_prompt' : Colors.NoColor, # Output prompt
96 96 'out_number' : Colors.NoColor, # Output prompt number
97 97
98 98 'normal' : Colors.NoColor # color off (usu. Colors.Normal)
99 99 } )
100 100
101 101 LinuxColors = ColorScheme(
102 102 'Linux',{
103 103 'header' : Colors.LightRed,
104 104 token.NUMBER : Colors.LightCyan,
105 105 token.OP : Colors.Yellow,
106 106 token.STRING : Colors.LightBlue,
107 107 tokenize.COMMENT : Colors.LightRed,
108 108 token.NAME : Colors.Normal,
109 109 token.ERRORTOKEN : Colors.Red,
110 110
111 111 _KEYWORD : Colors.LightGreen,
112 112 _TEXT : Colors.Yellow,
113 113
114 114 'in_prompt' : InputTermColors.Green,
115 115 'in_number' : InputTermColors.LightGreen,
116 116 'in_prompt2' : InputTermColors.Green,
117 117 'in_normal' : InputTermColors.Normal, # color off (usu. Colors.Normal)
118 118
119 119 'out_prompt' : Colors.Red,
120 120 'out_number' : Colors.LightRed,
121 121
122 122 'normal' : Colors.Normal # color off (usu. Colors.Normal)
123 123 } )
124 124
125 125 NeutralColors = ColorScheme(
126 126 'Neutral',{
127 127 'header' : Colors.Red,
128 128 token.NUMBER : Colors.Cyan,
129 129 token.OP : Colors.Blue,
130 130 token.STRING : Colors.Blue,
131 131 tokenize.COMMENT : Colors.Red,
132 132 token.NAME : Colors.Normal,
133 133 token.ERRORTOKEN : Colors.Red,
134 134
135 135 _KEYWORD : Colors.Green,
136 136 _TEXT : Colors.Blue,
137 137
138 138 'in_prompt' : InputTermColors.Blue,
139 139 'in_number' : InputTermColors.LightBlue,
140 140 'in_prompt2' : InputTermColors.Blue,
141 141 'in_normal' : InputTermColors.Normal, # color off (usu. Colors.Normal)
142 142
143 143 'out_prompt' : Colors.Red,
144 144 'out_number' : Colors.LightRed,
145 145
146 146 'normal' : Colors.Normal # color off (usu. Colors.Normal)
147 147 } )
148 148
149 149 # Hack: the 'neutral' colours are not very visible on a dark background on
150 150 # Windows. Since Windows command prompts have a dark background by default, and
151 151 # relatively few users are likely to alter that, we will use the 'Linux' colours,
152 152 # designed for a dark background, as the default on Windows. Changing it here
153 153 # avoids affecting the prompt colours rendered by prompt_toolkit, where the
154 154 # neutral defaults do work OK.
155 155
156 156 if os.name == 'nt':
157 157 NeutralColors = LinuxColors.copy(name='Neutral')
158 158
159 159 LightBGColors = ColorScheme(
160 160 'LightBG',{
161 161 'header' : Colors.Red,
162 162 token.NUMBER : Colors.Cyan,
163 163 token.OP : Colors.Blue,
164 164 token.STRING : Colors.Blue,
165 165 tokenize.COMMENT : Colors.Red,
166 166 token.NAME : Colors.Normal,
167 167 token.ERRORTOKEN : Colors.Red,
168 168
169 169
170 170 _KEYWORD : Colors.Green,
171 171 _TEXT : Colors.Blue,
172 172
173 173 'in_prompt' : InputTermColors.Blue,
174 174 'in_number' : InputTermColors.LightBlue,
175 175 'in_prompt2' : InputTermColors.Blue,
176 176 'in_normal' : InputTermColors.Normal, # color off (usu. Colors.Normal)
177 177
178 178 'out_prompt' : Colors.Red,
179 179 'out_number' : Colors.LightRed,
180 180
181 181 'normal' : Colors.Normal # color off (usu. Colors.Normal)
182 182 } )
183 183
184 184 # Build table of color schemes (needed by the parser)
185 185 ANSICodeColors = ColorSchemeTable([NoColor,LinuxColors,LightBGColors, NeutralColors],
186 186 _scheme_default)
187 187
188 Undefined = object()
189
188 190 class Parser(Colorable):
189 191 """ Format colored Python source.
190 192 """
191 193
192 194 def __init__(self, color_table=None, out = sys.stdout, parent=None, style=None):
193 195 """ Create a parser with a specified color table and output channel.
194 196
195 197 Call format() to process code.
196 198 """
197 199
198 200 super(Parser, self).__init__(parent=parent)
199 201
200 202 self.color_table = color_table and color_table or ANSICodeColors
201 203 self.out = out
204 if not style:
205 self.style = self.default_style
206 else:
207 self.style = style
208
202 209
203 def format(self, raw, out = None, scheme = ''):
204 return self.format2(raw, out, scheme)[0]
210 def format(self, raw, out=None, scheme=Undefined):
211 import warnings
212 if scheme is not Undefined:
213 warnings.warn('The `scheme` argument of IPython.utils.PyColorize:Parser.format is deprecated since IPython 6.0.'
214 'It will have no effect. Set the parser `style` directly.',
215 stacklevel=2)
216 return self.format2(raw, out)[0]
205 217
206 def format2(self, raw, out = None, scheme = ''):
218 def format2(self, raw, out = None):
207 219 """ Parse and send the colored source.
208 220
209 221 If out and scheme are not specified, the defaults (given to
210 222 constructor) are used.
211 223
212 224 out should be a file-type object. Optionally, out can be given as the
213 225 string 'str' and the parser will automatically return the output in a
214 226 string."""
215 227
216 228 string_output = 0
217 229 if out == 'str' or self.out == 'str' or \
218 230 isinstance(self.out,StringIO):
219 231 # XXX - I don't really like this state handling logic, but at this
220 232 # point I don't want to make major changes, so adding the
221 233 # isinstance() check is the simplest I can do to ensure correct
222 234 # behavior.
223 235 out_old = self.out
224 236 self.out = StringIO()
225 237 string_output = 1
226 238 elif out is not None:
227 239 self.out = out
228 240
229 241 # Fast return of the unmodified input for NoColor scheme
230 if scheme == 'NoColor':
242 if self.style == 'NoColor':
231 243 error = False
232 244 self.out.write(raw)
233 245 if string_output:
234 246 return raw,error
235 247 else:
236 248 return None,error
237 249
238 250 # local shorthands
239 colors = self.color_table[scheme].colors
251 colors = self.color_table[self.style].colors
240 252 self.colors = colors # put in object so __call__ sees it
241 253
242 254 # Remove trailing whitespace and normalize tabs
243 255 self.raw = raw.expandtabs().rstrip()
244 256
245 257 # store line offsets in self.lines
246 258 self.lines = [0, 0]
247 259 pos = 0
248 260 raw_find = self.raw.find
249 261 lines_append = self.lines.append
250 262 while 1:
251 263 pos = raw_find('\n', pos) + 1
252 264 if not pos: break
253 265 lines_append(pos)
254 266 lines_append(len(self.raw))
255 267
256 268 # parse the source and write it
257 269 self.pos = 0
258 270 text = StringIO(self.raw)
259 271
260 272 error = False
261 273 try:
262 274 for atoken in generate_tokens(text.readline):
263 275 self(*atoken)
264 276 except tokenize.TokenError as ex:
265 277 msg = ex.args[0]
266 278 line = ex.args[1][0]
267 279 self.out.write("%s\n\n*** ERROR: %s%s%s\n" %
268 280 (colors[token.ERRORTOKEN],
269 281 msg, self.raw[self.lines[line]:],
270 282 colors.normal)
271 283 )
272 284 error = True
273 285 self.out.write(colors.normal+'\n')
274 286 if string_output:
275 287 output = self.out.getvalue()
276 288 self.out = out_old
277 289 return (output, error)
278 290 return (None, error)
279 291
280 292 def __call__(self, toktype, toktext, start_pos, end_pos, line):
281 293 """ Token handler, with syntax highlighting."""
282 294 (srow,scol) = start_pos
283 295 (erow,ecol) = end_pos
284 296 colors = self.colors
285 297 owrite = self.out.write
286 298
287 299 # line separator, so this works across platforms
288 300 linesep = os.linesep
289 301
290 302 # calculate new positions
291 303 oldpos = self.pos
292 304 newpos = self.lines[srow] + scol
293 305 self.pos = newpos + len(toktext)
294 306
295 307 # send the original whitespace, if needed
296 308 if newpos > oldpos:
297 309 owrite(self.raw[oldpos:newpos])
298 310
299 311 # skip indenting tokens
300 312 if toktype in [token.INDENT, token.DEDENT]:
301 313 self.pos = newpos
302 314 return
303 315
304 316 # map token type to a color group
305 317 if token.LPAR <= toktype <= token.OP:
306 318 toktype = token.OP
307 319 elif toktype == token.NAME and keyword.iskeyword(toktext):
308 320 toktype = _KEYWORD
309 321 color = colors.get(toktype, colors[_TEXT])
310 322
311 323 #print '<%s>' % toktext, # dbg
312 324
313 325 # Triple quoted strings must be handled carefully so that backtracking
314 326 # in pagers works correctly. We need color terminators on _each_ line.
315 327 if linesep in toktext:
316 328 toktext = toktext.replace(linesep, '%s%s%s' %
317 329 (colors.normal,linesep,color))
318 330
319 331 # send text
320 332 owrite('%s%s%s' % (color,toktext,colors.normal))
321
322 def main(argv=None):
323 """Run as a command-line script: colorize a python file or stdin using ANSI
324 color escapes and print to stdout.
325
326 Inputs:
327
328 - argv(None): a list of strings like sys.argv[1:] giving the command-line
329 arguments. If None, use sys.argv[1:].
330 """
331
332 usage_msg = """%prog [options] [filename]
333
334 Colorize a python file or stdin using ANSI color escapes and print to stdout.
335 If no filename is given, or if filename is -, read standard input."""
336
337 import optparse
338 parser = optparse.OptionParser(usage=usage_msg)
339 newopt = parser.add_option
340 newopt('-s','--scheme',metavar='NAME',dest='scheme_name',action='store',
341 choices=['Linux','LightBG','NoColor'],default=_scheme_default,
342 help="give the color scheme to use. Currently only 'Linux'\
343 (default) and 'LightBG' and 'NoColor' are implemented (give without\
344 quotes)")
345
346 opts,args = parser.parse_args(argv)
347
348 if len(args) > 1:
349 parser.error("you must give at most one filename.")
350
351 if len(args) == 0:
352 fname = '-' # no filename given; setup to read from stdin
353 else:
354 fname = args[0]
355
356 if fname == '-':
357 stream = sys.stdin
358 else:
359 try:
360 stream = open(fname)
361 except IOError as msg:
362 print(msg, file=sys.stderr)
363 sys.exit(1)
364
365 parser = Parser()
366
367 # we need nested try blocks because pre-2.5 python doesn't support unified
368 # try-except-finally
369 try:
370 try:
371 # write colorized version to stdout
372 parser.format(stream.read(),scheme=opts.scheme_name)
373 except IOError as msg:
374 # if user reads through a pager and quits, don't print traceback
375 if msg.args != (32,'Broken pipe'):
376 raise
377 finally:
378 if stream is not sys.stdin:
379 stream.close() # in case a non-handled exception happened above
380
381 if __name__ == "__main__":
382 main()
@@ -1,26 +1,26 b''
1 1 #*****************************************************************************
2 2 # Copyright (C) 2016 The IPython Team <ipython-dev@scipy.org>
3 3 #
4 4 # Distributed under the terms of the BSD License. The full license is in
5 5 # the file COPYING, distributed as part of this software.
6 6 #*****************************************************************************
7 7 from __future__ import absolute_import
8 8
9 9 """
10 10 Color managing related utilities
11 11 """
12 12
13 13 import pygments
14 14
15 15 from traitlets.config import Configurable
16 16 from traitlets import Unicode
17 17
18 18
19 19 available_themes = lambda : [s for s in pygments.styles.get_all_styles()]+['NoColor','LightBG','Linux', 'Neutral']
20 20
21 21 class Colorable(Configurable):
22 22 """
23 23 A subclass of configurable for all the classes that have a `default_scheme`
24 24 """
25 default_style=Unicode('lightbg').tag(config=True)
25 default_style=Unicode('LightBG').tag(config=True)
26 26
@@ -1,78 +1,78 b''
1 1 # coding: utf-8
2 2 """Test suite for our color utilities.
3 3
4 4 Authors
5 5 -------
6 6
7 7 * Min RK
8 8 """
9 9 #-----------------------------------------------------------------------------
10 10 # Copyright (C) 2011 The IPython Development Team
11 11 #
12 12 # Distributed under the terms of the BSD License. The full license is in
13 13 # the file COPYING.txt, distributed as part of this software.
14 14 #-----------------------------------------------------------------------------
15 15
16 16 #-----------------------------------------------------------------------------
17 17 # Imports
18 18 #-----------------------------------------------------------------------------
19 19
20 20 # third party
21 21 import nose.tools as nt
22 22
23 23 # our own
24 24 from IPython.utils.PyColorize import Parser
25 25 import io
26 26
27 27 #-----------------------------------------------------------------------------
28 28 # Test functions
29 29 #-----------------------------------------------------------------------------
30 30
31 31 sample = u"""
32 32 def function(arg, *args, kwarg=True, **kwargs):
33 33 '''
34 34 this is docs
35 35 '''
36 36 pass is True
37 37 False == None
38 38
39 39 with io.open(ru'unicode'):
40 40 raise ValueError("\n escape \r sequence")
41 41
42 42 print("wΔ›ird ΓΌnicoΓ°e")
43 43
44 44 class Bar(Super):
45 45
46 46 def __init__(self):
47 47 super(Bar, self).__init__(1**2, 3^4, 5 or 6)
48 48 """
49 49
50 50 def test_loop_colors():
51 51
52 for scheme in ('Linux', 'NoColor','LightBG', 'Neutral'):
52 for style in ('Linux', 'NoColor','LightBG', 'Neutral'):
53 53
54 54 def test_unicode_colorize():
55 p = Parser()
56 f1 = p.format('1/0', 'str', scheme=scheme)
57 f2 = p.format(u'1/0', 'str', scheme=scheme)
55 p = Parser(style=style)
56 f1 = p.format('1/0', 'str')
57 f2 = p.format(u'1/0', 'str')
58 58 nt.assert_equal(f1, f2)
59 59
60 60 def test_parse_sample():
61 61 """and test writing to a buffer"""
62 62 buf = io.StringIO()
63 p = Parser()
64 p.format(sample, buf, scheme=scheme)
63 p = Parser(style=style)
64 p.format(sample, buf)
65 65 buf.seek(0)
66 66 f1 = buf.read()
67 67
68 68 nt.assert_not_in('ERROR', f1)
69 69
70 70 def test_parse_error():
71 p = Parser()
72 f1 = p.format(')', 'str', scheme=scheme)
73 if scheme != 'NoColor':
71 p = Parser(style=style)
72 f1 = p.format(')', 'str')
73 if style != 'NoColor':
74 74 nt.assert_in('ERROR', f1)
75 75
76 76 yield test_unicode_colorize
77 77 yield test_parse_sample
78 78 yield test_parse_error
General Comments 0
You need to be logged in to leave comments. Login now