##// END OF EJS Templates
Reapply our monkeypatch to inspect.findsource()....
Thomas Kluyver -
Show More
@@ -1,1245 +1,1238 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 ultratb.py -- Spice up your tracebacks!
4 4
5 5 * ColorTB
6 6 I've always found it a bit hard to visually parse tracebacks in Python. The
7 7 ColorTB class is a solution to that problem. It colors the different parts of a
8 8 traceback in a manner similar to what you would expect from a syntax-highlighting
9 9 text editor.
10 10
11 11 Installation instructions for ColorTB:
12 12 import sys,ultratb
13 13 sys.excepthook = ultratb.ColorTB()
14 14
15 15 * VerboseTB
16 16 I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds
17 17 of useful info when a traceback occurs. Ping originally had it spit out HTML
18 18 and intended it for CGI programmers, but why should they have all the fun? I
19 19 altered it to spit out colored text to the terminal. It's a bit overwhelming,
20 20 but kind of neat, and maybe useful for long-running programs that you believe
21 21 are bug-free. If a crash *does* occur in that type of program you want details.
22 22 Give it a shot--you'll love it or you'll hate it.
23 23
24 24 Note:
25 25
26 26 The Verbose mode prints the variables currently visible where the exception
27 27 happened (shortening their strings if too long). This can potentially be
28 28 very slow, if you happen to have a huge data structure whose string
29 29 representation is complex to compute. Your computer may appear to freeze for
30 30 a while with cpu usage at 100%. If this occurs, you can cancel the traceback
31 31 with Ctrl-C (maybe hitting it more than once).
32 32
33 33 If you encounter this kind of situation often, you may want to use the
34 34 Verbose_novars mode instead of the regular Verbose, which avoids formatting
35 35 variables (but otherwise includes the information and context given by
36 36 Verbose).
37 37
38 38
39 39 Installation instructions for ColorTB:
40 40 import sys,ultratb
41 41 sys.excepthook = ultratb.VerboseTB()
42 42
43 43 Note: Much of the code in this module was lifted verbatim from the standard
44 44 library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'.
45 45
46 46 * Color schemes
47 47 The colors are defined in the class TBTools through the use of the
48 48 ColorSchemeTable class. Currently the following exist:
49 49
50 50 - NoColor: allows all of this module to be used in any terminal (the color
51 51 escapes are just dummy blank strings).
52 52
53 53 - Linux: is meant to look good in a terminal like the Linux console (black
54 54 or very dark background).
55 55
56 56 - LightBG: similar to Linux but swaps dark/light colors to be more readable
57 57 in light background terminals.
58 58
59 59 You can implement other color schemes easily, the syntax is fairly
60 60 self-explanatory. Please send back new schemes you develop to the author for
61 61 possible inclusion in future releases.
62 62 """
63 63
64 64 #*****************************************************************************
65 65 # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
66 66 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
67 67 #
68 68 # Distributed under the terms of the BSD License. The full license is in
69 69 # the file COPYING, distributed as part of this software.
70 70 #*****************************************************************************
71 71
72 72 from __future__ import with_statement
73 73
74 74 import inspect
75 75 import keyword
76 76 import linecache
77 77 import os
78 78 import pydoc
79 79 import re
80 80 import sys
81 81 import time
82 82 import tokenize
83 83 import traceback
84 84 import types
85 85
86 86 try: # Python 2
87 87 generate_tokens = tokenize.generate_tokens
88 88 except AttributeError: # Python 3
89 89 generate_tokens = tokenize.tokenize
90 90
91 91 # For purposes of monkeypatching inspect to fix a bug in it.
92 92 from inspect import getsourcefile, getfile, getmodule,\
93 93 ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode
94 94
95 95 # IPython's own modules
96 96 # Modified pdb which doesn't damage IPython's readline handling
97 97 from IPython.core import debugger, ipapi
98 98 from IPython.core.display_trap import DisplayTrap
99 99 from IPython.core.excolors import exception_colors
100 100 from IPython.utils import PyColorize
101 101 from IPython.utils import io
102 102 from IPython.utils import py3compat
103 103 from IPython.utils import pyfile
104 104 from IPython.utils.data import uniq_stable
105 105 from IPython.utils.warn import info, error
106 106
107 107 # Globals
108 108 # amount of space to put line numbers before verbose tracebacks
109 109 INDENT_SIZE = 8
110 110
111 111 # Default color scheme. This is used, for example, by the traceback
112 112 # formatter. When running in an actual IPython instance, the user's rc.colors
113 113 # value is used, but havinga module global makes this functionality available
114 114 # to users of ultratb who are NOT running inside ipython.
115 115 DEFAULT_SCHEME = 'NoColor'
116 116
117 117 #---------------------------------------------------------------------------
118 118 # Code begins
119 119
120 120 # Utility functions
121 121 def inspect_error():
122 122 """Print a message about internal inspect errors.
123 123
124 124 These are unfortunately quite common."""
125 125
126 126 error('Internal Python error in the inspect module.\n'
127 127 'Below is the traceback from this internal error.\n')
128 128
129
130 # N.B. This function is a monkeypatch we are currently not applying.
131 # It was written some time ago, to fix an apparent Python bug with
132 # codeobj.co_firstlineno . Unfortunately, we don't know under what conditions
133 # the bug occurred, so we can't tell if it has been fixed. If it reappears, we
134 # will apply the monkeypatch again. Also, note that findsource() is not called
135 # by our code at this time - we don't know if it was when the monkeypatch was
136 # written, or if the monkeypatch is needed for some other code (like a debugger).
137 # For the discussion about not applying it, see gh-1229. TK, Jan 2011.
129 # This function is a monkeypatch we apply to the Python inspect module. We have
130 # now found when it's needed (see discussion on issue gh-1456), and we have a
131 # test case (IPython.core.tests.test_ultratb.ChangedPyFileTest) that fails if
132 # the monkeypatch is not applied. TK, Aug 2012.
138 133 def findsource(object):
139 134 """Return the entire source file and starting line number for an object.
140 135
141 136 The argument may be a module, class, method, function, traceback, frame,
142 137 or code object. The source code is returned as a list of all the lines
143 138 in the file and the line number indexes a line in that list. An IOError
144 139 is raised if the source code cannot be retrieved.
145 140
146 141 FIXED version with which we monkeypatch the stdlib to work around a bug."""
147 142
148 143 file = getsourcefile(object) or getfile(object)
149 144 # If the object is a frame, then trying to get the globals dict from its
150 145 # module won't work. Instead, the frame object itself has the globals
151 146 # dictionary.
152 147 globals_dict = None
153 148 if inspect.isframe(object):
154 149 # XXX: can this ever be false?
155 150 globals_dict = object.f_globals
156 151 else:
157 152 module = getmodule(object, file)
158 153 if module:
159 154 globals_dict = module.__dict__
160 155 lines = linecache.getlines(file, globals_dict)
161 156 if not lines:
162 157 raise IOError('could not get source code')
163 158
164 159 if ismodule(object):
165 160 return lines, 0
166 161
167 162 if isclass(object):
168 163 name = object.__name__
169 164 pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
170 165 # make some effort to find the best matching class definition:
171 166 # use the one with the least indentation, which is the one
172 167 # that's most probably not inside a function definition.
173 168 candidates = []
174 169 for i in range(len(lines)):
175 170 match = pat.match(lines[i])
176 171 if match:
177 172 # if it's at toplevel, it's already the best one
178 173 if lines[i][0] == 'c':
179 174 return lines, i
180 175 # else add whitespace to candidate list
181 176 candidates.append((match.group(1), i))
182 177 if candidates:
183 178 # this will sort by whitespace, and by line number,
184 179 # less whitespace first
185 180 candidates.sort()
186 181 return lines, candidates[0][1]
187 182 else:
188 183 raise IOError('could not find class definition')
189 184
190 185 if ismethod(object):
191 186 object = object.im_func
192 187 if isfunction(object):
193 188 object = object.func_code
194 189 if istraceback(object):
195 190 object = object.tb_frame
196 191 if isframe(object):
197 192 object = object.f_code
198 193 if iscode(object):
199 194 if not hasattr(object, 'co_firstlineno'):
200 195 raise IOError('could not find function definition')
201 196 pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
202 197 pmatch = pat.match
203 198 # fperez - fix: sometimes, co_firstlineno can give a number larger than
204 199 # the length of lines, which causes an error. Safeguard against that.
205 200 lnum = min(object.co_firstlineno,len(lines))-1
206 201 while lnum > 0:
207 202 if pmatch(lines[lnum]): break
208 203 lnum -= 1
209 204
210 205 return lines, lnum
211 206 raise IOError('could not find code object')
212 207
213 # Not applying the monkeypatch - see above the function for details. TK, Jan 2012
214 # Monkeypatch inspect to apply our bugfix. This code only works with py25
215 #if sys.version_info[:2] >= (2,5):
216 # inspect.findsource = findsource
208 # Monkeypatch inspect to apply our bugfix. This code only works with Python >= 2.5
209 inspect.findsource = findsource
217 210
218 211 def fix_frame_records_filenames(records):
219 212 """Try to fix the filenames in each record from inspect.getinnerframes().
220 213
221 214 Particularly, modules loaded from within zip files have useless filenames
222 215 attached to their code object, and inspect.getinnerframes() just uses it.
223 216 """
224 217 fixed_records = []
225 218 for frame, filename, line_no, func_name, lines, index in records:
226 219 # Look inside the frame's globals dictionary for __file__, which should
227 220 # be better.
228 221 better_fn = frame.f_globals.get('__file__', None)
229 222 if isinstance(better_fn, str):
230 223 # Check the type just in case someone did something weird with
231 224 # __file__. It might also be None if the error occurred during
232 225 # import.
233 226 filename = better_fn
234 227 fixed_records.append((frame, filename, line_no, func_name, lines, index))
235 228 return fixed_records
236 229
237 230
238 231 def _fixed_getinnerframes(etb, context=1,tb_offset=0):
239 232 import linecache
240 233 LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5
241 234
242 235 records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
243 236
244 237 # If the error is at the console, don't build any context, since it would
245 238 # otherwise produce 5 blank lines printed out (there is no file at the
246 239 # console)
247 240 rec_check = records[tb_offset:]
248 241 try:
249 242 rname = rec_check[0][1]
250 243 if rname == '<ipython console>' or rname.endswith('<string>'):
251 244 return rec_check
252 245 except IndexError:
253 246 pass
254 247
255 248 aux = traceback.extract_tb(etb)
256 249 assert len(records) == len(aux)
257 250 for i, (file, lnum, _, _) in zip(range(len(records)), aux):
258 251 maybeStart = lnum-1 - context//2
259 252 start = max(maybeStart, 0)
260 253 end = start + context
261 254 lines = linecache.getlines(file)[start:end]
262 255 buf = list(records[i])
263 256 buf[LNUM_POS] = lnum
264 257 buf[INDEX_POS] = lnum - 1 - start
265 258 buf[LINES_POS] = lines
266 259 records[i] = tuple(buf)
267 260 return records[tb_offset:]
268 261
269 262 # Helper function -- largely belongs to VerboseTB, but we need the same
270 263 # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they
271 264 # can be recognized properly by ipython.el's py-traceback-line-re
272 265 # (SyntaxErrors have to be treated specially because they have no traceback)
273 266
274 267 _parser = PyColorize.Parser()
275 268
276 269 def _format_traceback_lines(lnum, index, lines, Colors, lvals=None,scheme=None):
277 270 numbers_width = INDENT_SIZE - 1
278 271 res = []
279 272 i = lnum - index
280 273
281 274 # This lets us get fully syntax-highlighted tracebacks.
282 275 if scheme is None:
283 276 ipinst = ipapi.get()
284 277 if ipinst is not None:
285 278 scheme = ipinst.colors
286 279 else:
287 280 scheme = DEFAULT_SCHEME
288 281
289 282 _line_format = _parser.format2
290 283
291 284 for line in lines:
292 285 # FIXME: we need to ensure the source is a pure string at this point,
293 286 # else the coloring code makes a royal mess. This is in need of a
294 287 # serious refactoring, so that all of the ultratb and PyColorize code
295 288 # is unicode-safe. So for now this is rather an ugly hack, but
296 289 # necessary to at least have readable tracebacks. Improvements welcome!
297 290 line = py3compat.cast_bytes_py2(line, 'utf-8')
298 291
299 292 new_line, err = _line_format(line, 'str', scheme)
300 293 if not err: line = new_line
301 294
302 295 if i == lnum:
303 296 # This is the line with the error
304 297 pad = numbers_width - len(str(i))
305 298 if pad >= 3:
306 299 marker = '-'*(pad-3) + '-> '
307 300 elif pad == 2:
308 301 marker = '> '
309 302 elif pad == 1:
310 303 marker = '>'
311 304 else:
312 305 marker = ''
313 306 num = marker + str(i)
314 307 line = '%s%s%s %s%s' %(Colors.linenoEm, num,
315 308 Colors.line, line, Colors.Normal)
316 309 else:
317 310 num = '%*s' % (numbers_width,i)
318 311 line = '%s%s%s %s' %(Colors.lineno, num,
319 312 Colors.Normal, line)
320 313
321 314 res.append(line)
322 315 if lvals and i == lnum:
323 316 res.append(lvals + '\n')
324 317 i = i + 1
325 318 return res
326 319
327 320
328 321 #---------------------------------------------------------------------------
329 322 # Module classes
330 323 class TBTools(object):
331 324 """Basic tools used by all traceback printer classes."""
332 325
333 326 # Number of frames to skip when reporting tracebacks
334 327 tb_offset = 0
335 328
336 329 def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None):
337 330 # Whether to call the interactive pdb debugger after printing
338 331 # tracebacks or not
339 332 self.call_pdb = call_pdb
340 333
341 334 # Output stream to write to. Note that we store the original value in
342 335 # a private attribute and then make the public ostream a property, so
343 336 # that we can delay accessing io.stdout until runtime. The way
344 337 # things are written now, the io.stdout object is dynamically managed
345 338 # so a reference to it should NEVER be stored statically. This
346 339 # property approach confines this detail to a single location, and all
347 340 # subclasses can simply access self.ostream for writing.
348 341 self._ostream = ostream
349 342
350 343 # Create color table
351 344 self.color_scheme_table = exception_colors()
352 345
353 346 self.set_colors(color_scheme)
354 347 self.old_scheme = color_scheme # save initial value for toggles
355 348
356 349 if call_pdb:
357 350 self.pdb = debugger.Pdb(self.color_scheme_table.active_scheme_name)
358 351 else:
359 352 self.pdb = None
360 353
361 354 def _get_ostream(self):
362 355 """Output stream that exceptions are written to.
363 356
364 357 Valid values are:
365 358
366 359 - None: the default, which means that IPython will dynamically resolve
367 360 to io.stdout. This ensures compatibility with most tools, including
368 361 Windows (where plain stdout doesn't recognize ANSI escapes).
369 362
370 363 - Any object with 'write' and 'flush' attributes.
371 364 """
372 365 return io.stdout if self._ostream is None else self._ostream
373 366
374 367 def _set_ostream(self, val):
375 368 assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush'))
376 369 self._ostream = val
377 370
378 371 ostream = property(_get_ostream, _set_ostream)
379 372
380 373 def set_colors(self,*args,**kw):
381 374 """Shorthand access to the color table scheme selector method."""
382 375
383 376 # Set own color table
384 377 self.color_scheme_table.set_active_scheme(*args,**kw)
385 378 # for convenience, set Colors to the active scheme
386 379 self.Colors = self.color_scheme_table.active_colors
387 380 # Also set colors of debugger
388 381 if hasattr(self,'pdb') and self.pdb is not None:
389 382 self.pdb.set_colors(*args,**kw)
390 383
391 384 def color_toggle(self):
392 385 """Toggle between the currently active color scheme and NoColor."""
393 386
394 387 if self.color_scheme_table.active_scheme_name == 'NoColor':
395 388 self.color_scheme_table.set_active_scheme(self.old_scheme)
396 389 self.Colors = self.color_scheme_table.active_colors
397 390 else:
398 391 self.old_scheme = self.color_scheme_table.active_scheme_name
399 392 self.color_scheme_table.set_active_scheme('NoColor')
400 393 self.Colors = self.color_scheme_table.active_colors
401 394
402 395 def stb2text(self, stb):
403 396 """Convert a structured traceback (a list) to a string."""
404 397 return '\n'.join(stb)
405 398
406 399 def text(self, etype, value, tb, tb_offset=None, context=5):
407 400 """Return formatted traceback.
408 401
409 402 Subclasses may override this if they add extra arguments.
410 403 """
411 404 tb_list = self.structured_traceback(etype, value, tb,
412 405 tb_offset, context)
413 406 return self.stb2text(tb_list)
414 407
415 408 def structured_traceback(self, etype, evalue, tb, tb_offset=None,
416 409 context=5, mode=None):
417 410 """Return a list of traceback frames.
418 411
419 412 Must be implemented by each class.
420 413 """
421 414 raise NotImplementedError()
422 415
423 416
424 417 #---------------------------------------------------------------------------
425 418 class ListTB(TBTools):
426 419 """Print traceback information from a traceback list, with optional color.
427 420
428 421 Calling: requires 3 arguments:
429 422 (etype, evalue, elist)
430 423 as would be obtained by:
431 424 etype, evalue, tb = sys.exc_info()
432 425 if tb:
433 426 elist = traceback.extract_tb(tb)
434 427 else:
435 428 elist = None
436 429
437 430 It can thus be used by programs which need to process the traceback before
438 431 printing (such as console replacements based on the code module from the
439 432 standard library).
440 433
441 434 Because they are meant to be called without a full traceback (only a
442 435 list), instances of this class can't call the interactive pdb debugger."""
443 436
444 437 def __init__(self,color_scheme = 'NoColor', call_pdb=False, ostream=None):
445 438 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
446 439 ostream=ostream)
447 440
448 441 def __call__(self, etype, value, elist):
449 442 self.ostream.flush()
450 443 self.ostream.write(self.text(etype, value, elist))
451 444 self.ostream.write('\n')
452 445
453 446 def structured_traceback(self, etype, value, elist, tb_offset=None,
454 447 context=5):
455 448 """Return a color formatted string with the traceback info.
456 449
457 450 Parameters
458 451 ----------
459 452 etype : exception type
460 453 Type of the exception raised.
461 454
462 455 value : object
463 456 Data stored in the exception
464 457
465 458 elist : list
466 459 List of frames, see class docstring for details.
467 460
468 461 tb_offset : int, optional
469 462 Number of frames in the traceback to skip. If not given, the
470 463 instance value is used (set in constructor).
471 464
472 465 context : int, optional
473 466 Number of lines of context information to print.
474 467
475 468 Returns
476 469 -------
477 470 String with formatted exception.
478 471 """
479 472 tb_offset = self.tb_offset if tb_offset is None else tb_offset
480 473 Colors = self.Colors
481 474 out_list = []
482 475 if elist:
483 476
484 477 if tb_offset and len(elist) > tb_offset:
485 478 elist = elist[tb_offset:]
486 479
487 480 out_list.append('Traceback %s(most recent call last)%s:' %
488 481 (Colors.normalEm, Colors.Normal) + '\n')
489 482 out_list.extend(self._format_list(elist))
490 483 # The exception info should be a single entry in the list.
491 484 lines = ''.join(self._format_exception_only(etype, value))
492 485 out_list.append(lines)
493 486
494 487 # Note: this code originally read:
495 488
496 489 ## for line in lines[:-1]:
497 490 ## out_list.append(" "+line)
498 491 ## out_list.append(lines[-1])
499 492
500 493 # This means it was indenting everything but the last line by a little
501 494 # bit. I've disabled this for now, but if we see ugliness somewhre we
502 495 # can restore it.
503 496
504 497 return out_list
505 498
506 499 def _format_list(self, extracted_list):
507 500 """Format a list of traceback entry tuples for printing.
508 501
509 502 Given a list of tuples as returned by extract_tb() or
510 503 extract_stack(), return a list of strings ready for printing.
511 504 Each string in the resulting list corresponds to the item with the
512 505 same index in the argument list. Each string ends in a newline;
513 506 the strings may contain internal newlines as well, for those items
514 507 whose source text line is not None.
515 508
516 509 Lifted almost verbatim from traceback.py
517 510 """
518 511
519 512 Colors = self.Colors
520 513 list = []
521 514 for filename, lineno, name, line in extracted_list[:-1]:
522 515 item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
523 516 (Colors.filename, filename, Colors.Normal,
524 517 Colors.lineno, lineno, Colors.Normal,
525 518 Colors.name, name, Colors.Normal)
526 519 if line:
527 520 item += ' %s\n' % line.strip()
528 521 list.append(item)
529 522 # Emphasize the last entry
530 523 filename, lineno, name, line = extracted_list[-1]
531 524 item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
532 525 (Colors.normalEm,
533 526 Colors.filenameEm, filename, Colors.normalEm,
534 527 Colors.linenoEm, lineno, Colors.normalEm,
535 528 Colors.nameEm, name, Colors.normalEm,
536 529 Colors.Normal)
537 530 if line:
538 531 item += '%s %s%s\n' % (Colors.line, line.strip(),
539 532 Colors.Normal)
540 533 list.append(item)
541 534 #from pprint import pformat; print 'LISTTB', pformat(list) # dbg
542 535 return list
543 536
544 537 def _format_exception_only(self, etype, value):
545 538 """Format the exception part of a traceback.
546 539
547 540 The arguments are the exception type and value such as given by
548 541 sys.exc_info()[:2]. The return value is a list of strings, each ending
549 542 in a newline. Normally, the list contains a single string; however,
550 543 for SyntaxError exceptions, it contains several lines that (when
551 544 printed) display detailed information about where the syntax error
552 545 occurred. The message indicating which exception occurred is the
553 546 always last string in the list.
554 547
555 548 Also lifted nearly verbatim from traceback.py
556 549 """
557 550
558 551 have_filedata = False
559 552 Colors = self.Colors
560 553 list = []
561 554 stype = Colors.excName + etype.__name__ + Colors.Normal
562 555 if value is None:
563 556 # Not sure if this can still happen in Python 2.6 and above
564 557 list.append( str(stype) + '\n')
565 558 else:
566 559 if etype is SyntaxError:
567 560 have_filedata = True
568 561 #print 'filename is',filename # dbg
569 562 if not value.filename: value.filename = "<string>"
570 563 list.append('%s File %s"%s"%s, line %s%d%s\n' % \
571 564 (Colors.normalEm,
572 565 Colors.filenameEm, value.filename, Colors.normalEm,
573 566 Colors.linenoEm, value.lineno, Colors.Normal ))
574 567 if value.text is not None:
575 568 i = 0
576 569 while i < len(value.text) and value.text[i].isspace():
577 570 i += 1
578 571 list.append('%s %s%s\n' % (Colors.line,
579 572 value.text.strip(),
580 573 Colors.Normal))
581 574 if value.offset is not None:
582 575 s = ' '
583 576 for c in value.text[i:value.offset-1]:
584 577 if c.isspace():
585 578 s += c
586 579 else:
587 580 s += ' '
588 581 list.append('%s%s^%s\n' % (Colors.caret, s,
589 582 Colors.Normal) )
590 583
591 584 try:
592 585 s = value.msg
593 586 except Exception:
594 587 s = self._some_str(value)
595 588 if s:
596 589 list.append('%s%s:%s %s\n' % (str(stype), Colors.excName,
597 590 Colors.Normal, s))
598 591 else:
599 592 list.append('%s\n' % str(stype))
600 593
601 594 # sync with user hooks
602 595 if have_filedata:
603 596 ipinst = ipapi.get()
604 597 if ipinst is not None:
605 598 ipinst.hooks.synchronize_with_editor(value.filename, value.lineno, 0)
606 599
607 600 return list
608 601
609 602 def get_exception_only(self, etype, value):
610 603 """Only print the exception type and message, without a traceback.
611 604
612 605 Parameters
613 606 ----------
614 607 etype : exception type
615 608 value : exception value
616 609 """
617 610 return ListTB.structured_traceback(self, etype, value, [])
618 611
619 612
620 613 def show_exception_only(self, etype, evalue):
621 614 """Only print the exception type and message, without a traceback.
622 615
623 616 Parameters
624 617 ----------
625 618 etype : exception type
626 619 value : exception value
627 620 """
628 621 # This method needs to use __call__ from *this* class, not the one from
629 622 # a subclass whose signature or behavior may be different
630 623 ostream = self.ostream
631 624 ostream.flush()
632 625 ostream.write('\n'.join(self.get_exception_only(etype, evalue)))
633 626 ostream.flush()
634 627
635 628 def _some_str(self, value):
636 629 # Lifted from traceback.py
637 630 try:
638 631 return str(value)
639 632 except:
640 633 return '<unprintable %s object>' % type(value).__name__
641 634
642 635 #----------------------------------------------------------------------------
643 636 class VerboseTB(TBTools):
644 637 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
645 638 of HTML. Requires inspect and pydoc. Crazy, man.
646 639
647 640 Modified version which optionally strips the topmost entries from the
648 641 traceback, to be used with alternate interpreters (because their own code
649 642 would appear in the traceback)."""
650 643
651 644 def __init__(self,color_scheme = 'Linux', call_pdb=False, ostream=None,
652 645 tb_offset=0, long_header=False, include_vars=True,
653 646 check_cache=None):
654 647 """Specify traceback offset, headers and color scheme.
655 648
656 649 Define how many frames to drop from the tracebacks. Calling it with
657 650 tb_offset=1 allows use of this handler in interpreters which will have
658 651 their own code at the top of the traceback (VerboseTB will first
659 652 remove that frame before printing the traceback info)."""
660 653 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
661 654 ostream=ostream)
662 655 self.tb_offset = tb_offset
663 656 self.long_header = long_header
664 657 self.include_vars = include_vars
665 658 # By default we use linecache.checkcache, but the user can provide a
666 659 # different check_cache implementation. This is used by the IPython
667 660 # kernel to provide tracebacks for interactive code that is cached,
668 661 # by a compiler instance that flushes the linecache but preserves its
669 662 # own code cache.
670 663 if check_cache is None:
671 664 check_cache = linecache.checkcache
672 665 self.check_cache = check_cache
673 666
674 667 def structured_traceback(self, etype, evalue, etb, tb_offset=None,
675 668 context=5):
676 669 """Return a nice text document describing the traceback."""
677 670
678 671 tb_offset = self.tb_offset if tb_offset is None else tb_offset
679 672
680 673 # some locals
681 674 try:
682 675 etype = etype.__name__
683 676 except AttributeError:
684 677 pass
685 678 Colors = self.Colors # just a shorthand + quicker name lookup
686 679 ColorsNormal = Colors.Normal # used a lot
687 680 col_scheme = self.color_scheme_table.active_scheme_name
688 681 indent = ' '*INDENT_SIZE
689 682 em_normal = '%s\n%s%s' % (Colors.valEm, indent,ColorsNormal)
690 683 undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
691 684 exc = '%s%s%s' % (Colors.excName,etype,ColorsNormal)
692 685
693 686 # some internal-use functions
694 687 def text_repr(value):
695 688 """Hopefully pretty robust repr equivalent."""
696 689 # this is pretty horrible but should always return *something*
697 690 try:
698 691 return pydoc.text.repr(value)
699 692 except KeyboardInterrupt:
700 693 raise
701 694 except:
702 695 try:
703 696 return repr(value)
704 697 except KeyboardInterrupt:
705 698 raise
706 699 except:
707 700 try:
708 701 # all still in an except block so we catch
709 702 # getattr raising
710 703 name = getattr(value, '__name__', None)
711 704 if name:
712 705 # ick, recursion
713 706 return text_repr(name)
714 707 klass = getattr(value, '__class__', None)
715 708 if klass:
716 709 return '%s instance' % text_repr(klass)
717 710 except KeyboardInterrupt:
718 711 raise
719 712 except:
720 713 return 'UNRECOVERABLE REPR FAILURE'
721 714 def eqrepr(value, repr=text_repr): return '=%s' % repr(value)
722 715 def nullrepr(value, repr=text_repr): return ''
723 716
724 717 # meat of the code begins
725 718 try:
726 719 etype = etype.__name__
727 720 except AttributeError:
728 721 pass
729 722
730 723 if self.long_header:
731 724 # Header with the exception type, python version, and date
732 725 pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
733 726 date = time.ctime(time.time())
734 727
735 728 head = '%s%s%s\n%s%s%s\n%s' % (Colors.topline, '-'*75, ColorsNormal,
736 729 exc, ' '*(75-len(str(etype))-len(pyver)),
737 730 pyver, date.rjust(75) )
738 731 head += "\nA problem occured executing Python code. Here is the sequence of function"\
739 732 "\ncalls leading up to the error, with the most recent (innermost) call last."
740 733 else:
741 734 # Simplified header
742 735 head = '%s%s%s\n%s%s' % (Colors.topline, '-'*75, ColorsNormal,exc,
743 736 'Traceback (most recent call last)'.\
744 737 rjust(75 - len(str(etype)) ) )
745 738 frames = []
746 739 # Flush cache before calling inspect. This helps alleviate some of the
747 740 # problems with python 2.3's inspect.py.
748 741 ##self.check_cache()
749 742 # Drop topmost frames if requested
750 743 try:
751 744 # Try the default getinnerframes and Alex's: Alex's fixes some
752 745 # problems, but it generates empty tracebacks for console errors
753 746 # (5 blanks lines) where none should be returned.
754 747 #records = inspect.getinnerframes(etb, context)[tb_offset:]
755 748 #print 'python records:', records # dbg
756 749 records = _fixed_getinnerframes(etb, context, tb_offset)
757 750 #print 'alex records:', records # dbg
758 751 except:
759 752
760 753 # FIXME: I've been getting many crash reports from python 2.3
761 754 # users, traceable to inspect.py. If I can find a small test-case
762 755 # to reproduce this, I should either write a better workaround or
763 756 # file a bug report against inspect (if that's the real problem).
764 757 # So far, I haven't been able to find an isolated example to
765 758 # reproduce the problem.
766 759 inspect_error()
767 760 traceback.print_exc(file=self.ostream)
768 761 info('\nUnfortunately, your original traceback can not be constructed.\n')
769 762 return ''
770 763
771 764 # build some color string templates outside these nested loops
772 765 tpl_link = '%s%%s%s' % (Colors.filenameEm,ColorsNormal)
773 766 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
774 767 ColorsNormal)
775 768 tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
776 769 (Colors.vName, Colors.valEm, ColorsNormal)
777 770 tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
778 771 tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
779 772 Colors.vName, ColorsNormal)
780 773 tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
781 774 tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal)
782 775 tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm,Colors.line,
783 776 ColorsNormal)
784 777
785 778 # now, loop over all records printing context and info
786 779 abspath = os.path.abspath
787 780 for frame, file, lnum, func, lines, index in records:
788 781 #print '*** record:',file,lnum,func,lines,index # dbg
789 782
790 783 if not file:
791 784 file = '?'
792 785 elif not(file.startswith("<") and file.endswith(">")):
793 786 # Guess that filenames like <string> aren't real filenames, so
794 787 # don't call abspath on them.
795 788 try:
796 789 file = abspath(file)
797 790 except OSError:
798 791 # Not sure if this can still happen: abspath now works with
799 792 # file names like <string>
800 793 pass
801 794
802 795 link = tpl_link % file
803 796 args, varargs, varkw, locals = inspect.getargvalues(frame)
804 797
805 798 if func == '?':
806 799 call = ''
807 800 else:
808 801 # Decide whether to include variable details or not
809 802 var_repr = self.include_vars and eqrepr or nullrepr
810 803 try:
811 804 call = tpl_call % (func,inspect.formatargvalues(args,
812 805 varargs, varkw,
813 806 locals,formatvalue=var_repr))
814 807 except KeyError:
815 808 # This happens in situations like errors inside generator
816 809 # expressions, where local variables are listed in the
817 810 # line, but can't be extracted from the frame. I'm not
818 811 # 100% sure this isn't actually a bug in inspect itself,
819 812 # but since there's no info for us to compute with, the
820 813 # best we can do is report the failure and move on. Here
821 814 # we must *not* call any traceback construction again,
822 815 # because that would mess up use of %debug later on. So we
823 816 # simply report the failure and move on. The only
824 817 # limitation will be that this frame won't have locals
825 818 # listed in the call signature. Quite subtle problem...
826 819 # I can't think of a good way to validate this in a unit
827 820 # test, but running a script consisting of:
828 821 # dict( (k,v.strip()) for (k,v) in range(10) )
829 822 # will illustrate the error, if this exception catch is
830 823 # disabled.
831 824 call = tpl_call_fail % func
832 825
833 826 # Don't attempt to tokenize binary files.
834 827 if file.endswith(('.so', '.pyd', '.dll')):
835 828 frames.append('%s %s\n' % (link,call))
836 829 continue
837 830 elif file.endswith(('.pyc','.pyo')):
838 831 # Look up the corresponding source file.
839 832 file = pyfile.source_from_cache(file)
840 833
841 834 def linereader(file=file, lnum=[lnum], getline=linecache.getline):
842 835 line = getline(file, lnum[0])
843 836 lnum[0] += 1
844 837 return line
845 838
846 839 # Build the list of names on this line of code where the exception
847 840 # occurred.
848 841 try:
849 842 names = []
850 843 name_cont = False
851 844
852 845 for token_type, token, start, end, line in generate_tokens(linereader):
853 846 # build composite names
854 847 if token_type == tokenize.NAME and token not in keyword.kwlist:
855 848 if name_cont:
856 849 # Continuation of a dotted name
857 850 try:
858 851 names[-1].append(token)
859 852 except IndexError:
860 853 names.append([token])
861 854 name_cont = False
862 855 else:
863 856 # Regular new names. We append everything, the caller
864 857 # will be responsible for pruning the list later. It's
865 858 # very tricky to try to prune as we go, b/c composite
866 859 # names can fool us. The pruning at the end is easy
867 860 # to do (or the caller can print a list with repeated
868 861 # names if so desired.
869 862 names.append([token])
870 863 elif token == '.':
871 864 name_cont = True
872 865 elif token_type == tokenize.NEWLINE:
873 866 break
874 867
875 868 except (IndexError, UnicodeDecodeError):
876 869 # signals exit of tokenizer
877 870 pass
878 871 except tokenize.TokenError as msg:
879 872 _m = ("An unexpected error occurred while tokenizing input\n"
880 873 "The following traceback may be corrupted or invalid\n"
881 874 "The error message is: %s\n" % msg)
882 875 error(_m)
883 876
884 877 # Join composite names (e.g. "dict.fromkeys")
885 878 names = ['.'.join(n) for n in names]
886 879 # prune names list of duplicates, but keep the right order
887 880 unique_names = uniq_stable(names)
888 881
889 882 # Start loop over vars
890 883 lvals = []
891 884 if self.include_vars:
892 885 for name_full in unique_names:
893 886 name_base = name_full.split('.',1)[0]
894 887 if name_base in frame.f_code.co_varnames:
895 888 if name_base in locals:
896 889 try:
897 890 value = repr(eval(name_full,locals))
898 891 except:
899 892 value = undefined
900 893 else:
901 894 value = undefined
902 895 name = tpl_local_var % name_full
903 896 else:
904 897 if name_base in frame.f_globals:
905 898 try:
906 899 value = repr(eval(name_full,frame.f_globals))
907 900 except:
908 901 value = undefined
909 902 else:
910 903 value = undefined
911 904 name = tpl_global_var % name_full
912 905 lvals.append(tpl_name_val % (name,value))
913 906 if lvals:
914 907 lvals = '%s%s' % (indent,em_normal.join(lvals))
915 908 else:
916 909 lvals = ''
917 910
918 911 level = '%s %s\n' % (link,call)
919 912
920 913 if index is None:
921 914 frames.append(level)
922 915 else:
923 916 frames.append('%s%s' % (level,''.join(
924 917 _format_traceback_lines(lnum,index,lines,Colors,lvals,
925 918 col_scheme))))
926 919
927 920 # Get (safely) a string form of the exception info
928 921 try:
929 922 etype_str,evalue_str = map(str,(etype,evalue))
930 923 except:
931 924 # User exception is improperly defined.
932 925 etype,evalue = str,sys.exc_info()[:2]
933 926 etype_str,evalue_str = map(str,(etype,evalue))
934 927 # ... and format it
935 928 exception = ['%s%s%s: %s' % (Colors.excName, etype_str,
936 929 ColorsNormal, evalue_str)]
937 930 if (not py3compat.PY3) and type(evalue) is types.InstanceType:
938 931 try:
939 932 names = [w for w in dir(evalue) if isinstance(w, basestring)]
940 933 except:
941 934 # Every now and then, an object with funny inernals blows up
942 935 # when dir() is called on it. We do the best we can to report
943 936 # the problem and continue
944 937 _m = '%sException reporting error (object with broken dir())%s:'
945 938 exception.append(_m % (Colors.excName,ColorsNormal))
946 939 etype_str,evalue_str = map(str,sys.exc_info()[:2])
947 940 exception.append('%s%s%s: %s' % (Colors.excName,etype_str,
948 941 ColorsNormal, evalue_str))
949 942 names = []
950 943 for name in names:
951 944 value = text_repr(getattr(evalue, name))
952 945 exception.append('\n%s%s = %s' % (indent, name, value))
953 946
954 947 # vds: >>
955 948 if records:
956 949 filepath, lnum = records[-1][1:3]
957 950 #print "file:", str(file), "linenb", str(lnum) # dbg
958 951 filepath = os.path.abspath(filepath)
959 952 ipinst = ipapi.get()
960 953 if ipinst is not None:
961 954 ipinst.hooks.synchronize_with_editor(filepath, lnum, 0)
962 955 # vds: <<
963 956
964 957 # return all our info assembled as a single string
965 958 # return '%s\n\n%s\n%s' % (head,'\n'.join(frames),''.join(exception[0]) )
966 959 return [head] + frames + [''.join(exception[0])]
967 960
968 961 def debugger(self,force=False):
969 962 """Call up the pdb debugger if desired, always clean up the tb
970 963 reference.
971 964
972 965 Keywords:
973 966
974 967 - force(False): by default, this routine checks the instance call_pdb
975 968 flag and does not actually invoke the debugger if the flag is false.
976 969 The 'force' option forces the debugger to activate even if the flag
977 970 is false.
978 971
979 972 If the call_pdb flag is set, the pdb interactive debugger is
980 973 invoked. In all cases, the self.tb reference to the current traceback
981 974 is deleted to prevent lingering references which hamper memory
982 975 management.
983 976
984 977 Note that each call to pdb() does an 'import readline', so if your app
985 978 requires a special setup for the readline completers, you'll have to
986 979 fix that by hand after invoking the exception handler."""
987 980
988 981 if force or self.call_pdb:
989 982 if self.pdb is None:
990 983 self.pdb = debugger.Pdb(
991 984 self.color_scheme_table.active_scheme_name)
992 985 # the system displayhook may have changed, restore the original
993 986 # for pdb
994 987 display_trap = DisplayTrap(hook=sys.__displayhook__)
995 988 with display_trap:
996 989 self.pdb.reset()
997 990 # Find the right frame so we don't pop up inside ipython itself
998 991 if hasattr(self,'tb') and self.tb is not None:
999 992 etb = self.tb
1000 993 else:
1001 994 etb = self.tb = sys.last_traceback
1002 995 while self.tb is not None and self.tb.tb_next is not None:
1003 996 self.tb = self.tb.tb_next
1004 997 if etb and etb.tb_next:
1005 998 etb = etb.tb_next
1006 999 self.pdb.botframe = etb.tb_frame
1007 1000 self.pdb.interaction(self.tb.tb_frame, self.tb)
1008 1001
1009 1002 if hasattr(self,'tb'):
1010 1003 del self.tb
1011 1004
1012 1005 def handler(self, info=None):
1013 1006 (etype, evalue, etb) = info or sys.exc_info()
1014 1007 self.tb = etb
1015 1008 ostream = self.ostream
1016 1009 ostream.flush()
1017 1010 ostream.write(self.text(etype, evalue, etb))
1018 1011 ostream.write('\n')
1019 1012 ostream.flush()
1020 1013
1021 1014 # Changed so an instance can just be called as VerboseTB_inst() and print
1022 1015 # out the right info on its own.
1023 1016 def __call__(self, etype=None, evalue=None, etb=None):
1024 1017 """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
1025 1018 if etb is None:
1026 1019 self.handler()
1027 1020 else:
1028 1021 self.handler((etype, evalue, etb))
1029 1022 try:
1030 1023 self.debugger()
1031 1024 except KeyboardInterrupt:
1032 1025 print "\nKeyboardInterrupt"
1033 1026
1034 1027 #----------------------------------------------------------------------------
1035 1028 class FormattedTB(VerboseTB, ListTB):
1036 1029 """Subclass ListTB but allow calling with a traceback.
1037 1030
1038 1031 It can thus be used as a sys.excepthook for Python > 2.1.
1039 1032
1040 1033 Also adds 'Context' and 'Verbose' modes, not available in ListTB.
1041 1034
1042 1035 Allows a tb_offset to be specified. This is useful for situations where
1043 1036 one needs to remove a number of topmost frames from the traceback (such as
1044 1037 occurs with python programs that themselves execute other python code,
1045 1038 like Python shells). """
1046 1039
1047 1040 def __init__(self, mode='Plain', color_scheme='Linux', call_pdb=False,
1048 1041 ostream=None,
1049 1042 tb_offset=0, long_header=False, include_vars=False,
1050 1043 check_cache=None):
1051 1044
1052 1045 # NEVER change the order of this list. Put new modes at the end:
1053 1046 self.valid_modes = ['Plain','Context','Verbose']
1054 1047 self.verbose_modes = self.valid_modes[1:3]
1055 1048
1056 1049 VerboseTB.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
1057 1050 ostream=ostream, tb_offset=tb_offset,
1058 1051 long_header=long_header, include_vars=include_vars,
1059 1052 check_cache=check_cache)
1060 1053
1061 1054 # Different types of tracebacks are joined with different separators to
1062 1055 # form a single string. They are taken from this dict
1063 1056 self._join_chars = dict(Plain='', Context='\n', Verbose='\n')
1064 1057 # set_mode also sets the tb_join_char attribute
1065 1058 self.set_mode(mode)
1066 1059
1067 1060 def _extract_tb(self,tb):
1068 1061 if tb:
1069 1062 return traceback.extract_tb(tb)
1070 1063 else:
1071 1064 return None
1072 1065
1073 1066 def structured_traceback(self, etype, value, tb, tb_offset=None, context=5):
1074 1067 tb_offset = self.tb_offset if tb_offset is None else tb_offset
1075 1068 mode = self.mode
1076 1069 if mode in self.verbose_modes:
1077 1070 # Verbose modes need a full traceback
1078 1071 return VerboseTB.structured_traceback(
1079 1072 self, etype, value, tb, tb_offset, context
1080 1073 )
1081 1074 else:
1082 1075 # We must check the source cache because otherwise we can print
1083 1076 # out-of-date source code.
1084 1077 self.check_cache()
1085 1078 # Now we can extract and format the exception
1086 1079 elist = self._extract_tb(tb)
1087 1080 return ListTB.structured_traceback(
1088 1081 self, etype, value, elist, tb_offset, context
1089 1082 )
1090 1083
1091 1084 def stb2text(self, stb):
1092 1085 """Convert a structured traceback (a list) to a string."""
1093 1086 return self.tb_join_char.join(stb)
1094 1087
1095 1088
1096 1089 def set_mode(self,mode=None):
1097 1090 """Switch to the desired mode.
1098 1091
1099 1092 If mode is not specified, cycles through the available modes."""
1100 1093
1101 1094 if not mode:
1102 1095 new_idx = ( self.valid_modes.index(self.mode) + 1 ) % \
1103 1096 len(self.valid_modes)
1104 1097 self.mode = self.valid_modes[new_idx]
1105 1098 elif mode not in self.valid_modes:
1106 1099 raise ValueError('Unrecognized mode in FormattedTB: <'+mode+'>\n'
1107 1100 'Valid modes: '+str(self.valid_modes))
1108 1101 else:
1109 1102 self.mode = mode
1110 1103 # include variable details only in 'Verbose' mode
1111 1104 self.include_vars = (self.mode == self.valid_modes[2])
1112 1105 # Set the join character for generating text tracebacks
1113 1106 self.tb_join_char = self._join_chars[self.mode]
1114 1107
1115 1108 # some convenient shorcuts
1116 1109 def plain(self):
1117 1110 self.set_mode(self.valid_modes[0])
1118 1111
1119 1112 def context(self):
1120 1113 self.set_mode(self.valid_modes[1])
1121 1114
1122 1115 def verbose(self):
1123 1116 self.set_mode(self.valid_modes[2])
1124 1117
1125 1118 #----------------------------------------------------------------------------
1126 1119 class AutoFormattedTB(FormattedTB):
1127 1120 """A traceback printer which can be called on the fly.
1128 1121
1129 1122 It will find out about exceptions by itself.
1130 1123
1131 1124 A brief example:
1132 1125
1133 1126 AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
1134 1127 try:
1135 1128 ...
1136 1129 except:
1137 1130 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
1138 1131 """
1139 1132
1140 1133 def __call__(self,etype=None,evalue=None,etb=None,
1141 1134 out=None,tb_offset=None):
1142 1135 """Print out a formatted exception traceback.
1143 1136
1144 1137 Optional arguments:
1145 1138 - out: an open file-like object to direct output to.
1146 1139
1147 1140 - tb_offset: the number of frames to skip over in the stack, on a
1148 1141 per-call basis (this overrides temporarily the instance's tb_offset
1149 1142 given at initialization time. """
1150 1143
1151 1144
1152 1145 if out is None:
1153 1146 out = self.ostream
1154 1147 out.flush()
1155 1148 out.write(self.text(etype, evalue, etb, tb_offset))
1156 1149 out.write('\n')
1157 1150 out.flush()
1158 1151 # FIXME: we should remove the auto pdb behavior from here and leave
1159 1152 # that to the clients.
1160 1153 try:
1161 1154 self.debugger()
1162 1155 except KeyboardInterrupt:
1163 1156 print "\nKeyboardInterrupt"
1164 1157
1165 1158 def structured_traceback(self, etype=None, value=None, tb=None,
1166 1159 tb_offset=None, context=5):
1167 1160 if etype is None:
1168 1161 etype,value,tb = sys.exc_info()
1169 1162 self.tb = tb
1170 1163 return FormattedTB.structured_traceback(
1171 1164 self, etype, value, tb, tb_offset, context)
1172 1165
1173 1166 #---------------------------------------------------------------------------
1174 1167
1175 1168 # A simple class to preserve Nathan's original functionality.
1176 1169 class ColorTB(FormattedTB):
1177 1170 """Shorthand to initialize a FormattedTB in Linux colors mode."""
1178 1171 def __init__(self,color_scheme='Linux',call_pdb=0):
1179 1172 FormattedTB.__init__(self,color_scheme=color_scheme,
1180 1173 call_pdb=call_pdb)
1181 1174
1182 1175
1183 1176 class SyntaxTB(ListTB):
1184 1177 """Extension which holds some state: the last exception value"""
1185 1178
1186 1179 def __init__(self,color_scheme = 'NoColor'):
1187 1180 ListTB.__init__(self,color_scheme)
1188 1181 self.last_syntax_error = None
1189 1182
1190 1183 def __call__(self, etype, value, elist):
1191 1184 self.last_syntax_error = value
1192 1185 ListTB.__call__(self,etype,value,elist)
1193 1186
1194 1187 def clear_err_state(self):
1195 1188 """Return the current error state and clear it"""
1196 1189 e = self.last_syntax_error
1197 1190 self.last_syntax_error = None
1198 1191 return e
1199 1192
1200 1193 def stb2text(self, stb):
1201 1194 """Convert a structured traceback (a list) to a string."""
1202 1195 return ''.join(stb)
1203 1196
1204 1197
1205 1198 #----------------------------------------------------------------------------
1206 1199 # module testing (minimal)
1207 1200 if __name__ == "__main__":
1208 1201 def spam(c, d_e):
1209 1202 (d, e) = d_e
1210 1203 x = c + d
1211 1204 y = c * d
1212 1205 foo(x, y)
1213 1206
1214 1207 def foo(a, b, bar=1):
1215 1208 eggs(a, b + bar)
1216 1209
1217 1210 def eggs(f, g, z=globals()):
1218 1211 h = f + g
1219 1212 i = f - g
1220 1213 return h / i
1221 1214
1222 1215 print ''
1223 1216 print '*** Before ***'
1224 1217 try:
1225 1218 print spam(1, (2, 3))
1226 1219 except:
1227 1220 traceback.print_exc()
1228 1221 print ''
1229 1222
1230 1223 handler = ColorTB()
1231 1224 print '*** ColorTB ***'
1232 1225 try:
1233 1226 print spam(1, (2, 3))
1234 1227 except:
1235 1228 handler(*sys.exc_info())
1236 1229 print ''
1237 1230
1238 1231 handler = VerboseTB()
1239 1232 print '*** VerboseTB ***'
1240 1233 try:
1241 1234 print spam(1, (2, 3))
1242 1235 except:
1243 1236 handler(*sys.exc_info())
1244 1237 print ''
1245 1238
General Comments 0
You need to be logged in to leave comments. Login now