##// END OF EJS Templates
i1673 PEP8 formatting in `ultratab.py`
Justyna Ilczuk -
r17156:74cb0680
parent child
Show More
@@ -39,7 +39,7 Give it a shot--you'll love it or you'll hate it.
39 Verbose).
39 Verbose).
40
40
41
41
42 Installation instructions for ColorTB::
42 Installation instructions for VerboseTB::
43
43
44 import sys,ultratb
44 import sys,ultratb
45 sys.excepthook = ultratb.VerboseTB()
45 sys.excepthook = ultratb.VerboseTB()
@@ -72,8 +72,8 Inheritance diagram:
72 :parts: 3
72 :parts: 3
73 """
73 """
74
74
75 #*****************************************************************************
75 # *****************************************************************************
76 # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
76 # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
77 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
77 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
78 #
78 #
79 # Distributed under the terms of the BSD License. The full license is in
79 # Distributed under the terms of the BSD License. The full license is in
@@ -95,14 +95,14 import tokenize
95 import traceback
95 import traceback
96 import types
96 import types
97
97
98 try: # Python 2
98 try: # Python 2
99 generate_tokens = tokenize.generate_tokens
99 generate_tokens = tokenize.generate_tokens
100 except AttributeError: # Python 3
100 except AttributeError: # Python 3
101 generate_tokens = tokenize.tokenize
101 generate_tokens = tokenize.tokenize
102
102
103 # For purposes of monkeypatching inspect to fix a bug in it.
103 # For purposes of monkeypatching inspect to fix a bug in it.
104 from inspect import getsourcefile, getfile, getmodule,\
104 from inspect import getsourcefile, getfile, getmodule, \
105 ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode
105 ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode
106
106
107 # IPython's own modules
107 # IPython's own modules
108 # Modified pdb which doesn't damage IPython's readline handling
108 # Modified pdb which doesn't damage IPython's readline handling
@@ -125,7 +125,7 INDENT_SIZE = 8
125
125
126 # Default color scheme. This is used, for example, by the traceback
126 # Default color scheme. This is used, for example, by the traceback
127 # formatter. When running in an actual IPython instance, the user's rc.colors
127 # formatter. When running in an actual IPython instance, the user's rc.colors
128 # value is used, but havinga module global makes this functionality available
128 # value is used, but having a module global makes this functionality available
129 # to users of ultratb who are NOT running inside ipython.
129 # to users of ultratb who are NOT running inside ipython.
130 DEFAULT_SCHEME = 'NoColor'
130 DEFAULT_SCHEME = 'NoColor'
131
131
@@ -141,6 +141,7 def inspect_error():
141 error('Internal Python error in the inspect module.\n'
141 error('Internal Python error in the inspect module.\n'
142 'Below is the traceback from this internal error.\n')
142 'Below is the traceback from this internal error.\n')
143
143
144
144 # This function is a monkeypatch we apply to the Python inspect module. We have
145 # This function is a monkeypatch we apply to the Python inspect module. We have
145 # now found when it's needed (see discussion on issue gh-1456), and we have a
146 # now found when it's needed (see discussion on issue gh-1456), and we have a
146 # test case (IPython.core.tests.test_ultratb.ChangedPyFileTest) that fails if
147 # test case (IPython.core.tests.test_ultratb.ChangedPyFileTest) that fails if
@@ -212,7 +213,7 def findsource(object):
212 pmatch = pat.match
213 pmatch = pat.match
213 # fperez - fix: sometimes, co_firstlineno can give a number larger than
214 # fperez - fix: sometimes, co_firstlineno can give a number larger than
214 # the length of lines, which causes an error. Safeguard against that.
215 # the length of lines, which causes an error. Safeguard against that.
215 lnum = min(object.co_firstlineno,len(lines))-1
216 lnum = min(object.co_firstlineno, len(lines)) - 1
216 while lnum > 0:
217 while lnum > 0:
217 if pmatch(lines[lnum]): break
218 if pmatch(lines[lnum]): break
218 lnum -= 1
219 lnum -= 1
@@ -220,9 +221,11 def findsource(object):
220 return lines, lnum
221 return lines, lnum
221 raise IOError('could not find code object')
222 raise IOError('could not find code object')
222
223
224
223 # Monkeypatch inspect to apply our bugfix.
225 # Monkeypatch inspect to apply our bugfix.
224 def with_patch_inspect(f):
226 def with_patch_inspect(f):
225 """decorator for monkeypatching inspect.findsource"""
227 """decorator for monkeypatching inspect.findsource"""
228
226 def wrapped(*args, **kwargs):
229 def wrapped(*args, **kwargs):
227 save_findsource = inspect.findsource
230 save_findsource = inspect.findsource
228 inspect.findsource = findsource
231 inspect.findsource = findsource
@@ -230,8 +233,10 def with_patch_inspect(f):
230 return f(*args, **kwargs)
233 return f(*args, **kwargs)
231 finally:
234 finally:
232 inspect.findsource = save_findsource
235 inspect.findsource = save_findsource
236
233 return wrapped
237 return wrapped
234
238
239
235 def fix_frame_records_filenames(records):
240 def fix_frame_records_filenames(records):
236 """Try to fix the filenames in each record from inspect.getinnerframes().
241 """Try to fix the filenames in each record from inspect.getinnerframes().
237
242
@@ -253,10 +258,10 def fix_frame_records_filenames(records):
253
258
254
259
255 @with_patch_inspect
260 @with_patch_inspect
256 def _fixed_getinnerframes(etb, context=1,tb_offset=0):
261 def _fixed_getinnerframes(etb, context=1, tb_offset=0):
257 LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5
262 LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5
258
263
259 records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
264 records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
260
265
261 # If the error is at the console, don't build any context, since it would
266 # If the error is at the console, don't build any context, since it would
262 # otherwise produce 5 blank lines printed out (there is no file at the
267 # otherwise produce 5 blank lines printed out (there is no file at the
@@ -272,9 +277,9 def _fixed_getinnerframes(etb, context=1,tb_offset=0):
272 aux = traceback.extract_tb(etb)
277 aux = traceback.extract_tb(etb)
273 assert len(records) == len(aux)
278 assert len(records) == len(aux)
274 for i, (file, lnum, _, _) in zip(range(len(records)), aux):
279 for i, (file, lnum, _, _) in zip(range(len(records)), aux):
275 maybeStart = lnum-1 - context//2
280 maybeStart = lnum - 1 - context // 2
276 start = max(maybeStart, 0)
281 start = max(maybeStart, 0)
277 end = start + context
282 end = start + context
278 lines = ulinecache.getlines(file)[start:end]
283 lines = ulinecache.getlines(file)[start:end]
279 buf = list(records[i])
284 buf = list(records[i])
280 buf[LNUM_POS] = lnum
285 buf[LNUM_POS] = lnum
@@ -290,7 +295,8 def _fixed_getinnerframes(etb, context=1,tb_offset=0):
290
295
291 _parser = PyColorize.Parser()
296 _parser = PyColorize.Parser()
292
297
293 def _format_traceback_lines(lnum, index, lines, Colors, lvals=None,scheme=None):
298
299 def _format_traceback_lines(lnum, index, lines, Colors, lvals=None, scheme=None):
294 numbers_width = INDENT_SIZE - 1
300 numbers_width = INDENT_SIZE - 1
295 res = []
301 res = []
296 i = lnum - index
302 i = lnum - index
@@ -315,7 +321,7 def _format_traceback_lines(lnum, index, lines, Colors, lvals=None,scheme=None):
315 # This is the line with the error
321 # This is the line with the error
316 pad = numbers_width - len(str(i))
322 pad = numbers_width - len(str(i))
317 if pad >= 3:
323 if pad >= 3:
318 marker = '-'*(pad-3) + '-> '
324 marker = '-' * (pad - 3) + '-> '
319 elif pad == 2:
325 elif pad == 2:
320 marker = '> '
326 marker = '> '
321 elif pad == 1:
327 elif pad == 1:
@@ -323,12 +329,12 def _format_traceback_lines(lnum, index, lines, Colors, lvals=None,scheme=None):
323 else:
329 else:
324 marker = ''
330 marker = ''
325 num = marker + str(i)
331 num = marker + str(i)
326 line = '%s%s%s %s%s' %(Colors.linenoEm, num,
332 line = '%s%s%s %s%s' % (Colors.linenoEm, num,
327 Colors.line, line, Colors.Normal)
333 Colors.line, line, Colors.Normal)
328 else:
334 else:
329 num = '%*s' % (numbers_width,i)
335 num = '%*s' % (numbers_width, i)
330 line = '%s%s%s %s' %(Colors.lineno, num,
336 line = '%s%s%s %s' % (Colors.lineno, num,
331 Colors.Normal, line)
337 Colors.Normal, line)
332
338
333 res.append(line)
339 res.append(line)
334 if lvals and i == lnum:
340 if lvals and i == lnum:
@@ -389,16 +395,16 class TBTools(object):
389
395
390 ostream = property(_get_ostream, _set_ostream)
396 ostream = property(_get_ostream, _set_ostream)
391
397
392 def set_colors(self,*args,**kw):
398 def set_colors(self, *args, **kw):
393 """Shorthand access to the color table scheme selector method."""
399 """Shorthand access to the color table scheme selector method."""
394
400
395 # Set own color table
401 # Set own color table
396 self.color_scheme_table.set_active_scheme(*args,**kw)
402 self.color_scheme_table.set_active_scheme(*args, **kw)
397 # for convenience, set Colors to the active scheme
403 # for convenience, set Colors to the active scheme
398 self.Colors = self.color_scheme_table.active_colors
404 self.Colors = self.color_scheme_table.active_colors
399 # Also set colors of debugger
405 # Also set colors of debugger
400 if hasattr(self,'pdb') and self.pdb is not None:
406 if hasattr(self, 'pdb') and self.pdb is not None:
401 self.pdb.set_colors(*args,**kw)
407 self.pdb.set_colors(*args, **kw)
402
408
403 def color_toggle(self):
409 def color_toggle(self):
404 """Toggle between the currently active color scheme and NoColor."""
410 """Toggle between the currently active color scheme and NoColor."""
@@ -453,7 +459,7 class ListTB(TBTools):
453 Because they are meant to be called without a full traceback (only a
459 Because they are meant to be called without a full traceback (only a
454 list), instances of this class can't call the interactive pdb debugger."""
460 list), instances of this class can't call the interactive pdb debugger."""
455
461
456 def __init__(self,color_scheme = 'NoColor', call_pdb=False, ostream=None):
462 def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None):
457 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
463 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
458 ostream=ostream)
464 ostream=ostream)
459
465
@@ -497,7 +503,7 class ListTB(TBTools):
497 elist = elist[tb_offset:]
503 elist = elist[tb_offset:]
498
504
499 out_list.append('Traceback %s(most recent call last)%s:' %
505 out_list.append('Traceback %s(most recent call last)%s:' %
500 (Colors.normalEm, Colors.Normal) + '\n')
506 (Colors.normalEm, Colors.Normal) + '\n')
501 out_list.extend(self._format_list(elist))
507 out_list.extend(self._format_list(elist))
502 # The exception info should be a single entry in the list.
508 # The exception info should be a single entry in the list.
503 lines = ''.join(self._format_exception_only(etype, value))
509 lines = ''.join(self._format_exception_only(etype, value))
@@ -532,23 +538,23 class ListTB(TBTools):
532 list = []
538 list = []
533 for filename, lineno, name, line in extracted_list[:-1]:
539 for filename, lineno, name, line in extracted_list[:-1]:
534 item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
540 item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
535 (Colors.filename, filename, Colors.Normal,
541 (Colors.filename, filename, Colors.Normal,
536 Colors.lineno, lineno, Colors.Normal,
542 Colors.lineno, lineno, Colors.Normal,
537 Colors.name, name, Colors.Normal)
543 Colors.name, name, Colors.Normal)
538 if line:
544 if line:
539 item += ' %s\n' % line.strip()
545 item += ' %s\n' % line.strip()
540 list.append(item)
546 list.append(item)
541 # Emphasize the last entry
547 # Emphasize the last entry
542 filename, lineno, name, line = extracted_list[-1]
548 filename, lineno, name, line = extracted_list[-1]
543 item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
549 item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
544 (Colors.normalEm,
550 (Colors.normalEm,
545 Colors.filenameEm, filename, Colors.normalEm,
551 Colors.filenameEm, filename, Colors.normalEm,
546 Colors.linenoEm, lineno, Colors.normalEm,
552 Colors.linenoEm, lineno, Colors.normalEm,
547 Colors.nameEm, name, Colors.normalEm,
553 Colors.nameEm, name, Colors.normalEm,
548 Colors.Normal)
554 Colors.Normal)
549 if line:
555 if line:
550 item += '%s %s%s\n' % (Colors.line, line.strip(),
556 item += '%s %s%s\n' % (Colors.line, line.strip(),
551 Colors.Normal)
557 Colors.Normal)
552 list.append(item)
558 list.append(item)
553 #from pprint import pformat; print 'LISTTB', pformat(list) # dbg
559 #from pprint import pformat; print 'LISTTB', pformat(list) # dbg
554 return list
560 return list
@@ -572,7 +578,7 class ListTB(TBTools):
572 stype = Colors.excName + etype.__name__ + Colors.Normal
578 stype = Colors.excName + etype.__name__ + Colors.Normal
573 if value is None:
579 if value is None:
574 # Not sure if this can still happen in Python 2.6 and above
580 # Not sure if this can still happen in Python 2.6 and above
575 list.append( py3compat.cast_unicode(stype) + '\n')
581 list.append(py3compat.cast_unicode(stype) + '\n')
576 else:
582 else:
577 if issubclass(etype, SyntaxError):
583 if issubclass(etype, SyntaxError):
578 have_filedata = True
584 have_filedata = True
@@ -585,9 +591,9 class ListTB(TBTools):
585 lineno = 'unknown'
591 lineno = 'unknown'
586 textline = ''
592 textline = ''
587 list.append('%s File %s"%s"%s, line %s%s%s\n' % \
593 list.append('%s File %s"%s"%s, line %s%s%s\n' % \
588 (Colors.normalEm,
594 (Colors.normalEm,
589 Colors.filenameEm, py3compat.cast_unicode(value.filename), Colors.normalEm,
595 Colors.filenameEm, py3compat.cast_unicode(value.filename), Colors.normalEm,
590 Colors.linenoEm, lineno, Colors.Normal ))
596 Colors.linenoEm, lineno, Colors.Normal ))
591 if textline == '':
597 if textline == '':
592 textline = py3compat.cast_unicode(value.text, "utf-8")
598 textline = py3compat.cast_unicode(value.text, "utf-8")
593
599
@@ -600,13 +606,13 class ListTB(TBTools):
600 Colors.Normal))
606 Colors.Normal))
601 if value.offset is not None:
607 if value.offset is not None:
602 s = ' '
608 s = ' '
603 for c in textline[i:value.offset-1]:
609 for c in textline[i:value.offset - 1]:
604 if c.isspace():
610 if c.isspace():
605 s += c
611 s += c
606 else:
612 else:
607 s += ' '
613 s += ' '
608 list.append('%s%s^%s\n' % (Colors.caret, s,
614 list.append('%s%s^%s\n' % (Colors.caret, s,
609 Colors.Normal) )
615 Colors.Normal))
610
616
611 try:
617 try:
612 s = value.msg
618 s = value.msg
@@ -636,7 +642,6 class ListTB(TBTools):
636 """
642 """
637 return ListTB.structured_traceback(self, etype, value, [])
643 return ListTB.structured_traceback(self, etype, value, [])
638
644
639
640 def show_exception_only(self, etype, evalue):
645 def show_exception_only(self, etype, evalue):
641 """Only print the exception type and message, without a traceback.
646 """Only print the exception type and message, without a traceback.
642
647
@@ -659,6 +664,7 class ListTB(TBTools):
659 except:
664 except:
660 return '<unprintable %s object>' % type(value).__name__
665 return '<unprintable %s object>' % type(value).__name__
661
666
667
662 #----------------------------------------------------------------------------
668 #----------------------------------------------------------------------------
663 class VerboseTB(TBTools):
669 class VerboseTB(TBTools):
664 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
670 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
@@ -668,7 +674,7 class VerboseTB(TBTools):
668 traceback, to be used with alternate interpreters (because their own code
674 traceback, to be used with alternate interpreters (because their own code
669 would appear in the traceback)."""
675 would appear in the traceback)."""
670
676
671 def __init__(self,color_scheme = 'Linux', call_pdb=False, ostream=None,
677 def __init__(self, color_scheme='Linux', call_pdb=False, ostream=None,
672 tb_offset=0, long_header=False, include_vars=True,
678 tb_offset=0, long_header=False, include_vars=True,
673 check_cache=None):
679 check_cache=None):
674 """Specify traceback offset, headers and color scheme.
680 """Specify traceback offset, headers and color scheme.
@@ -702,13 +708,13 class VerboseTB(TBTools):
702 etype = etype.__name__
708 etype = etype.__name__
703 except AttributeError:
709 except AttributeError:
704 pass
710 pass
705 Colors = self.Colors # just a shorthand + quicker name lookup
711 Colors = self.Colors # just a shorthand + quicker name lookup
706 ColorsNormal = Colors.Normal # used a lot
712 ColorsNormal = Colors.Normal # used a lot
707 col_scheme = self.color_scheme_table.active_scheme_name
713 col_scheme = self.color_scheme_table.active_scheme_name
708 indent = ' '*INDENT_SIZE
714 indent = ' ' * INDENT_SIZE
709 em_normal = '%s\n%s%s' % (Colors.valEm, indent,ColorsNormal)
715 em_normal = '%s\n%s%s' % (Colors.valEm, indent, ColorsNormal)
710 undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
716 undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
711 exc = '%s%s%s' % (Colors.excName,etype,ColorsNormal)
717 exc = '%s%s%s' % (Colors.excName, etype, ColorsNormal)
712
718
713 # some internal-use functions
719 # some internal-use functions
714 def text_repr(value):
720 def text_repr(value):
@@ -738,8 +744,12 class VerboseTB(TBTools):
738 raise
744 raise
739 except:
745 except:
740 return 'UNRECOVERABLE REPR FAILURE'
746 return 'UNRECOVERABLE REPR FAILURE'
741 def eqrepr(value, repr=text_repr): return '=%s' % repr(value)
747
742 def nullrepr(value, repr=text_repr): return ''
748 def eqrepr(value, repr=text_repr):
749 return '=%s' % repr(value)
750
751 def nullrepr(value, repr=text_repr):
752 return ''
743
753
744 # meat of the code begins
754 # meat of the code begins
745 try:
755 try:
@@ -752,16 +762,16 class VerboseTB(TBTools):
752 pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
762 pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
753 date = time.ctime(time.time())
763 date = time.ctime(time.time())
754
764
755 head = '%s%s%s\n%s%s%s\n%s' % (Colors.topline, '-'*75, ColorsNormal,
765 head = '%s%s%s\n%s%s%s\n%s' % (Colors.topline, '-' * 75, ColorsNormal,
756 exc, ' '*(75-len(str(etype))-len(pyver)),
766 exc, ' ' * (75 - len(str(etype)) - len(pyver)),
757 pyver, date.rjust(75) )
767 pyver, date.rjust(75) )
758 head += "\nA problem occured executing Python code. Here is the sequence of function"\
768 head += "\nA problem occured executing Python code. Here is the sequence of function" \
759 "\ncalls leading up to the error, with the most recent (innermost) call last."
769 "\ncalls leading up to the error, with the most recent (innermost) call last."
760 else:
770 else:
761 # Simplified header
771 # Simplified header
762 head = '%s%s%s\n%s%s' % (Colors.topline, '-'*75, ColorsNormal,exc,
772 head = '%s%s%s\n%s%s' % (Colors.topline, '-' * 75, ColorsNormal, exc,
763 'Traceback (most recent call last)'.\
773 'Traceback (most recent call last)'. \
764 rjust(75 - len(str(etype)) ) )
774 rjust(75 - len(str(etype))) )
765 frames = []
775 frames = []
766 # Flush cache before calling inspect. This helps alleviate some of the
776 # Flush cache before calling inspect. This helps alleviate some of the
767 # problems with python 2.3's inspect.py.
777 # problems with python 2.3's inspect.py.
@@ -789,18 +799,18 class VerboseTB(TBTools):
789 return ''
799 return ''
790
800
791 # build some color string templates outside these nested loops
801 # build some color string templates outside these nested loops
792 tpl_link = '%s%%s%s' % (Colors.filenameEm,ColorsNormal)
802 tpl_link = '%s%%s%s' % (Colors.filenameEm, ColorsNormal)
793 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
803 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
794 ColorsNormal)
804 ColorsNormal)
795 tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
805 tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
796 (Colors.vName, Colors.valEm, ColorsNormal)
806 (Colors.vName, Colors.valEm, ColorsNormal)
797 tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
807 tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
798 tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
808 tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
799 Colors.vName, ColorsNormal)
809 Colors.vName, ColorsNormal)
800 tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
810 tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
801 tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal)
811 tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal)
802 tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm,Colors.line,
812 tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm, Colors.line,
803 ColorsNormal)
813 ColorsNormal)
804
814
805 # now, loop over all records printing context and info
815 # now, loop over all records printing context and info
806 abspath = os.path.abspath
816 abspath = os.path.abspath
@@ -808,7 +818,7 class VerboseTB(TBTools):
808 #print '*** record:',file,lnum,func,lines,index # dbg
818 #print '*** record:',file,lnum,func,lines,index # dbg
809 if not file:
819 if not file:
810 file = '?'
820 file = '?'
811 elif not(file.startswith(str("<")) and file.endswith(str(">"))):
821 elif not (file.startswith(str("<")) and file.endswith(str(">"))):
812 # Guess that filenames like <string> aren't real filenames, so
822 # Guess that filenames like <string> aren't real filenames, so
813 # don't call abspath on them.
823 # don't call abspath on them.
814 try:
824 try:
@@ -827,9 +837,9 class VerboseTB(TBTools):
827 # Decide whether to include variable details or not
837 # Decide whether to include variable details or not
828 var_repr = self.include_vars and eqrepr or nullrepr
838 var_repr = self.include_vars and eqrepr or nullrepr
829 try:
839 try:
830 call = tpl_call % (func,inspect.formatargvalues(args,
840 call = tpl_call % (func, inspect.formatargvalues(args,
831 varargs, varkw,
841 varargs, varkw,
832 locals,formatvalue=var_repr))
842 locals, formatvalue=var_repr))
833 except KeyError:
843 except KeyError:
834 # This happens in situations like errors inside generator
844 # This happens in situations like errors inside generator
835 # expressions, where local variables are listed in the
845 # expressions, where local variables are listed in the
@@ -848,12 +858,12 class VerboseTB(TBTools):
848 # will illustrate the error, if this exception catch is
858 # will illustrate the error, if this exception catch is
849 # disabled.
859 # disabled.
850 call = tpl_call_fail % func
860 call = tpl_call_fail % func
851
861
852 # Don't attempt to tokenize binary files.
862 # Don't attempt to tokenize binary files.
853 if file.endswith(('.so', '.pyd', '.dll')):
863 if file.endswith(('.so', '.pyd', '.dll')):
854 frames.append('%s %s\n' % (link,call))
864 frames.append('%s %s\n' % (link, call))
855 continue
865 continue
856 elif file.endswith(('.pyc','.pyo')):
866 elif file.endswith(('.pyc', '.pyo')):
857 # Look up the corresponding source file.
867 # Look up the corresponding source file.
858 file = openpy.source_from_cache(file)
868 file = openpy.source_from_cache(file)
859
869
@@ -867,7 +877,7 class VerboseTB(TBTools):
867 try:
877 try:
868 names = []
878 names = []
869 name_cont = False
879 name_cont = False
870
880
871 for token_type, token, start, end, line in generate_tokens(linereader):
881 for token_type, token, start, end, line in generate_tokens(linereader):
872 # build composite names
882 # build composite names
873 if token_type == tokenize.NAME and token not in keyword.kwlist:
883 if token_type == tokenize.NAME and token not in keyword.kwlist:
@@ -890,7 +900,7 class VerboseTB(TBTools):
890 name_cont = True
900 name_cont = True
891 elif token_type == tokenize.NEWLINE:
901 elif token_type == tokenize.NEWLINE:
892 break
902 break
893
903
894 except (IndexError, UnicodeDecodeError):
904 except (IndexError, UnicodeDecodeError):
895 # signals exit of tokenizer
905 # signals exit of tokenizer
896 pass
906 pass
@@ -909,11 +919,11 class VerboseTB(TBTools):
909 lvals = []
919 lvals = []
910 if self.include_vars:
920 if self.include_vars:
911 for name_full in unique_names:
921 for name_full in unique_names:
912 name_base = name_full.split('.',1)[0]
922 name_base = name_full.split('.', 1)[0]
913 if name_base in frame.f_code.co_varnames:
923 if name_base in frame.f_code.co_varnames:
914 if name_base in locals:
924 if name_base in locals:
915 try:
925 try:
916 value = repr(eval(name_full,locals))
926 value = repr(eval(name_full, locals))
917 except:
927 except:
918 value = undefined
928 value = undefined
919 else:
929 else:
@@ -922,34 +932,34 class VerboseTB(TBTools):
922 else:
932 else:
923 if name_base in frame.f_globals:
933 if name_base in frame.f_globals:
924 try:
934 try:
925 value = repr(eval(name_full,frame.f_globals))
935 value = repr(eval(name_full, frame.f_globals))
926 except:
936 except:
927 value = undefined
937 value = undefined
928 else:
938 else:
929 value = undefined
939 value = undefined
930 name = tpl_global_var % name_full
940 name = tpl_global_var % name_full
931 lvals.append(tpl_name_val % (name,value))
941 lvals.append(tpl_name_val % (name, value))
932 if lvals:
942 if lvals:
933 lvals = '%s%s' % (indent,em_normal.join(lvals))
943 lvals = '%s%s' % (indent, em_normal.join(lvals))
934 else:
944 else:
935 lvals = ''
945 lvals = ''
936
946
937 level = '%s %s\n' % (link,call)
947 level = '%s %s\n' % (link, call)
938
948
939 if index is None:
949 if index is None:
940 frames.append(level)
950 frames.append(level)
941 else:
951 else:
942 frames.append('%s%s' % (level,''.join(
952 frames.append('%s%s' % (level, ''.join(
943 _format_traceback_lines(lnum,index,lines,Colors,lvals,
953 _format_traceback_lines(lnum, index, lines, Colors, lvals,
944 col_scheme))))
954 col_scheme))))
945
955
946 # Get (safely) a string form of the exception info
956 # Get (safely) a string form of the exception info
947 try:
957 try:
948 etype_str,evalue_str = map(str,(etype,evalue))
958 etype_str, evalue_str = map(str, (etype, evalue))
949 except:
959 except:
950 # User exception is improperly defined.
960 # User exception is improperly defined.
951 etype,evalue = str,sys.exc_info()[:2]
961 etype, evalue = str, sys.exc_info()[:2]
952 etype_str,evalue_str = map(str,(etype,evalue))
962 etype_str, evalue_str = map(str, (etype, evalue))
953 # ... and format it
963 # ... and format it
954 exception = ['%s%s%s: %s' % (Colors.excName, etype_str,
964 exception = ['%s%s%s: %s' % (Colors.excName, etype_str,
955 ColorsNormal, py3compat.cast_unicode(evalue_str))]
965 ColorsNormal, py3compat.cast_unicode(evalue_str))]
@@ -961,10 +971,10 class VerboseTB(TBTools):
961 # when dir() is called on it. We do the best we can to report
971 # when dir() is called on it. We do the best we can to report
962 # the problem and continue
972 # the problem and continue
963 _m = '%sException reporting error (object with broken dir())%s:'
973 _m = '%sException reporting error (object with broken dir())%s:'
964 exception.append(_m % (Colors.excName,ColorsNormal))
974 exception.append(_m % (Colors.excName, ColorsNormal))
965 etype_str,evalue_str = map(str,sys.exc_info()[:2])
975 etype_str, evalue_str = map(str, sys.exc_info()[:2])
966 exception.append('%s%s%s: %s' % (Colors.excName,etype_str,
976 exception.append('%s%s%s: %s' % (Colors.excName, etype_str,
967 ColorsNormal, py3compat.cast_unicode(evalue_str)))
977 ColorsNormal, py3compat.cast_unicode(evalue_str)))
968 names = []
978 names = []
969 for name in names:
979 for name in names:
970 value = text_repr(getattr(evalue, name))
980 value = text_repr(getattr(evalue, name))
@@ -972,19 +982,19 class VerboseTB(TBTools):
972
982
973 # vds: >>
983 # vds: >>
974 if records:
984 if records:
975 filepath, lnum = records[-1][1:3]
985 filepath, lnum = records[-1][1:3]
976 #print "file:", str(file), "linenb", str(lnum) # dbg
986 #print "file:", str(file), "linenb", str(lnum) # dbg
977 filepath = os.path.abspath(filepath)
987 filepath = os.path.abspath(filepath)
978 ipinst = get_ipython()
988 ipinst = get_ipython()
979 if ipinst is not None:
989 if ipinst is not None:
980 ipinst.hooks.synchronize_with_editor(filepath, lnum, 0)
990 ipinst.hooks.synchronize_with_editor(filepath, lnum, 0)
981 # vds: <<
991 # vds: <<
982
992
983 # return all our info assembled as a single string
993 # return all our info assembled as a single string
984 # return '%s\n\n%s\n%s' % (head,'\n'.join(frames),''.join(exception[0]) )
994 # return '%s\n\n%s\n%s' % (head,'\n'.join(frames),''.join(exception[0]) )
985 return [head] + frames + [''.join(exception[0])]
995 return [head] + frames + [''.join(exception[0])]
986
996
987 def debugger(self,force=False):
997 def debugger(self, force=False):
988 """Call up the pdb debugger if desired, always clean up the tb
998 """Call up the pdb debugger if desired, always clean up the tb
989 reference.
999 reference.
990
1000
@@ -1014,7 +1024,7 class VerboseTB(TBTools):
1014 with display_trap:
1024 with display_trap:
1015 self.pdb.reset()
1025 self.pdb.reset()
1016 # Find the right frame so we don't pop up inside ipython itself
1026 # Find the right frame so we don't pop up inside ipython itself
1017 if hasattr(self,'tb') and self.tb is not None:
1027 if hasattr(self, 'tb') and self.tb is not None:
1018 etb = self.tb
1028 etb = self.tb
1019 else:
1029 else:
1020 etb = self.tb = sys.last_traceback
1030 etb = self.tb = sys.last_traceback
@@ -1025,7 +1035,7 class VerboseTB(TBTools):
1025 self.pdb.botframe = etb.tb_frame
1035 self.pdb.botframe = etb.tb_frame
1026 self.pdb.interaction(self.tb.tb_frame, self.tb)
1036 self.pdb.interaction(self.tb.tb_frame, self.tb)
1027
1037
1028 if hasattr(self,'tb'):
1038 if hasattr(self, 'tb'):
1029 del self.tb
1039 del self.tb
1030
1040
1031 def handler(self, info=None):
1041 def handler(self, info=None):
@@ -1050,6 +1060,7 class VerboseTB(TBTools):
1050 except KeyboardInterrupt:
1060 except KeyboardInterrupt:
1051 print("\nKeyboardInterrupt")
1061 print("\nKeyboardInterrupt")
1052
1062
1063
1053 #----------------------------------------------------------------------------
1064 #----------------------------------------------------------------------------
1054 class FormattedTB(VerboseTB, ListTB):
1065 class FormattedTB(VerboseTB, ListTB):
1055 """Subclass ListTB but allow calling with a traceback.
1066 """Subclass ListTB but allow calling with a traceback.
@@ -1069,7 +1080,7 class FormattedTB(VerboseTB, ListTB):
1069 check_cache=None):
1080 check_cache=None):
1070
1081
1071 # NEVER change the order of this list. Put new modes at the end:
1082 # NEVER change the order of this list. Put new modes at the end:
1072 self.valid_modes = ['Plain','Context','Verbose']
1083 self.valid_modes = ['Plain', 'Context', 'Verbose']
1073 self.verbose_modes = self.valid_modes[1:3]
1084 self.verbose_modes = self.valid_modes[1:3]
1074
1085
1075 VerboseTB.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
1086 VerboseTB.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
@@ -1083,7 +1094,7 class FormattedTB(VerboseTB, ListTB):
1083 # set_mode also sets the tb_join_char attribute
1094 # set_mode also sets the tb_join_char attribute
1084 self.set_mode(mode)
1095 self.set_mode(mode)
1085
1096
1086 def _extract_tb(self,tb):
1097 def _extract_tb(self, tb):
1087 if tb:
1098 if tb:
1088 return traceback.extract_tb(tb)
1099 return traceback.extract_tb(tb)
1089 else:
1100 else:
@@ -1112,7 +1123,7 class FormattedTB(VerboseTB, ListTB):
1112 return self.tb_join_char.join(stb)
1123 return self.tb_join_char.join(stb)
1113
1124
1114
1125
1115 def set_mode(self,mode=None):
1126 def set_mode(self, mode=None):
1116 """Switch to the desired mode.
1127 """Switch to the desired mode.
1117
1128
1118 If mode is not specified, cycles through the available modes."""
1129 If mode is not specified, cycles through the available modes."""
@@ -1122,8 +1133,8 class FormattedTB(VerboseTB, ListTB):
1122 len(self.valid_modes)
1133 len(self.valid_modes)
1123 self.mode = self.valid_modes[new_idx]
1134 self.mode = self.valid_modes[new_idx]
1124 elif mode not in self.valid_modes:
1135 elif mode not in self.valid_modes:
1125 raise ValueError('Unrecognized mode in FormattedTB: <'+mode+'>\n'
1136 raise ValueError('Unrecognized mode in FormattedTB: <' + mode + '>\n'
1126 'Valid modes: '+str(self.valid_modes))
1137 'Valid modes: ' + str(self.valid_modes))
1127 else:
1138 else:
1128 self.mode = mode
1139 self.mode = mode
1129 # include variable details only in 'Verbose' mode
1140 # include variable details only in 'Verbose' mode
@@ -1131,7 +1142,7 class FormattedTB(VerboseTB, ListTB):
1131 # Set the join character for generating text tracebacks
1142 # Set the join character for generating text tracebacks
1132 self.tb_join_char = self._join_chars[self.mode]
1143 self.tb_join_char = self._join_chars[self.mode]
1133
1144
1134 # some convenient shorcuts
1145 # some convenient shortcuts
1135 def plain(self):
1146 def plain(self):
1136 self.set_mode(self.valid_modes[0])
1147 self.set_mode(self.valid_modes[0])
1137
1148
@@ -1141,6 +1152,7 class FormattedTB(VerboseTB, ListTB):
1141 def verbose(self):
1152 def verbose(self):
1142 self.set_mode(self.valid_modes[2])
1153 self.set_mode(self.valid_modes[2])
1143
1154
1155
1144 #----------------------------------------------------------------------------
1156 #----------------------------------------------------------------------------
1145 class AutoFormattedTB(FormattedTB):
1157 class AutoFormattedTB(FormattedTB):
1146 """A traceback printer which can be called on the fly.
1158 """A traceback printer which can be called on the fly.
@@ -1156,8 +1168,8 class AutoFormattedTB(FormattedTB):
1156 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
1168 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
1157 """
1169 """
1158
1170
1159 def __call__(self,etype=None,evalue=None,etb=None,
1171 def __call__(self, etype=None, evalue=None, etb=None,
1160 out=None,tb_offset=None):
1172 out=None, tb_offset=None):
1161 """Print out a formatted exception traceback.
1173 """Print out a formatted exception traceback.
1162
1174
1163 Optional arguments:
1175 Optional arguments:
@@ -1167,7 +1179,6 class AutoFormattedTB(FormattedTB):
1167 per-call basis (this overrides temporarily the instance's tb_offset
1179 per-call basis (this overrides temporarily the instance's tb_offset
1168 given at initialization time. """
1180 given at initialization time. """
1169
1181
1170
1171 if out is None:
1182 if out is None:
1172 out = self.ostream
1183 out = self.ostream
1173 out.flush()
1184 out.flush()
@@ -1184,31 +1195,33 class AutoFormattedTB(FormattedTB):
1184 def structured_traceback(self, etype=None, value=None, tb=None,
1195 def structured_traceback(self, etype=None, value=None, tb=None,
1185 tb_offset=None, context=5):
1196 tb_offset=None, context=5):
1186 if etype is None:
1197 if etype is None:
1187 etype,value,tb = sys.exc_info()
1198 etype, value, tb = sys.exc_info()
1188 self.tb = tb
1199 self.tb = tb
1189 return FormattedTB.structured_traceback(
1200 return FormattedTB.structured_traceback(
1190 self, etype, value, tb, tb_offset, context)
1201 self, etype, value, tb, tb_offset, context)
1191
1202
1203
1192 #---------------------------------------------------------------------------
1204 #---------------------------------------------------------------------------
1193
1205
1194 # A simple class to preserve Nathan's original functionality.
1206 # A simple class to preserve Nathan's original functionality.
1195 class ColorTB(FormattedTB):
1207 class ColorTB(FormattedTB):
1196 """Shorthand to initialize a FormattedTB in Linux colors mode."""
1208 """Shorthand to initialize a FormattedTB in Linux colors mode."""
1197 def __init__(self,color_scheme='Linux',call_pdb=0):
1209
1198 FormattedTB.__init__(self,color_scheme=color_scheme,
1210 def __init__(self, color_scheme='Linux', call_pdb=0):
1211 FormattedTB.__init__(self, color_scheme=color_scheme,
1199 call_pdb=call_pdb)
1212 call_pdb=call_pdb)
1200
1213
1201
1214
1202 class SyntaxTB(ListTB):
1215 class SyntaxTB(ListTB):
1203 """Extension which holds some state: the last exception value"""
1216 """Extension which holds some state: the last exception value"""
1204
1217
1205 def __init__(self,color_scheme = 'NoColor'):
1218 def __init__(self, color_scheme='NoColor'):
1206 ListTB.__init__(self,color_scheme)
1219 ListTB.__init__(self, color_scheme)
1207 self.last_syntax_error = None
1220 self.last_syntax_error = None
1208
1221
1209 def __call__(self, etype, value, elist):
1222 def __call__(self, etype, value, elist):
1210 self.last_syntax_error = value
1223 self.last_syntax_error = value
1211 ListTB.__call__(self,etype,value,elist)
1224 ListTB.__call__(self, etype, value, elist)
1212
1225
1213 def structured_traceback(self, etype, value, elist, tb_offset=None,
1226 def structured_traceback(self, etype, value, elist, tb_offset=None,
1214 context=5):
1227 context=5):
@@ -1223,7 +1236,7 class SyntaxTB(ListTB):
1223 if newtext:
1236 if newtext:
1224 value.text = newtext
1237 value.text = newtext
1225 return super(SyntaxTB, self).structured_traceback(etype, value, elist,
1238 return super(SyntaxTB, self).structured_traceback(etype, value, elist,
1226 tb_offset=tb_offset, context=context)
1239 tb_offset=tb_offset, context=context)
1227
1240
1228 def clear_err_state(self):
1241 def clear_err_state(self):
1229 """Return the current error state and clear it"""
1242 """Return the current error state and clear it"""
General Comments 0
You need to be logged in to leave comments. Login now