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