##// 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,11 +20,36 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 """Return a color table with fields for exception reporting.
25
26 The table is an instance of ColorSchemeTable with schemes added for
27 'Linux', 'LightBG' and 'NoColor' and fields for exception handling filled
28 in.
29
30 Examples:
31
32 >>> ec = exception_colors()
33 >>> ec.active_scheme_name
34 ''
35 >>> print ec.active_colors
36 None
37
38 Now we activate a color scheme:
39 >>> ec.set_active_scheme('NoColor')
40 >>> ec.active_scheme_name
41 'NoColor'
42 >>> ec.active_colors.keys()
43 ['em', 'caret', '__allownew', 'name', 'val', 'vName', 'Normal', 'normalEm',
44 'filename', 'linenoEm', 'excName', 'lineno', 'valEm', 'filenameEm',
45 'nameEm', 'line', 'topline']
46 """
47
48 ex_colors = ColorSchemeTable()
24
49
25 # Populate it with color schemes
50 # Populate it with color schemes
26 C = TermColors # shorthand and local lookup
51 C = TermColors # shorthand and local lookup
27 ExceptionColors.add_scheme(ColorScheme(
52 ex_colors.add_scheme(ColorScheme(
28 'NoColor',
53 'NoColor',
29 # The color to be used for the top line
54 # The color to be used for the top line
30 topline = C.NoColor,
55 topline = C.NoColor,
@@ -52,7 +77,7 b' ExceptionColors.add_scheme(ColorScheme('
52 ))
77 ))
53
78
54 # make some schemes as instances so we can copy them for modification easily
79 # make some schemes as instances so we can copy them for modification easily
55 ExceptionColors.add_scheme(ColorScheme(
80 ex_colors.add_scheme(ColorScheme(
56 'Linux',
81 'Linux',
57 # The color to be used for the top line
82 # The color to be used for the top line
58 topline = C.LightRed,
83 topline = C.LightRed,
@@ -80,7 +105,7 b' ExceptionColors.add_scheme(ColorScheme('
80 ))
105 ))
81
106
82 # For light backgrounds, swap dark/light colors
107 # For light backgrounds, swap dark/light colors
83 ExceptionColors.add_scheme(ColorScheme(
108 ex_colors.add_scheme(ColorScheme(
84 'LightBG',
109 'LightBG',
85 # The color to be used for the top line
110 # The color to be used for the top line
86 topline = C.Red,
111 topline = C.Red,
@@ -107,3 +132,12 b' ExceptionColors.add_scheme(ColorScheme('
107 caret = C.Normal,
132 caret = C.Normal,
108 Normal = C.Normal
133 Normal = C.Normal
109 ))
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)
138 # If the object is a frame, then trying to get the globals dict from its
139 # module won't work. Instead, the frame object itself has the globals
140 # dictionary.
141 globals_dict = None
142 if inspect.isframe(object):
143 # XXX: can this ever be false?
144 globals_dict = object.f_globals
145 else:
144 module = getmodule(object, file)
146 module = getmodule(object, file)
145 if module:
147 if module:
146 lines = linecache.getlines(file, module.__dict__)
148 globals_dict = module.__dict__
147 else:
149 lines = linecache.getlines(file, globals_dict)
148 lines = linecache.getlines(file)
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."""
@@ -425,6 +446,7 b' class ListTB(TBTools):'
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))
886 try:
848 self.debugger()
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)
1003 out.flush()
1004 try:
963 self.debugger()
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