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