##// END OF EJS Templates
Update exception colors API to PEP8, various small fixes in related files....
Fernando Perez -
Show More
@@ -39,7 +39,7 b' import sys'
39
39
40 from IPython import PyColorize, ColorANSI, ipapi
40 from IPython import PyColorize, ColorANSI, ipapi
41 from IPython.genutils import Term
41 from IPython.genutils import Term
42 from IPython.excolors import ExceptionColors
42 from IPython.excolors import exception_colors
43
43
44 # See if we can use pydb.
44 # See if we can use pydb.
45 has_pydb = False
45 has_pydb = False
@@ -210,7 +210,7 b' class Pdb(OldPdb):'
210
210
211 # Create color table: we copy the default one from the traceback
211 # Create color table: we copy the default one from the traceback
212 # module and add a few attributes needed for debugging
212 # module and add a few attributes needed for debugging
213 self.color_scheme_table = ExceptionColors.copy()
213 self.color_scheme_table = exception_colors()
214
214
215 # shorthands
215 # shorthands
216 C = ColorANSI.TermColors
216 C = ColorANSI.TermColors
@@ -257,8 +257,7 b' class Pdb(OldPdb):'
257
257
258 # Create color table: we copy the default one from the traceback
258 # Create color table: we copy the default one from the traceback
259 # module and add a few attributes needed for debugging
259 # module and add a few attributes needed for debugging
260 ExceptionColors.set_active_scheme(color_scheme)
260 self.color_scheme_table = exception_colors()
261 self.color_scheme_table = ExceptionColors.copy()
262
261
263 # shorthands
262 # shorthands
264 C = ColorANSI.TermColors
263 C = ColorANSI.TermColors
@@ -20,90 +20,124 b' __version__ = Release.version'
20 # Required modules
20 # Required modules
21 from IPython.ColorANSI import ColorSchemeTable, TermColors, ColorScheme
21 from IPython.ColorANSI import ColorSchemeTable, TermColors, ColorScheme
22
22
23 ExceptionColors = ColorSchemeTable()
23 def exception_colors():
24
24 """Return a color table with fields for exception reporting.
25 # Populate it with color schemes
25
26 C = TermColors # shorthand and local lookup
26 The table is an instance of ColorSchemeTable with schemes added for
27 ExceptionColors.add_scheme(ColorScheme(
27 'Linux', 'LightBG' and 'NoColor' and fields for exception handling filled
28 'NoColor',
28 in.
29 # The color to be used for the top line
29
30 topline = C.NoColor,
30 Examples:
31
31
32 # The colors to be used in the traceback
32 >>> ec = exception_colors()
33 filename = C.NoColor,
33 >>> ec.active_scheme_name
34 lineno = C.NoColor,
34 ''
35 name = C.NoColor,
35 >>> print ec.active_colors
36 vName = C.NoColor,
36 None
37 val = C.NoColor,
37
38 em = C.NoColor,
38 Now we activate a color scheme:
39
39 >>> ec.set_active_scheme('NoColor')
40 # Emphasized colors for the last frame of the traceback
40 >>> ec.active_scheme_name
41 normalEm = C.NoColor,
41 'NoColor'
42 filenameEm = C.NoColor,
42 >>> ec.active_colors.keys()
43 linenoEm = C.NoColor,
43 ['em', 'caret', '__allownew', 'name', 'val', 'vName', 'Normal', 'normalEm',
44 nameEm = C.NoColor,
44 'filename', 'linenoEm', 'excName', 'lineno', 'valEm', 'filenameEm',
45 valEm = C.NoColor,
45 'nameEm', 'line', 'topline']
46
46 """
47 # Colors for printing the exception
48 excName = C.NoColor,
49 line = C.NoColor,
50 caret = C.NoColor,
51 Normal = C.NoColor
52 ))
53
54 # make some schemes as instances so we can copy them for modification easily
55 ExceptionColors.add_scheme(ColorScheme(
56 'Linux',
57 # The color to be used for the top line
58 topline = C.LightRed,
59
60 # The colors to be used in the traceback
61 filename = C.Green,
62 lineno = C.Green,
63 name = C.Purple,
64 vName = C.Cyan,
65 val = C.Green,
66 em = C.LightCyan,
67
68 # Emphasized colors for the last frame of the traceback
69 normalEm = C.LightCyan,
70 filenameEm = C.LightGreen,
71 linenoEm = C.LightGreen,
72 nameEm = C.LightPurple,
73 valEm = C.LightBlue,
74
75 # Colors for printing the exception
76 excName = C.LightRed,
77 line = C.Yellow,
78 caret = C.White,
79 Normal = C.Normal
80 ))
81
82 # For light backgrounds, swap dark/light colors
83 ExceptionColors.add_scheme(ColorScheme(
84 'LightBG',
85 # The color to be used for the top line
86 topline = C.Red,
87
47
88 # The colors to be used in the traceback
48 ex_colors = ColorSchemeTable()
89 filename = C.LightGreen,
49
90 lineno = C.LightGreen,
50 # Populate it with color schemes
91 name = C.LightPurple,
51 C = TermColors # shorthand and local lookup
92 vName = C.Cyan,
52 ex_colors.add_scheme(ColorScheme(
93 val = C.LightGreen,
53 'NoColor',
94 em = C.Cyan,
54 # The color to be used for the top line
95
55 topline = C.NoColor,
96 # Emphasized colors for the last frame of the traceback
56
97 normalEm = C.Cyan,
57 # The colors to be used in the traceback
98 filenameEm = C.Green,
58 filename = C.NoColor,
99 linenoEm = C.Green,
59 lineno = C.NoColor,
100 nameEm = C.Purple,
60 name = C.NoColor,
101 valEm = C.Blue,
61 vName = C.NoColor,
102
62 val = C.NoColor,
103 # Colors for printing the exception
63 em = C.NoColor,
104 excName = C.Red,
64
105 #line = C.Brown, # brown often is displayed as yellow
65 # Emphasized colors for the last frame of the traceback
106 line = C.Red,
66 normalEm = C.NoColor,
107 caret = C.Normal,
67 filenameEm = C.NoColor,
108 Normal = C.Normal
68 linenoEm = C.NoColor,
109 ))
69 nameEm = C.NoColor,
70 valEm = C.NoColor,
71
72 # Colors for printing the exception
73 excName = C.NoColor,
74 line = C.NoColor,
75 caret = C.NoColor,
76 Normal = C.NoColor
77 ))
78
79 # make some schemes as instances so we can copy them for modification easily
80 ex_colors.add_scheme(ColorScheme(
81 'Linux',
82 # The color to be used for the top line
83 topline = C.LightRed,
84
85 # The colors to be used in the traceback
86 filename = C.Green,
87 lineno = C.Green,
88 name = C.Purple,
89 vName = C.Cyan,
90 val = C.Green,
91 em = C.LightCyan,
92
93 # Emphasized colors for the last frame of the traceback
94 normalEm = C.LightCyan,
95 filenameEm = C.LightGreen,
96 linenoEm = C.LightGreen,
97 nameEm = C.LightPurple,
98 valEm = C.LightBlue,
99
100 # Colors for printing the exception
101 excName = C.LightRed,
102 line = C.Yellow,
103 caret = C.White,
104 Normal = C.Normal
105 ))
106
107 # For light backgrounds, swap dark/light colors
108 ex_colors.add_scheme(ColorScheme(
109 'LightBG',
110 # The color to be used for the top line
111 topline = C.Red,
112
113 # The colors to be used in the traceback
114 filename = C.LightGreen,
115 lineno = C.LightGreen,
116 name = C.LightPurple,
117 vName = C.Cyan,
118 val = C.LightGreen,
119 em = C.Cyan,
120
121 # Emphasized colors for the last frame of the traceback
122 normalEm = C.Cyan,
123 filenameEm = C.Green,
124 linenoEm = C.Green,
125 nameEm = C.Purple,
126 valEm = C.Blue,
127
128 # Colors for printing the exception
129 excName = C.Red,
130 #line = C.Brown, # brown often is displayed as yellow
131 line = C.Red,
132 caret = C.Normal,
133 Normal = C.Normal
134 ))
135
136 return ex_colors
137
138
139 # For backwards compatibility, keep around a single global object. Note that
140 # this should NOT be used, the factory function should be used instead, since
141 # these objects are stateful and it's very easy to get strange bugs if any code
142 # modifies the module-level object's state.
143 ExceptionColors = exception_colors()
@@ -1,5 +1,4 b''
1 # encoding: utf-8
1 # -*- coding: utf-8 -*-
2
3 """
2 """
4 ultraTB.py -- Spice up your tracebacks!
3 ultraTB.py -- Spice up your tracebacks!
5
4
@@ -61,20 +60,15 b' You can implement other color schemes easily, the syntax is fairly'
61 self-explanatory. Please send back new schemes you develop to the author for
60 self-explanatory. Please send back new schemes you develop to the author for
62 possible inclusion in future releases.
61 possible inclusion in future releases.
63
62
64 $Id: ultraTB.py 2480 2007-07-06 19:33:43Z fperez $"""
63 $Id: ultraTB.py 2908 2007-12-30 21:07:46Z vivainio $"""
65
66 __docformat__ = "restructuredtext en"
67
64
68 #-------------------------------------------------------------------------------
65 #*****************************************************************************
69 # Copyright (C) 2008 The IPython Development Team
66 # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
67 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
70 #
68 #
71 # Distributed under the terms of the BSD License. The full license is in
69 # Distributed under the terms of the BSD License. The full license is in
72 # the file COPYING, distributed as part of this software.
70 # the file COPYING, distributed as part of this software.
73 #-------------------------------------------------------------------------------
71 #*****************************************************************************
74
75 #-------------------------------------------------------------------------------
76 # Imports
77 #-------------------------------------------------------------------------------
78
72
79 from IPython import Release
73 from IPython import Release
80 __author__ = '%s <%s>\n%s <%s>' % (Release.authors['Nathan']+
74 __author__ = '%s <%s>\n%s <%s>' % (Release.authors['Nathan']+
@@ -104,7 +98,7 b' from inspect import getsourcefile, getfile, getmodule,\\'
104 # Modified pdb which doesn't damage IPython's readline handling
98 # Modified pdb which doesn't damage IPython's readline handling
105 from IPython import Debugger, PyColorize
99 from IPython import Debugger, PyColorize
106 from IPython.ipstruct import Struct
100 from IPython.ipstruct import Struct
107 from IPython.excolors import ExceptionColors
101 from IPython.excolors import exception_colors
108 from IPython.genutils import Term,uniq_stable,error,info
102 from IPython.genutils import Term,uniq_stable,error,info
109
103
110 # Globals
104 # Globals
@@ -141,11 +135,18 b' def findsource(object):'
141 FIXED version with which we monkeypatch the stdlib to work around a bug."""
135 FIXED version with which we monkeypatch the stdlib to work around a bug."""
142
136
143 file = getsourcefile(object) or getfile(object)
137 file = getsourcefile(object) or getfile(object)
144 module = getmodule(object, file)
138 # If the object is a frame, then trying to get the globals dict from its
145 if module:
139 # module won't work. Instead, the frame object itself has the globals
146 lines = linecache.getlines(file, module.__dict__)
140 # dictionary.
141 globals_dict = None
142 if inspect.isframe(object):
143 # XXX: can this ever be false?
144 globals_dict = object.f_globals
147 else:
145 else:
148 lines = linecache.getlines(file)
146 module = getmodule(object, file)
147 if module:
148 globals_dict = module.__dict__
149 lines = linecache.getlines(file, globals_dict)
149 if not lines:
150 if not lines:
150 raise IOError('could not get source code')
151 raise IOError('could not get source code')
151
152
@@ -202,11 +203,31 b' def findsource(object):'
202 if sys.version_info[:2] >= (2,5):
203 if sys.version_info[:2] >= (2,5):
203 inspect.findsource = findsource
204 inspect.findsource = findsource
204
205
206 def fix_frame_records_filenames(records):
207 """Try to fix the filenames in each record from inspect.getinnerframes().
208
209 Particularly, modules loaded from within zip files have useless filenames
210 attached to their code object, and inspect.getinnerframes() just uses it.
211 """
212 fixed_records = []
213 for frame, filename, line_no, func_name, lines, index in records:
214 # Look inside the frame's globals dictionary for __file__, which should
215 # be better.
216 better_fn = frame.f_globals.get('__file__', None)
217 if isinstance(better_fn, str):
218 # Check the type just in case someone did something weird with
219 # __file__. It might also be None if the error occurred during
220 # import.
221 filename = better_fn
222 fixed_records.append((frame, filename, line_no, func_name, lines, index))
223 return fixed_records
224
225
205 def _fixed_getinnerframes(etb, context=1,tb_offset=0):
226 def _fixed_getinnerframes(etb, context=1,tb_offset=0):
206 import linecache
227 import linecache
207 LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5
228 LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5
208
229
209 records = inspect.getinnerframes(etb, context)
230 records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
210
231
211 # If the error is at the console, don't build any context, since it would
232 # If the error is at the console, don't build any context, since it would
212 # otherwise produce 5 blank lines printed out (there is no file at the
233 # otherwise produce 5 blank lines printed out (there is no file at the
@@ -299,7 +320,7 b' class TBTools:'
299 self.call_pdb = call_pdb
320 self.call_pdb = call_pdb
300
321
301 # Create color table
322 # Create color table
302 self.color_scheme_table = ExceptionColors
323 self.color_scheme_table = exception_colors()
303
324
304 self.set_colors(color_scheme)
325 self.set_colors(color_scheme)
305 self.old_scheme = color_scheme # save initial value for toggles
326 self.old_scheme = color_scheme # save initial value for toggles
@@ -356,8 +377,8 b' class ListTB(TBTools):'
356
377
357 def __call__(self, etype, value, elist):
378 def __call__(self, etype, value, elist):
358 Term.cout.flush()
379 Term.cout.flush()
359 Term.cerr.flush()
360 print >> Term.cerr, self.text(etype,value,elist)
380 print >> Term.cerr, self.text(etype,value,elist)
381 Term.cerr.flush()
361
382
362 def text(self,etype, value, elist,context=5):
383 def text(self,etype, value, elist,context=5):
363 """Return a color formatted string with the traceback info."""
384 """Return a color formatted string with the traceback info."""
@@ -424,7 +445,8 b' class ListTB(TBTools):'
424
445
425 Also lifted nearly verbatim from traceback.py
446 Also lifted nearly verbatim from traceback.py
426 """
447 """
427
448
449 have_filedata = False
428 Colors = self.Colors
450 Colors = self.Colors
429 list = []
451 list = []
430 try:
452 try:
@@ -438,8 +460,9 b' class ListTB(TBTools):'
438 try:
460 try:
439 msg, (filename, lineno, offset, line) = value
461 msg, (filename, lineno, offset, line) = value
440 except:
462 except:
441 pass
463 have_filedata = False
442 else:
464 else:
465 have_filedata = True
443 #print 'filename is',filename # dbg
466 #print 'filename is',filename # dbg
444 if not filename: filename = "<string>"
467 if not filename: filename = "<string>"
445 list.append('%s File %s"%s"%s, line %s%d%s\n' % \
468 list.append('%s File %s"%s"%s, line %s%d%s\n' % \
@@ -469,6 +492,12 b' class ListTB(TBTools):'
469 Colors.Normal, s))
492 Colors.Normal, s))
470 else:
493 else:
471 list.append('%s\n' % str(stype))
494 list.append('%s\n' % str(stype))
495
496 # vds:>>
497 if have_filedata:
498 __IPYTHON__.hooks.synchronize_with_editor(filename, lineno, 0)
499 # vds:<<
500
472 return list
501 return list
473
502
474 def _some_str(self, value):
503 def _some_str(self, value):
@@ -780,6 +809,15 b' class VerboseTB(TBTools):'
780 for name in names:
809 for name in names:
781 value = text_repr(getattr(evalue, name))
810 value = text_repr(getattr(evalue, name))
782 exception.append('\n%s%s = %s' % (indent, name, value))
811 exception.append('\n%s%s = %s' % (indent, name, value))
812
813 # vds: >>
814 if records:
815 filepath, lnum = records[-1][1:3]
816 #print "file:", str(file), "linenb", str(lnum) # dbg
817 filepath = os.path.abspath(filepath)
818 __IPYTHON__.hooks.synchronize_with_editor(filepath, lnum, 0)
819 # vds: <<
820
783 # return all our info assembled as a single string
821 # return all our info assembled as a single string
784 return '%s\n\n%s\n%s' % (head,'\n'.join(frames),''.join(exception[0]) )
822 return '%s\n\n%s\n%s' % (head,'\n'.join(frames),''.join(exception[0]) )
785
823
@@ -834,8 +872,8 b' class VerboseTB(TBTools):'
834 (etype, evalue, etb) = info or sys.exc_info()
872 (etype, evalue, etb) = info or sys.exc_info()
835 self.tb = etb
873 self.tb = etb
836 Term.cout.flush()
874 Term.cout.flush()
837 Term.cerr.flush()
838 print >> Term.cerr, self.text(etype, evalue, etb)
875 print >> Term.cerr, self.text(etype, evalue, etb)
876 Term.cerr.flush()
839
877
840 # Changed so an instance can just be called as VerboseTB_inst() and print
878 # Changed so an instance can just be called as VerboseTB_inst() and print
841 # out the right info on its own.
879 # out the right info on its own.
@@ -845,7 +883,10 b' class VerboseTB(TBTools):'
845 self.handler()
883 self.handler()
846 else:
884 else:
847 self.handler((etype, evalue, etb))
885 self.handler((etype, evalue, etb))
848 self.debugger()
886 try:
887 self.debugger()
888 except KeyboardInterrupt:
889 print "\nKeyboardInterrupt"
849
890
850 #----------------------------------------------------------------------------
891 #----------------------------------------------------------------------------
851 class FormattedTB(VerboseTB,ListTB):
892 class FormattedTB(VerboseTB,ListTB):
@@ -953,14 +994,17 b' class AutoFormattedTB(FormattedTB):'
953 if out is None:
994 if out is None:
954 out = Term.cerr
995 out = Term.cerr
955 Term.cout.flush()
996 Term.cout.flush()
956 out.flush()
957 if tb_offset is not None:
997 if tb_offset is not None:
958 tb_offset, self.tb_offset = self.tb_offset, tb_offset
998 tb_offset, self.tb_offset = self.tb_offset, tb_offset
959 print >> out, self.text(etype, evalue, etb)
999 print >> out, self.text(etype, evalue, etb)
960 self.tb_offset = tb_offset
1000 self.tb_offset = tb_offset
961 else:
1001 else:
962 print >> out, self.text(etype, evalue, etb)
1002 print >> out, self.text(etype, evalue, etb)
963 self.debugger()
1003 out.flush()
1004 try:
1005 self.debugger()
1006 except KeyboardInterrupt:
1007 print "\nKeyboardInterrupt"
964
1008
965 def text(self,etype=None,value=None,tb=None,context=5,mode=None):
1009 def text(self,etype=None,value=None,tb=None,context=5,mode=None):
966 if etype is None:
1010 if etype is None:
@@ -98,7 +98,7 b' from inspect import getsourcefile, getfile, getmodule,\\'
98 # Modified pdb which doesn't damage IPython's readline handling
98 # Modified pdb which doesn't damage IPython's readline handling
99 from IPython import Debugger, PyColorize
99 from IPython import Debugger, PyColorize
100 from IPython.ipstruct import Struct
100 from IPython.ipstruct import Struct
101 from IPython.excolors import ExceptionColors
101 from IPython.excolors import exception_colors
102 from IPython.genutils import Term,uniq_stable,error,info
102 from IPython.genutils import Term,uniq_stable,error,info
103
103
104 # Globals
104 # Globals
@@ -320,7 +320,7 b' class TBTools:'
320 self.call_pdb = call_pdb
320 self.call_pdb = call_pdb
321
321
322 # Create color table
322 # Create color table
323 self.color_scheme_table = ExceptionColors
323 self.color_scheme_table = exception_colors()
324
324
325 self.set_colors(color_scheme)
325 self.set_colors(color_scheme)
326 self.old_scheme = color_scheme # save initial value for toggles
326 self.old_scheme = color_scheme # save initial value for toggles
General Comments 0
You need to be logged in to leave comments. Login now