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