##// END OF EJS Templates
Merge pull request #12601 from Carreau/show-frames
Matthias Bussonnier -
r26057:f5176ad0 merge
parent child Browse files
Show More
@@ -1,809 +1,813 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 Pdb debugger class.
3 Pdb debugger class.
4
4
5 Modified from the standard pdb.Pdb class to avoid including readline, so that
5 Modified from the standard pdb.Pdb class to avoid including readline, so that
6 the command line completion of other programs which include this isn't
6 the command line completion of other programs which include this isn't
7 damaged.
7 damaged.
8
8
9 In the future, this class will be expanded with improvements over the standard
9 In the future, this class will be expanded with improvements over the standard
10 pdb.
10 pdb.
11
11
12 The code in this file is mainly lifted out of cmd.py in Python 2.2, with minor
12 The code in this file is mainly lifted out of cmd.py in Python 2.2, with minor
13 changes. Licensing should therefore be under the standard Python terms. For
13 changes. Licensing should therefore be under the standard Python terms. For
14 details on the PSF (Python Software Foundation) standard license, see:
14 details on the PSF (Python Software Foundation) standard license, see:
15
15
16 https://docs.python.org/2/license.html
16 https://docs.python.org/2/license.html
17 """
17 """
18
18
19 #*****************************************************************************
19 #*****************************************************************************
20 #
20 #
21 # This file is licensed under the PSF license.
21 # This file is licensed under the PSF license.
22 #
22 #
23 # Copyright (C) 2001 Python Software Foundation, www.python.org
23 # Copyright (C) 2001 Python Software Foundation, www.python.org
24 # Copyright (C) 2005-2006 Fernando Perez. <fperez@colorado.edu>
24 # Copyright (C) 2005-2006 Fernando Perez. <fperez@colorado.edu>
25 #
25 #
26 #
26 #
27 #*****************************************************************************
27 #*****************************************************************************
28
28
29 import bdb
29 import bdb
30 import functools
30 import functools
31 import inspect
31 import inspect
32 import linecache
32 import linecache
33 import sys
33 import sys
34 import warnings
34 import warnings
35 import re
35 import re
36
36
37 from IPython import get_ipython
37 from IPython import get_ipython
38 from IPython.utils import PyColorize
38 from IPython.utils import PyColorize
39 from IPython.utils import coloransi, py3compat
39 from IPython.utils import coloransi, py3compat
40 from IPython.core.excolors import exception_colors
40 from IPython.core.excolors import exception_colors
41 from IPython.testing.skipdoctest import skip_doctest
41 from IPython.testing.skipdoctest import skip_doctest
42
42
43
43
44 prompt = 'ipdb> '
44 prompt = 'ipdb> '
45
45
46 #We have to check this directly from sys.argv, config struct not yet available
46 #We have to check this directly from sys.argv, config struct not yet available
47 from pdb import Pdb as OldPdb
47 from pdb import Pdb as OldPdb
48
48
49 # Allow the set_trace code to operate outside of an ipython instance, even if
49 # Allow the set_trace code to operate outside of an ipython instance, even if
50 # it does so with some limitations. The rest of this support is implemented in
50 # it does so with some limitations. The rest of this support is implemented in
51 # the Tracer constructor.
51 # the Tracer constructor.
52
52
53 def make_arrow(pad):
53 def make_arrow(pad):
54 """generate the leading arrow in front of traceback or debugger"""
54 """generate the leading arrow in front of traceback or debugger"""
55 if pad >= 2:
55 if pad >= 2:
56 return '-'*(pad-2) + '> '
56 return '-'*(pad-2) + '> '
57 elif pad == 1:
57 elif pad == 1:
58 return '>'
58 return '>'
59 return ''
59 return ''
60
60
61
61
62 def BdbQuit_excepthook(et, ev, tb, excepthook=None):
62 def BdbQuit_excepthook(et, ev, tb, excepthook=None):
63 """Exception hook which handles `BdbQuit` exceptions.
63 """Exception hook which handles `BdbQuit` exceptions.
64
64
65 All other exceptions are processed using the `excepthook`
65 All other exceptions are processed using the `excepthook`
66 parameter.
66 parameter.
67 """
67 """
68 warnings.warn("`BdbQuit_excepthook` is deprecated since version 5.1",
68 warnings.warn("`BdbQuit_excepthook` is deprecated since version 5.1",
69 DeprecationWarning, stacklevel=2)
69 DeprecationWarning, stacklevel=2)
70 if et==bdb.BdbQuit:
70 if et==bdb.BdbQuit:
71 print('Exiting Debugger.')
71 print('Exiting Debugger.')
72 elif excepthook is not None:
72 elif excepthook is not None:
73 excepthook(et, ev, tb)
73 excepthook(et, ev, tb)
74 else:
74 else:
75 # Backwards compatibility. Raise deprecation warning?
75 # Backwards compatibility. Raise deprecation warning?
76 BdbQuit_excepthook.excepthook_ori(et,ev,tb)
76 BdbQuit_excepthook.excepthook_ori(et,ev,tb)
77
77
78
78
79 def BdbQuit_IPython_excepthook(self,et,ev,tb,tb_offset=None):
79 def BdbQuit_IPython_excepthook(self,et,ev,tb,tb_offset=None):
80 warnings.warn(
80 warnings.warn(
81 "`BdbQuit_IPython_excepthook` is deprecated since version 5.1",
81 "`BdbQuit_IPython_excepthook` is deprecated since version 5.1",
82 DeprecationWarning, stacklevel=2)
82 DeprecationWarning, stacklevel=2)
83 print('Exiting Debugger.')
83 print('Exiting Debugger.')
84
84
85
85
86 class Tracer(object):
86 class Tracer(object):
87 """
87 """
88 DEPRECATED
88 DEPRECATED
89
89
90 Class for local debugging, similar to pdb.set_trace.
90 Class for local debugging, similar to pdb.set_trace.
91
91
92 Instances of this class, when called, behave like pdb.set_trace, but
92 Instances of this class, when called, behave like pdb.set_trace, but
93 providing IPython's enhanced capabilities.
93 providing IPython's enhanced capabilities.
94
94
95 This is implemented as a class which must be initialized in your own code
95 This is implemented as a class which must be initialized in your own code
96 and not as a standalone function because we need to detect at runtime
96 and not as a standalone function because we need to detect at runtime
97 whether IPython is already active or not. That detection is done in the
97 whether IPython is already active or not. That detection is done in the
98 constructor, ensuring that this code plays nicely with a running IPython,
98 constructor, ensuring that this code plays nicely with a running IPython,
99 while functioning acceptably (though with limitations) if outside of it.
99 while functioning acceptably (though with limitations) if outside of it.
100 """
100 """
101
101
102 @skip_doctest
102 @skip_doctest
103 def __init__(self, colors=None):
103 def __init__(self, colors=None):
104 """
104 """
105 DEPRECATED
105 DEPRECATED
106
106
107 Create a local debugger instance.
107 Create a local debugger instance.
108
108
109 Parameters
109 Parameters
110 ----------
110 ----------
111
111
112 colors : str, optional
112 colors : str, optional
113 The name of the color scheme to use, it must be one of IPython's
113 The name of the color scheme to use, it must be one of IPython's
114 valid color schemes. If not given, the function will default to
114 valid color schemes. If not given, the function will default to
115 the current IPython scheme when running inside IPython, and to
115 the current IPython scheme when running inside IPython, and to
116 'NoColor' otherwise.
116 'NoColor' otherwise.
117
117
118 Examples
118 Examples
119 --------
119 --------
120 ::
120 ::
121
121
122 from IPython.core.debugger import Tracer; debug_here = Tracer()
122 from IPython.core.debugger import Tracer; debug_here = Tracer()
123
123
124 Later in your code::
124 Later in your code::
125
125
126 debug_here() # -> will open up the debugger at that point.
126 debug_here() # -> will open up the debugger at that point.
127
127
128 Once the debugger activates, you can use all of its regular commands to
128 Once the debugger activates, you can use all of its regular commands to
129 step through code, set breakpoints, etc. See the pdb documentation
129 step through code, set breakpoints, etc. See the pdb documentation
130 from the Python standard library for usage details.
130 from the Python standard library for usage details.
131 """
131 """
132 warnings.warn("`Tracer` is deprecated since version 5.1, directly use "
132 warnings.warn("`Tracer` is deprecated since version 5.1, directly use "
133 "`IPython.core.debugger.Pdb.set_trace()`",
133 "`IPython.core.debugger.Pdb.set_trace()`",
134 DeprecationWarning, stacklevel=2)
134 DeprecationWarning, stacklevel=2)
135
135
136 ip = get_ipython()
136 ip = get_ipython()
137 if ip is None:
137 if ip is None:
138 # Outside of ipython, we set our own exception hook manually
138 # Outside of ipython, we set our own exception hook manually
139 sys.excepthook = functools.partial(BdbQuit_excepthook,
139 sys.excepthook = functools.partial(BdbQuit_excepthook,
140 excepthook=sys.excepthook)
140 excepthook=sys.excepthook)
141 def_colors = 'NoColor'
141 def_colors = 'NoColor'
142 else:
142 else:
143 # In ipython, we use its custom exception handler mechanism
143 # In ipython, we use its custom exception handler mechanism
144 def_colors = ip.colors
144 def_colors = ip.colors
145 ip.set_custom_exc((bdb.BdbQuit,), BdbQuit_IPython_excepthook)
145 ip.set_custom_exc((bdb.BdbQuit,), BdbQuit_IPython_excepthook)
146
146
147 if colors is None:
147 if colors is None:
148 colors = def_colors
148 colors = def_colors
149
149
150 # The stdlib debugger internally uses a modified repr from the `repr`
150 # The stdlib debugger internally uses a modified repr from the `repr`
151 # module, that limits the length of printed strings to a hardcoded
151 # module, that limits the length of printed strings to a hardcoded
152 # limit of 30 characters. That much trimming is too aggressive, let's
152 # limit of 30 characters. That much trimming is too aggressive, let's
153 # at least raise that limit to 80 chars, which should be enough for
153 # at least raise that limit to 80 chars, which should be enough for
154 # most interactive uses.
154 # most interactive uses.
155 try:
155 try:
156 from reprlib import aRepr
156 from reprlib import aRepr
157 aRepr.maxstring = 80
157 aRepr.maxstring = 80
158 except:
158 except:
159 # This is only a user-facing convenience, so any error we encounter
159 # This is only a user-facing convenience, so any error we encounter
160 # here can be warned about but can be otherwise ignored. These
160 # here can be warned about but can be otherwise ignored. These
161 # printouts will tell us about problems if this API changes
161 # printouts will tell us about problems if this API changes
162 import traceback
162 import traceback
163 traceback.print_exc()
163 traceback.print_exc()
164
164
165 self.debugger = Pdb(colors)
165 self.debugger = Pdb(colors)
166
166
167 def __call__(self):
167 def __call__(self):
168 """Starts an interactive debugger at the point where called.
168 """Starts an interactive debugger at the point where called.
169
169
170 This is similar to the pdb.set_trace() function from the std lib, but
170 This is similar to the pdb.set_trace() function from the std lib, but
171 using IPython's enhanced debugger."""
171 using IPython's enhanced debugger."""
172
172
173 self.debugger.set_trace(sys._getframe().f_back)
173 self.debugger.set_trace(sys._getframe().f_back)
174
174
175
175
176 RGX_EXTRA_INDENT = re.compile(r'(?<=\n)\s+')
176 RGX_EXTRA_INDENT = re.compile(r'(?<=\n)\s+')
177
177
178
178
179 def strip_indentation(multiline_string):
179 def strip_indentation(multiline_string):
180 return RGX_EXTRA_INDENT.sub('', multiline_string)
180 return RGX_EXTRA_INDENT.sub('', multiline_string)
181
181
182
182
183 def decorate_fn_with_doc(new_fn, old_fn, additional_text=""):
183 def decorate_fn_with_doc(new_fn, old_fn, additional_text=""):
184 """Make new_fn have old_fn's doc string. This is particularly useful
184 """Make new_fn have old_fn's doc string. This is particularly useful
185 for the ``do_...`` commands that hook into the help system.
185 for the ``do_...`` commands that hook into the help system.
186 Adapted from from a comp.lang.python posting
186 Adapted from from a comp.lang.python posting
187 by Duncan Booth."""
187 by Duncan Booth."""
188 def wrapper(*args, **kw):
188 def wrapper(*args, **kw):
189 return new_fn(*args, **kw)
189 return new_fn(*args, **kw)
190 if old_fn.__doc__:
190 if old_fn.__doc__:
191 wrapper.__doc__ = strip_indentation(old_fn.__doc__) + additional_text
191 wrapper.__doc__ = strip_indentation(old_fn.__doc__) + additional_text
192 return wrapper
192 return wrapper
193
193
194
194
195 class Pdb(OldPdb):
195 class Pdb(OldPdb):
196 """Modified Pdb class, does not load readline.
196 """Modified Pdb class, does not load readline.
197
197
198 for a standalone version that uses prompt_toolkit, see
198 for a standalone version that uses prompt_toolkit, see
199 `IPython.terminal.debugger.TerminalPdb` and
199 `IPython.terminal.debugger.TerminalPdb` and
200 `IPython.terminal.debugger.set_trace()`
200 `IPython.terminal.debugger.set_trace()`
201 """
201 """
202
202
203 def __init__(self, color_scheme=None, completekey=None,
203 def __init__(self, color_scheme=None, completekey=None,
204 stdin=None, stdout=None, context=5, **kwargs):
204 stdin=None, stdout=None, context=5, **kwargs):
205 """Create a new IPython debugger.
205 """Create a new IPython debugger.
206
206
207 :param color_scheme: Deprecated, do not use.
207 :param color_scheme: Deprecated, do not use.
208 :param completekey: Passed to pdb.Pdb.
208 :param completekey: Passed to pdb.Pdb.
209 :param stdin: Passed to pdb.Pdb.
209 :param stdin: Passed to pdb.Pdb.
210 :param stdout: Passed to pdb.Pdb.
210 :param stdout: Passed to pdb.Pdb.
211 :param context: Number of lines of source code context to show when
211 :param context: Number of lines of source code context to show when
212 displaying stacktrace information.
212 displaying stacktrace information.
213 :param kwargs: Passed to pdb.Pdb.
213 :param kwargs: Passed to pdb.Pdb.
214 The possibilities are python version dependent, see the python
214 The possibilities are python version dependent, see the python
215 docs for more info.
215 docs for more info.
216 """
216 """
217
217
218 # Parent constructor:
218 # Parent constructor:
219 try:
219 try:
220 self.context = int(context)
220 self.context = int(context)
221 if self.context <= 0:
221 if self.context <= 0:
222 raise ValueError("Context must be a positive integer")
222 raise ValueError("Context must be a positive integer")
223 except (TypeError, ValueError) as e:
223 except (TypeError, ValueError) as e:
224 raise ValueError("Context must be a positive integer") from e
224 raise ValueError("Context must be a positive integer") from e
225
225
226 # `kwargs` ensures full compatibility with stdlib's `pdb.Pdb`.
226 # `kwargs` ensures full compatibility with stdlib's `pdb.Pdb`.
227 OldPdb.__init__(self, completekey, stdin, stdout, **kwargs)
227 OldPdb.__init__(self, completekey, stdin, stdout, **kwargs)
228
228
229 # IPython changes...
229 # IPython changes...
230 self.shell = get_ipython()
230 self.shell = get_ipython()
231
231
232 if self.shell is None:
232 if self.shell is None:
233 save_main = sys.modules['__main__']
233 save_main = sys.modules['__main__']
234 # No IPython instance running, we must create one
234 # No IPython instance running, we must create one
235 from IPython.terminal.interactiveshell import \
235 from IPython.terminal.interactiveshell import \
236 TerminalInteractiveShell
236 TerminalInteractiveShell
237 self.shell = TerminalInteractiveShell.instance()
237 self.shell = TerminalInteractiveShell.instance()
238 # needed by any code which calls __import__("__main__") after
238 # needed by any code which calls __import__("__main__") after
239 # the debugger was entered. See also #9941.
239 # the debugger was entered. See also #9941.
240 sys.modules['__main__'] = save_main
240 sys.modules['__main__'] = save_main
241
241
242 if color_scheme is not None:
242 if color_scheme is not None:
243 warnings.warn(
243 warnings.warn(
244 "The `color_scheme` argument is deprecated since version 5.1",
244 "The `color_scheme` argument is deprecated since version 5.1",
245 DeprecationWarning, stacklevel=2)
245 DeprecationWarning, stacklevel=2)
246 else:
246 else:
247 color_scheme = self.shell.colors
247 color_scheme = self.shell.colors
248
248
249 self.aliases = {}
249 self.aliases = {}
250
250
251 # Create color table: we copy the default one from the traceback
251 # Create color table: we copy the default one from the traceback
252 # module and add a few attributes needed for debugging
252 # module and add a few attributes needed for debugging
253 self.color_scheme_table = exception_colors()
253 self.color_scheme_table = exception_colors()
254
254
255 # shorthands
255 # shorthands
256 C = coloransi.TermColors
256 C = coloransi.TermColors
257 cst = self.color_scheme_table
257 cst = self.color_scheme_table
258
258
259 cst['NoColor'].colors.prompt = C.NoColor
259 cst['NoColor'].colors.prompt = C.NoColor
260 cst['NoColor'].colors.breakpoint_enabled = C.NoColor
260 cst['NoColor'].colors.breakpoint_enabled = C.NoColor
261 cst['NoColor'].colors.breakpoint_disabled = C.NoColor
261 cst['NoColor'].colors.breakpoint_disabled = C.NoColor
262
262
263 cst['Linux'].colors.prompt = C.Green
263 cst['Linux'].colors.prompt = C.Green
264 cst['Linux'].colors.breakpoint_enabled = C.LightRed
264 cst['Linux'].colors.breakpoint_enabled = C.LightRed
265 cst['Linux'].colors.breakpoint_disabled = C.Red
265 cst['Linux'].colors.breakpoint_disabled = C.Red
266
266
267 cst['LightBG'].colors.prompt = C.Blue
267 cst['LightBG'].colors.prompt = C.Blue
268 cst['LightBG'].colors.breakpoint_enabled = C.LightRed
268 cst['LightBG'].colors.breakpoint_enabled = C.LightRed
269 cst['LightBG'].colors.breakpoint_disabled = C.Red
269 cst['LightBG'].colors.breakpoint_disabled = C.Red
270
270
271 cst['Neutral'].colors.prompt = C.Blue
271 cst['Neutral'].colors.prompt = C.Blue
272 cst['Neutral'].colors.breakpoint_enabled = C.LightRed
272 cst['Neutral'].colors.breakpoint_enabled = C.LightRed
273 cst['Neutral'].colors.breakpoint_disabled = C.Red
273 cst['Neutral'].colors.breakpoint_disabled = C.Red
274
274
275
275
276 # Add a python parser so we can syntax highlight source while
276 # Add a python parser so we can syntax highlight source while
277 # debugging.
277 # debugging.
278 self.parser = PyColorize.Parser(style=color_scheme)
278 self.parser = PyColorize.Parser(style=color_scheme)
279 self.set_colors(color_scheme)
279 self.set_colors(color_scheme)
280
280
281 # Set the prompt - the default prompt is '(Pdb)'
281 # Set the prompt - the default prompt is '(Pdb)'
282 self.prompt = prompt
282 self.prompt = prompt
283 self.skip_hidden = True
283 self.skip_hidden = True
284
284
285 def set_colors(self, scheme):
285 def set_colors(self, scheme):
286 """Shorthand access to the color table scheme selector method."""
286 """Shorthand access to the color table scheme selector method."""
287 self.color_scheme_table.set_active_scheme(scheme)
287 self.color_scheme_table.set_active_scheme(scheme)
288 self.parser.style = scheme
288 self.parser.style = scheme
289
289
290
290
291 def hidden_frames(self, stack):
291 def hidden_frames(self, stack):
292 """
292 """
293 Given an index in the stack return wether it should be skipped.
293 Given an index in the stack return whether it should be skipped.
294
294
295 This is used in up/down and where to skip frames.
295 This is used in up/down and where to skip frames.
296 """
296 """
297 # The f_locals dictionary is updated from the actual frame
297 # The f_locals dictionary is updated from the actual frame
298 # locals whenever the .f_locals accessor is called, so we
298 # locals whenever the .f_locals accessor is called, so we
299 # avoid calling it here to preserve self.curframe_locals.
299 # avoid calling it here to preserve self.curframe_locals.
300 # Futhermore, there is no good reason to hide the current frame.
300 # Futhermore, there is no good reason to hide the current frame.
301 ip_hide = [
301 ip_hide = [
302 False if s[0] is self.curframe else s[0].f_locals.get(
302 False if s[0] is self.curframe else s[0].f_locals.get(
303 "__tracebackhide__", False)
303 "__tracebackhide__", False)
304 for s in stack]
304 for s in stack]
305 ip_start = [i for i, s in enumerate(ip_hide) if s == "__ipython_bottom__"]
305 ip_start = [i for i, s in enumerate(ip_hide) if s == "__ipython_bottom__"]
306 if ip_start:
306 if ip_start:
307 ip_hide = [h if i > ip_start[0] else True for (i, h) in enumerate(ip_hide)]
307 ip_hide = [h if i > ip_start[0] else True for (i, h) in enumerate(ip_hide)]
308 return ip_hide
308 return ip_hide
309
309
310 def interaction(self, frame, traceback):
310 def interaction(self, frame, traceback):
311 try:
311 try:
312 OldPdb.interaction(self, frame, traceback)
312 OldPdb.interaction(self, frame, traceback)
313 except KeyboardInterrupt:
313 except KeyboardInterrupt:
314 self.stdout.write("\n" + self.shell.get_exception_only())
314 self.stdout.write("\n" + self.shell.get_exception_only())
315
315
316 def new_do_frame(self, arg):
316 def new_do_frame(self, arg):
317 OldPdb.do_frame(self, arg)
317 OldPdb.do_frame(self, arg)
318
318
319 def new_do_quit(self, arg):
319 def new_do_quit(self, arg):
320
320
321 if hasattr(self, 'old_all_completions'):
321 if hasattr(self, 'old_all_completions'):
322 self.shell.Completer.all_completions=self.old_all_completions
322 self.shell.Completer.all_completions=self.old_all_completions
323
323
324 return OldPdb.do_quit(self, arg)
324 return OldPdb.do_quit(self, arg)
325
325
326 do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit)
326 do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit)
327
327
328 def new_do_restart(self, arg):
328 def new_do_restart(self, arg):
329 """Restart command. In the context of ipython this is exactly the same
329 """Restart command. In the context of ipython this is exactly the same
330 thing as 'quit'."""
330 thing as 'quit'."""
331 self.msg("Restart doesn't make sense here. Using 'quit' instead.")
331 self.msg("Restart doesn't make sense here. Using 'quit' instead.")
332 return self.do_quit(arg)
332 return self.do_quit(arg)
333
333
334 def print_stack_trace(self, context=None):
334 def print_stack_trace(self, context=None):
335 Colors = self.color_scheme_table.active_colors
335 Colors = self.color_scheme_table.active_colors
336 ColorsNormal = Colors.Normal
336 ColorsNormal = Colors.Normal
337 if context is None:
337 if context is None:
338 context = self.context
338 context = self.context
339 try:
339 try:
340 context=int(context)
340 context=int(context)
341 if context <= 0:
341 if context <= 0:
342 raise ValueError("Context must be a positive integer")
342 raise ValueError("Context must be a positive integer")
343 except (TypeError, ValueError) as e:
343 except (TypeError, ValueError) as e:
344 raise ValueError("Context must be a positive integer") from e
344 raise ValueError("Context must be a positive integer") from e
345 try:
345 try:
346 skipped = 0
346 skipped = 0
347 for hidden, frame_lineno in zip(self.hidden_frames(self.stack), self.stack):
347 for hidden, frame_lineno in zip(self.hidden_frames(self.stack), self.stack):
348 if hidden and self.skip_hidden:
348 if hidden and self.skip_hidden:
349 skipped += 1
349 skipped += 1
350 continue
350 continue
351 if skipped:
351 if skipped:
352 print(
352 print(
353 f"{Colors.excName} [... skipping {skipped} hidden frame(s)]{ColorsNormal}\n"
353 f"{Colors.excName} [... skipping {skipped} hidden frame(s)]{ColorsNormal}\n"
354 )
354 )
355 skipped = 0
355 skipped = 0
356 self.print_stack_entry(frame_lineno, context=context)
356 self.print_stack_entry(frame_lineno, context=context)
357 if skipped:
357 if skipped:
358 print(
358 print(
359 f"{Colors.excName} [... skipping {skipped} hidden frame(s)]{ColorsNormal}\n"
359 f"{Colors.excName} [... skipping {skipped} hidden frame(s)]{ColorsNormal}\n"
360 )
360 )
361 except KeyboardInterrupt:
361 except KeyboardInterrupt:
362 pass
362 pass
363
363
364 def print_stack_entry(self, frame_lineno, prompt_prefix='\n-> ',
364 def print_stack_entry(self, frame_lineno, prompt_prefix='\n-> ',
365 context=None):
365 context=None):
366 if context is None:
366 if context is None:
367 context = self.context
367 context = self.context
368 try:
368 try:
369 context=int(context)
369 context=int(context)
370 if context <= 0:
370 if context <= 0:
371 raise ValueError("Context must be a positive integer")
371 raise ValueError("Context must be a positive integer")
372 except (TypeError, ValueError) as e:
372 except (TypeError, ValueError) as e:
373 raise ValueError("Context must be a positive integer") from e
373 raise ValueError("Context must be a positive integer") from e
374 print(self.format_stack_entry(frame_lineno, '', context), file=self.stdout)
374 print(self.format_stack_entry(frame_lineno, '', context), file=self.stdout)
375
375
376 # vds: >>
376 # vds: >>
377 frame, lineno = frame_lineno
377 frame, lineno = frame_lineno
378 filename = frame.f_code.co_filename
378 filename = frame.f_code.co_filename
379 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
379 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
380 # vds: <<
380 # vds: <<
381
381
382 def format_stack_entry(self, frame_lineno, lprefix=': ', context=None):
382 def format_stack_entry(self, frame_lineno, lprefix=': ', context=None):
383 if context is None:
383 if context is None:
384 context = self.context
384 context = self.context
385 try:
385 try:
386 context=int(context)
386 context=int(context)
387 if context <= 0:
387 if context <= 0:
388 print("Context must be a positive integer", file=self.stdout)
388 print("Context must be a positive integer", file=self.stdout)
389 except (TypeError, ValueError):
389 except (TypeError, ValueError):
390 print("Context must be a positive integer", file=self.stdout)
390 print("Context must be a positive integer", file=self.stdout)
391
391
392 import reprlib
392 import reprlib
393
393
394 ret = []
394 ret = []
395
395
396 Colors = self.color_scheme_table.active_colors
396 Colors = self.color_scheme_table.active_colors
397 ColorsNormal = Colors.Normal
397 ColorsNormal = Colors.Normal
398 tpl_link = u'%s%%s%s' % (Colors.filenameEm, ColorsNormal)
398 tpl_link = u'%s%%s%s' % (Colors.filenameEm, ColorsNormal)
399 tpl_call = u'%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal)
399 tpl_call = u'%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal)
400 tpl_line = u'%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
400 tpl_line = u'%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
401 tpl_line_em = u'%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line,
401 tpl_line_em = u'%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line,
402 ColorsNormal)
402 ColorsNormal)
403
403
404 frame, lineno = frame_lineno
404 frame, lineno = frame_lineno
405
405
406 return_value = ''
406 return_value = ''
407 if '__return__' in frame.f_locals:
407 if '__return__' in frame.f_locals:
408 rv = frame.f_locals['__return__']
408 rv = frame.f_locals['__return__']
409 #return_value += '->'
409 #return_value += '->'
410 return_value += reprlib.repr(rv) + '\n'
410 return_value += reprlib.repr(rv) + '\n'
411 ret.append(return_value)
411 ret.append(return_value)
412
412
413 #s = filename + '(' + `lineno` + ')'
413 #s = filename + '(' + `lineno` + ')'
414 filename = self.canonic(frame.f_code.co_filename)
414 filename = self.canonic(frame.f_code.co_filename)
415 link = tpl_link % py3compat.cast_unicode(filename)
415 link = tpl_link % py3compat.cast_unicode(filename)
416
416
417 if frame.f_code.co_name:
417 if frame.f_code.co_name:
418 func = frame.f_code.co_name
418 func = frame.f_code.co_name
419 else:
419 else:
420 func = "<lambda>"
420 func = "<lambda>"
421
421
422 call = ''
422 call = ''
423 if func != '?':
423 if func != '?':
424 if '__args__' in frame.f_locals:
424 if '__args__' in frame.f_locals:
425 args = reprlib.repr(frame.f_locals['__args__'])
425 args = reprlib.repr(frame.f_locals['__args__'])
426 else:
426 else:
427 args = '()'
427 args = '()'
428 call = tpl_call % (func, args)
428 call = tpl_call % (func, args)
429
429
430 # The level info should be generated in the same format pdb uses, to
430 # The level info should be generated in the same format pdb uses, to
431 # avoid breaking the pdbtrack functionality of python-mode in *emacs.
431 # avoid breaking the pdbtrack functionality of python-mode in *emacs.
432 if frame is self.curframe:
432 if frame is self.curframe:
433 ret.append('> ')
433 ret.append('> ')
434 else:
434 else:
435 ret.append(' ')
435 ret.append(' ')
436 ret.append(u'%s(%s)%s\n' % (link,lineno,call))
436 ret.append(u'%s(%s)%s\n' % (link,lineno,call))
437
437
438 start = lineno - 1 - context//2
438 start = lineno - 1 - context//2
439 lines = linecache.getlines(filename)
439 lines = linecache.getlines(filename)
440 start = min(start, len(lines) - context)
440 start = min(start, len(lines) - context)
441 start = max(start, 0)
441 start = max(start, 0)
442 lines = lines[start : start + context]
442 lines = lines[start : start + context]
443
443
444 for i,line in enumerate(lines):
444 for i,line in enumerate(lines):
445 show_arrow = (start + 1 + i == lineno)
445 show_arrow = (start + 1 + i == lineno)
446 linetpl = (frame is self.curframe or show_arrow) \
446 linetpl = (frame is self.curframe or show_arrow) \
447 and tpl_line_em \
447 and tpl_line_em \
448 or tpl_line
448 or tpl_line
449 ret.append(self.__format_line(linetpl, filename,
449 ret.append(self.__format_line(linetpl, filename,
450 start + 1 + i, line,
450 start + 1 + i, line,
451 arrow = show_arrow) )
451 arrow = show_arrow) )
452 return ''.join(ret)
452 return ''.join(ret)
453
453
454 def __format_line(self, tpl_line, filename, lineno, line, arrow = False):
454 def __format_line(self, tpl_line, filename, lineno, line, arrow = False):
455 bp_mark = ""
455 bp_mark = ""
456 bp_mark_color = ""
456 bp_mark_color = ""
457
457
458 new_line, err = self.parser.format2(line, 'str')
458 new_line, err = self.parser.format2(line, 'str')
459 if not err:
459 if not err:
460 line = new_line
460 line = new_line
461
461
462 bp = None
462 bp = None
463 if lineno in self.get_file_breaks(filename):
463 if lineno in self.get_file_breaks(filename):
464 bps = self.get_breaks(filename, lineno)
464 bps = self.get_breaks(filename, lineno)
465 bp = bps[-1]
465 bp = bps[-1]
466
466
467 if bp:
467 if bp:
468 Colors = self.color_scheme_table.active_colors
468 Colors = self.color_scheme_table.active_colors
469 bp_mark = str(bp.number)
469 bp_mark = str(bp.number)
470 bp_mark_color = Colors.breakpoint_enabled
470 bp_mark_color = Colors.breakpoint_enabled
471 if not bp.enabled:
471 if not bp.enabled:
472 bp_mark_color = Colors.breakpoint_disabled
472 bp_mark_color = Colors.breakpoint_disabled
473
473
474 numbers_width = 7
474 numbers_width = 7
475 if arrow:
475 if arrow:
476 # This is the line with the error
476 # This is the line with the error
477 pad = numbers_width - len(str(lineno)) - len(bp_mark)
477 pad = numbers_width - len(str(lineno)) - len(bp_mark)
478 num = '%s%s' % (make_arrow(pad), str(lineno))
478 num = '%s%s' % (make_arrow(pad), str(lineno))
479 else:
479 else:
480 num = '%*s' % (numbers_width - len(bp_mark), str(lineno))
480 num = '%*s' % (numbers_width - len(bp_mark), str(lineno))
481
481
482 return tpl_line % (bp_mark_color + bp_mark, num, line)
482 return tpl_line % (bp_mark_color + bp_mark, num, line)
483
483
484
484
485 def print_list_lines(self, filename, first, last):
485 def print_list_lines(self, filename, first, last):
486 """The printing (as opposed to the parsing part of a 'list'
486 """The printing (as opposed to the parsing part of a 'list'
487 command."""
487 command."""
488 try:
488 try:
489 Colors = self.color_scheme_table.active_colors
489 Colors = self.color_scheme_table.active_colors
490 ColorsNormal = Colors.Normal
490 ColorsNormal = Colors.Normal
491 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
491 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
492 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal)
492 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal)
493 src = []
493 src = []
494 if filename == "<string>" and hasattr(self, "_exec_filename"):
494 if filename == "<string>" and hasattr(self, "_exec_filename"):
495 filename = self._exec_filename
495 filename = self._exec_filename
496
496
497 for lineno in range(first, last+1):
497 for lineno in range(first, last+1):
498 line = linecache.getline(filename, lineno)
498 line = linecache.getline(filename, lineno)
499 if not line:
499 if not line:
500 break
500 break
501
501
502 if lineno == self.curframe.f_lineno:
502 if lineno == self.curframe.f_lineno:
503 line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True)
503 line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True)
504 else:
504 else:
505 line = self.__format_line(tpl_line, filename, lineno, line, arrow = False)
505 line = self.__format_line(tpl_line, filename, lineno, line, arrow = False)
506
506
507 src.append(line)
507 src.append(line)
508 self.lineno = lineno
508 self.lineno = lineno
509
509
510 print(''.join(src), file=self.stdout)
510 print(''.join(src), file=self.stdout)
511
511
512 except KeyboardInterrupt:
512 except KeyboardInterrupt:
513 pass
513 pass
514
514
515 def do_skip_hidden(self, arg):
515 def do_skip_hidden(self, arg):
516 """
516 """
517 Change whether or not we should skip frames with the
517 Change whether or not we should skip frames with the
518 __tracebackhide__ attribute.
518 __tracebackhide__ attribute.
519 """
519 """
520 if arg.strip().lower() in ("true", "yes"):
520 if arg.strip().lower() in ("true", "yes"):
521 self.skip_hidden = True
521 self.skip_hidden = True
522 elif arg.strip().lower() in ("false", "no"):
522 elif arg.strip().lower() in ("false", "no"):
523 self.skip_hidden = False
523 self.skip_hidden = False
524
524
525 def do_list(self, arg):
525 def do_list(self, arg):
526 """Print lines of code from the current stack frame
526 """Print lines of code from the current stack frame
527 """
527 """
528 self.lastcmd = 'list'
528 self.lastcmd = 'list'
529 last = None
529 last = None
530 if arg:
530 if arg:
531 try:
531 try:
532 x = eval(arg, {}, {})
532 x = eval(arg, {}, {})
533 if type(x) == type(()):
533 if type(x) == type(()):
534 first, last = x
534 first, last = x
535 first = int(first)
535 first = int(first)
536 last = int(last)
536 last = int(last)
537 if last < first:
537 if last < first:
538 # Assume it's a count
538 # Assume it's a count
539 last = first + last
539 last = first + last
540 else:
540 else:
541 first = max(1, int(x) - 5)
541 first = max(1, int(x) - 5)
542 except:
542 except:
543 print('*** Error in argument:', repr(arg), file=self.stdout)
543 print('*** Error in argument:', repr(arg), file=self.stdout)
544 return
544 return
545 elif self.lineno is None:
545 elif self.lineno is None:
546 first = max(1, self.curframe.f_lineno - 5)
546 first = max(1, self.curframe.f_lineno - 5)
547 else:
547 else:
548 first = self.lineno + 1
548 first = self.lineno + 1
549 if last is None:
549 if last is None:
550 last = first + 10
550 last = first + 10
551 self.print_list_lines(self.curframe.f_code.co_filename, first, last)
551 self.print_list_lines(self.curframe.f_code.co_filename, first, last)
552
552
553 # vds: >>
553 # vds: >>
554 lineno = first
554 lineno = first
555 filename = self.curframe.f_code.co_filename
555 filename = self.curframe.f_code.co_filename
556 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
556 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
557 # vds: <<
557 # vds: <<
558
558
559 do_l = do_list
559 do_l = do_list
560
560
561 def getsourcelines(self, obj):
561 def getsourcelines(self, obj):
562 lines, lineno = inspect.findsource(obj)
562 lines, lineno = inspect.findsource(obj)
563 if inspect.isframe(obj) and obj.f_globals is obj.f_locals:
563 if inspect.isframe(obj) and obj.f_globals is obj.f_locals:
564 # must be a module frame: do not try to cut a block out of it
564 # must be a module frame: do not try to cut a block out of it
565 return lines, 1
565 return lines, 1
566 elif inspect.ismodule(obj):
566 elif inspect.ismodule(obj):
567 return lines, 1
567 return lines, 1
568 return inspect.getblock(lines[lineno:]), lineno+1
568 return inspect.getblock(lines[lineno:]), lineno+1
569
569
570 def do_longlist(self, arg):
570 def do_longlist(self, arg):
571 """Print lines of code from the current stack frame.
571 """Print lines of code from the current stack frame.
572
572
573 Shows more lines than 'list' does.
573 Shows more lines than 'list' does.
574 """
574 """
575 self.lastcmd = 'longlist'
575 self.lastcmd = 'longlist'
576 try:
576 try:
577 lines, lineno = self.getsourcelines(self.curframe)
577 lines, lineno = self.getsourcelines(self.curframe)
578 except OSError as err:
578 except OSError as err:
579 self.error(err)
579 self.error(err)
580 return
580 return
581 last = lineno + len(lines)
581 last = lineno + len(lines)
582 self.print_list_lines(self.curframe.f_code.co_filename, lineno, last)
582 self.print_list_lines(self.curframe.f_code.co_filename, lineno, last)
583 do_ll = do_longlist
583 do_ll = do_longlist
584
584
585 def do_debug(self, arg):
585 def do_debug(self, arg):
586 """debug code
586 """debug code
587 Enter a recursive debugger that steps through the code
587 Enter a recursive debugger that steps through the code
588 argument (which is an arbitrary expression or statement to be
588 argument (which is an arbitrary expression or statement to be
589 executed in the current environment).
589 executed in the current environment).
590 """
590 """
591 sys.settrace(None)
591 sys.settrace(None)
592 globals = self.curframe.f_globals
592 globals = self.curframe.f_globals
593 locals = self.curframe_locals
593 locals = self.curframe_locals
594 p = self.__class__(completekey=self.completekey,
594 p = self.__class__(completekey=self.completekey,
595 stdin=self.stdin, stdout=self.stdout)
595 stdin=self.stdin, stdout=self.stdout)
596 p.use_rawinput = self.use_rawinput
596 p.use_rawinput = self.use_rawinput
597 p.prompt = "(%s) " % self.prompt.strip()
597 p.prompt = "(%s) " % self.prompt.strip()
598 self.message("ENTERING RECURSIVE DEBUGGER")
598 self.message("ENTERING RECURSIVE DEBUGGER")
599 sys.call_tracing(p.run, (arg, globals, locals))
599 sys.call_tracing(p.run, (arg, globals, locals))
600 self.message("LEAVING RECURSIVE DEBUGGER")
600 self.message("LEAVING RECURSIVE DEBUGGER")
601 sys.settrace(self.trace_dispatch)
601 sys.settrace(self.trace_dispatch)
602 self.lastcmd = p.lastcmd
602 self.lastcmd = p.lastcmd
603
603
604 def do_pdef(self, arg):
604 def do_pdef(self, arg):
605 """Print the call signature for any callable object.
605 """Print the call signature for any callable object.
606
606
607 The debugger interface to %pdef"""
607 The debugger interface to %pdef"""
608 namespaces = [('Locals', self.curframe.f_locals),
608 namespaces = [('Locals', self.curframe.f_locals),
609 ('Globals', self.curframe.f_globals)]
609 ('Globals', self.curframe.f_globals)]
610 self.shell.find_line_magic('pdef')(arg, namespaces=namespaces)
610 self.shell.find_line_magic('pdef')(arg, namespaces=namespaces)
611
611
612 def do_pdoc(self, arg):
612 def do_pdoc(self, arg):
613 """Print the docstring for an object.
613 """Print the docstring for an object.
614
614
615 The debugger interface to %pdoc."""
615 The debugger interface to %pdoc."""
616 namespaces = [('Locals', self.curframe.f_locals),
616 namespaces = [('Locals', self.curframe.f_locals),
617 ('Globals', self.curframe.f_globals)]
617 ('Globals', self.curframe.f_globals)]
618 self.shell.find_line_magic('pdoc')(arg, namespaces=namespaces)
618 self.shell.find_line_magic('pdoc')(arg, namespaces=namespaces)
619
619
620 def do_pfile(self, arg):
620 def do_pfile(self, arg):
621 """Print (or run through pager) the file where an object is defined.
621 """Print (or run through pager) the file where an object is defined.
622
622
623 The debugger interface to %pfile.
623 The debugger interface to %pfile.
624 """
624 """
625 namespaces = [('Locals', self.curframe.f_locals),
625 namespaces = [('Locals', self.curframe.f_locals),
626 ('Globals', self.curframe.f_globals)]
626 ('Globals', self.curframe.f_globals)]
627 self.shell.find_line_magic('pfile')(arg, namespaces=namespaces)
627 self.shell.find_line_magic('pfile')(arg, namespaces=namespaces)
628
628
629 def do_pinfo(self, arg):
629 def do_pinfo(self, arg):
630 """Provide detailed information about an object.
630 """Provide detailed information about an object.
631
631
632 The debugger interface to %pinfo, i.e., obj?."""
632 The debugger interface to %pinfo, i.e., obj?."""
633 namespaces = [('Locals', self.curframe.f_locals),
633 namespaces = [('Locals', self.curframe.f_locals),
634 ('Globals', self.curframe.f_globals)]
634 ('Globals', self.curframe.f_globals)]
635 self.shell.find_line_magic('pinfo')(arg, namespaces=namespaces)
635 self.shell.find_line_magic('pinfo')(arg, namespaces=namespaces)
636
636
637 def do_pinfo2(self, arg):
637 def do_pinfo2(self, arg):
638 """Provide extra detailed information about an object.
638 """Provide extra detailed information about an object.
639
639
640 The debugger interface to %pinfo2, i.e., obj??."""
640 The debugger interface to %pinfo2, i.e., obj??."""
641 namespaces = [('Locals', self.curframe.f_locals),
641 namespaces = [('Locals', self.curframe.f_locals),
642 ('Globals', self.curframe.f_globals)]
642 ('Globals', self.curframe.f_globals)]
643 self.shell.find_line_magic('pinfo2')(arg, namespaces=namespaces)
643 self.shell.find_line_magic('pinfo2')(arg, namespaces=namespaces)
644
644
645 def do_psource(self, arg):
645 def do_psource(self, arg):
646 """Print (or run through pager) the source code for an object."""
646 """Print (or run through pager) the source code for an object."""
647 namespaces = [('Locals', self.curframe.f_locals),
647 namespaces = [('Locals', self.curframe.f_locals),
648 ('Globals', self.curframe.f_globals)]
648 ('Globals', self.curframe.f_globals)]
649 self.shell.find_line_magic('psource')(arg, namespaces=namespaces)
649 self.shell.find_line_magic('psource')(arg, namespaces=namespaces)
650
650
651 def do_where(self, arg):
651 def do_where(self, arg):
652 """w(here)
652 """w(here)
653 Print a stack trace, with the most recent frame at the bottom.
653 Print a stack trace, with the most recent frame at the bottom.
654 An arrow indicates the "current frame", which determines the
654 An arrow indicates the "current frame", which determines the
655 context of most commands. 'bt' is an alias for this command.
655 context of most commands. 'bt' is an alias for this command.
656
656
657 Take a number as argument as an (optional) number of context line to
657 Take a number as argument as an (optional) number of context line to
658 print"""
658 print"""
659 if arg:
659 if arg:
660 try:
660 try:
661 context = int(arg)
661 context = int(arg)
662 except ValueError as err:
662 except ValueError as err:
663 self.error(err)
663 self.error(err)
664 return
664 return
665 self.print_stack_trace(context)
665 self.print_stack_trace(context)
666 else:
666 else:
667 self.print_stack_trace()
667 self.print_stack_trace()
668
668
669 do_w = do_where
669 do_w = do_where
670
670
671 def stop_here(self, frame):
671 def stop_here(self, frame):
672 hidden = False
672 hidden = False
673 if self.skip_hidden:
673 if self.skip_hidden:
674 hidden = frame.f_locals.get("__tracebackhide__", False)
674 hidden = frame.f_locals.get("__tracebackhide__", False)
675 if hidden:
675 if hidden:
676 Colors = self.color_scheme_table.active_colors
676 Colors = self.color_scheme_table.active_colors
677 ColorsNormal = Colors.Normal
677 ColorsNormal = Colors.Normal
678 print(f"{Colors.excName} [... skipped 1 hidden frame]{ColorsNormal}\n")
678 print(f"{Colors.excName} [... skipped 1 hidden frame]{ColorsNormal}\n")
679
679
680 return super().stop_here(frame)
680 return super().stop_here(frame)
681
681
682 def do_up(self, arg):
682 def do_up(self, arg):
683 """u(p) [count]
683 """u(p) [count]
684 Move the current frame count (default one) levels up in the
684 Move the current frame count (default one) levels up in the
685 stack trace (to an older frame).
685 stack trace (to an older frame).
686
686
687 Will skip hidden frames.
687 Will skip hidden frames.
688 """
688 """
689 ## modified version of upstream that skips
689 ## modified version of upstream that skips
690 # frames with __tracebackide__
690 # frames with __tracebackide__
691 if self.curindex == 0:
691 if self.curindex == 0:
692 self.error("Oldest frame")
692 self.error("Oldest frame")
693 return
693 return
694 try:
694 try:
695 count = int(arg or 1)
695 count = int(arg or 1)
696 except ValueError:
696 except ValueError:
697 self.error("Invalid frame count (%s)" % arg)
697 self.error("Invalid frame count (%s)" % arg)
698 return
698 return
699 skipped = 0
699 skipped = 0
700 if count < 0:
700 if count < 0:
701 _newframe = 0
701 _newframe = 0
702 else:
702 else:
703 _newindex = self.curindex
703 _newindex = self.curindex
704 counter = 0
704 counter = 0
705 hidden_frames = self.hidden_frames(self.stack)
705 hidden_frames = self.hidden_frames(self.stack)
706 for i in range(self.curindex - 1, -1, -1):
706 for i in range(self.curindex - 1, -1, -1):
707 frame = self.stack[i][0]
707 frame = self.stack[i][0]
708 if hidden_frames[i] and self.skip_hidden:
708 if hidden_frames[i] and self.skip_hidden:
709 skipped += 1
709 skipped += 1
710 continue
710 continue
711 counter += 1
711 counter += 1
712 if counter >= count:
712 if counter >= count:
713 break
713 break
714 else:
714 else:
715 # if no break occured.
715 # if no break occured.
716 self.error("all frames above hidden")
716 self.error(
717 "all frames above hidden, use `skip_hidden False` to get get into those."
718 )
717 return
719 return
718
720
719 Colors = self.color_scheme_table.active_colors
721 Colors = self.color_scheme_table.active_colors
720 ColorsNormal = Colors.Normal
722 ColorsNormal = Colors.Normal
721 _newframe = i
723 _newframe = i
722 self._select_frame(_newframe)
724 self._select_frame(_newframe)
723 if skipped:
725 if skipped:
724 print(
726 print(
725 f"{Colors.excName} [... skipped {skipped} hidden frame(s)]{ColorsNormal}\n"
727 f"{Colors.excName} [... skipped {skipped} hidden frame(s)]{ColorsNormal}\n"
726 )
728 )
727
729
728 def do_down(self, arg):
730 def do_down(self, arg):
729 """d(own) [count]
731 """d(own) [count]
730 Move the current frame count (default one) levels down in the
732 Move the current frame count (default one) levels down in the
731 stack trace (to a newer frame).
733 stack trace (to a newer frame).
732
734
733 Will skip hidden frames.
735 Will skip hidden frames.
734 """
736 """
735 if self.curindex + 1 == len(self.stack):
737 if self.curindex + 1 == len(self.stack):
736 self.error("Newest frame")
738 self.error("Newest frame")
737 return
739 return
738 try:
740 try:
739 count = int(arg or 1)
741 count = int(arg or 1)
740 except ValueError:
742 except ValueError:
741 self.error("Invalid frame count (%s)" % arg)
743 self.error("Invalid frame count (%s)" % arg)
742 return
744 return
743 if count < 0:
745 if count < 0:
744 _newframe = len(self.stack) - 1
746 _newframe = len(self.stack) - 1
745 else:
747 else:
746 _newindex = self.curindex
748 _newindex = self.curindex
747 counter = 0
749 counter = 0
748 skipped = 0
750 skipped = 0
749 hidden_frames = self.hidden_frames(self.stack)
751 hidden_frames = self.hidden_frames(self.stack)
750 for i in range(self.curindex + 1, len(self.stack)):
752 for i in range(self.curindex + 1, len(self.stack)):
751 frame = self.stack[i][0]
753 frame = self.stack[i][0]
752 if hidden_frames[i] and self.skip_hidden:
754 if hidden_frames[i] and self.skip_hidden:
753 skipped += 1
755 skipped += 1
754 continue
756 continue
755 counter += 1
757 counter += 1
756 if counter >= count:
758 if counter >= count:
757 break
759 break
758 else:
760 else:
759 self.error("all frames bellow hidden")
761 self.error(
762 "all frames bellow hidden, use `skip_hidden False` to get get into those."
763 )
760 return
764 return
761
765
762 Colors = self.color_scheme_table.active_colors
766 Colors = self.color_scheme_table.active_colors
763 ColorsNormal = Colors.Normal
767 ColorsNormal = Colors.Normal
764 if skipped:
768 if skipped:
765 print(
769 print(
766 f"{Colors.excName} [... skipped {skipped} hidden frame(s)]{ColorsNormal}\n"
770 f"{Colors.excName} [... skipped {skipped} hidden frame(s)]{ColorsNormal}\n"
767 )
771 )
768 _newframe = i
772 _newframe = i
769
773
770 self._select_frame(_newframe)
774 self._select_frame(_newframe)
771
775
772 do_d = do_down
776 do_d = do_down
773 do_u = do_up
777 do_u = do_up
774
778
775 class InterruptiblePdb(Pdb):
779 class InterruptiblePdb(Pdb):
776 """Version of debugger where KeyboardInterrupt exits the debugger altogether."""
780 """Version of debugger where KeyboardInterrupt exits the debugger altogether."""
777
781
778 def cmdloop(self):
782 def cmdloop(self):
779 """Wrap cmdloop() such that KeyboardInterrupt stops the debugger."""
783 """Wrap cmdloop() such that KeyboardInterrupt stops the debugger."""
780 try:
784 try:
781 return OldPdb.cmdloop(self)
785 return OldPdb.cmdloop(self)
782 except KeyboardInterrupt:
786 except KeyboardInterrupt:
783 self.stop_here = lambda frame: False
787 self.stop_here = lambda frame: False
784 self.do_quit("")
788 self.do_quit("")
785 sys.settrace(None)
789 sys.settrace(None)
786 self.quitting = False
790 self.quitting = False
787 raise
791 raise
788
792
789 def _cmdloop(self):
793 def _cmdloop(self):
790 while True:
794 while True:
791 try:
795 try:
792 # keyboard interrupts allow for an easy way to cancel
796 # keyboard interrupts allow for an easy way to cancel
793 # the current command, so allow them during interactive input
797 # the current command, so allow them during interactive input
794 self.allow_kbdint = True
798 self.allow_kbdint = True
795 self.cmdloop()
799 self.cmdloop()
796 self.allow_kbdint = False
800 self.allow_kbdint = False
797 break
801 break
798 except KeyboardInterrupt:
802 except KeyboardInterrupt:
799 self.message('--KeyboardInterrupt--')
803 self.message('--KeyboardInterrupt--')
800 raise
804 raise
801
805
802
806
803 def set_trace(frame=None):
807 def set_trace(frame=None):
804 """
808 """
805 Start debugging from `frame`.
809 Start debugging from `frame`.
806
810
807 If frame is not specified, debugging starts from caller's frame.
811 If frame is not specified, debugging starts from caller's frame.
808 """
812 """
809 Pdb().set_trace(frame or sys._getframe().f_back)
813 Pdb().set_trace(frame or sys._getframe().f_back)
@@ -1,1086 +1,1087 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 Verbose and colourful traceback formatting.
3 Verbose and colourful traceback formatting.
4
4
5 **ColorTB**
5 **ColorTB**
6
6
7 I've always found it a bit hard to visually parse tracebacks in Python. The
7 I've always found it a bit hard to visually parse tracebacks in Python. The
8 ColorTB class is a solution to that problem. It colors the different parts of a
8 ColorTB class is a solution to that problem. It colors the different parts of a
9 traceback in a manner similar to what you would expect from a syntax-highlighting
9 traceback in a manner similar to what you would expect from a syntax-highlighting
10 text editor.
10 text editor.
11
11
12 Installation instructions for ColorTB::
12 Installation instructions for ColorTB::
13
13
14 import sys,ultratb
14 import sys,ultratb
15 sys.excepthook = ultratb.ColorTB()
15 sys.excepthook = ultratb.ColorTB()
16
16
17 **VerboseTB**
17 **VerboseTB**
18
18
19 I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds
19 I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds
20 of useful info when a traceback occurs. Ping originally had it spit out HTML
20 of useful info when a traceback occurs. Ping originally had it spit out HTML
21 and intended it for CGI programmers, but why should they have all the fun? I
21 and intended it for CGI programmers, but why should they have all the fun? I
22 altered it to spit out colored text to the terminal. It's a bit overwhelming,
22 altered it to spit out colored text to the terminal. It's a bit overwhelming,
23 but kind of neat, and maybe useful for long-running programs that you believe
23 but kind of neat, and maybe useful for long-running programs that you believe
24 are bug-free. If a crash *does* occur in that type of program you want details.
24 are bug-free. If a crash *does* occur in that type of program you want details.
25 Give it a shot--you'll love it or you'll hate it.
25 Give it a shot--you'll love it or you'll hate it.
26
26
27 .. note::
27 .. note::
28
28
29 The Verbose mode prints the variables currently visible where the exception
29 The Verbose mode prints the variables currently visible where the exception
30 happened (shortening their strings if too long). This can potentially be
30 happened (shortening their strings if too long). This can potentially be
31 very slow, if you happen to have a huge data structure whose string
31 very slow, if you happen to have a huge data structure whose string
32 representation is complex to compute. Your computer may appear to freeze for
32 representation is complex to compute. Your computer may appear to freeze for
33 a while with cpu usage at 100%. If this occurs, you can cancel the traceback
33 a while with cpu usage at 100%. If this occurs, you can cancel the traceback
34 with Ctrl-C (maybe hitting it more than once).
34 with Ctrl-C (maybe hitting it more than once).
35
35
36 If you encounter this kind of situation often, you may want to use the
36 If you encounter this kind of situation often, you may want to use the
37 Verbose_novars mode instead of the regular Verbose, which avoids formatting
37 Verbose_novars mode instead of the regular Verbose, which avoids formatting
38 variables (but otherwise includes the information and context given by
38 variables (but otherwise includes the information and context given by
39 Verbose).
39 Verbose).
40
40
41 .. note::
41 .. note::
42
42
43 The verbose mode print all variables in the stack, which means it can
43 The verbose mode print all variables in the stack, which means it can
44 potentially leak sensitive information like access keys, or unencrypted
44 potentially leak sensitive information like access keys, or unencrypted
45 password.
45 password.
46
46
47 Installation instructions for VerboseTB::
47 Installation instructions for VerboseTB::
48
48
49 import sys,ultratb
49 import sys,ultratb
50 sys.excepthook = ultratb.VerboseTB()
50 sys.excepthook = ultratb.VerboseTB()
51
51
52 Note: Much of the code in this module was lifted verbatim from the standard
52 Note: Much of the code in this module was lifted verbatim from the standard
53 library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'.
53 library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'.
54
54
55 Color schemes
55 Color schemes
56 -------------
56 -------------
57
57
58 The colors are defined in the class TBTools through the use of the
58 The colors are defined in the class TBTools through the use of the
59 ColorSchemeTable class. Currently the following exist:
59 ColorSchemeTable class. Currently the following exist:
60
60
61 - NoColor: allows all of this module to be used in any terminal (the color
61 - NoColor: allows all of this module to be used in any terminal (the color
62 escapes are just dummy blank strings).
62 escapes are just dummy blank strings).
63
63
64 - Linux: is meant to look good in a terminal like the Linux console (black
64 - Linux: is meant to look good in a terminal like the Linux console (black
65 or very dark background).
65 or very dark background).
66
66
67 - LightBG: similar to Linux but swaps dark/light colors to be more readable
67 - LightBG: similar to Linux but swaps dark/light colors to be more readable
68 in light background terminals.
68 in light background terminals.
69
69
70 - Neutral: a neutral color scheme that should be readable on both light and
70 - Neutral: a neutral color scheme that should be readable on both light and
71 dark background
71 dark background
72
72
73 You can implement other color schemes easily, the syntax is fairly
73 You can implement other color schemes easily, the syntax is fairly
74 self-explanatory. Please send back new schemes you develop to the author for
74 self-explanatory. Please send back new schemes you develop to the author for
75 possible inclusion in future releases.
75 possible inclusion in future releases.
76
76
77 Inheritance diagram:
77 Inheritance diagram:
78
78
79 .. inheritance-diagram:: IPython.core.ultratb
79 .. inheritance-diagram:: IPython.core.ultratb
80 :parts: 3
80 :parts: 3
81 """
81 """
82
82
83 #*****************************************************************************
83 #*****************************************************************************
84 # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
84 # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
85 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
85 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
86 #
86 #
87 # Distributed under the terms of the BSD License. The full license is in
87 # Distributed under the terms of the BSD License. The full license is in
88 # the file COPYING, distributed as part of this software.
88 # the file COPYING, distributed as part of this software.
89 #*****************************************************************************
89 #*****************************************************************************
90
90
91
91
92 import inspect
92 import inspect
93 import linecache
93 import linecache
94 import pydoc
94 import pydoc
95 import sys
95 import sys
96 import time
96 import time
97 import traceback
97 import traceback
98
98
99 import stack_data
99 import stack_data
100 from pygments.formatters.terminal256 import Terminal256Formatter
100 from pygments.formatters.terminal256 import Terminal256Formatter
101 from pygments.styles import get_style_by_name
101 from pygments.styles import get_style_by_name
102
102
103 # IPython's own modules
103 # IPython's own modules
104 from IPython import get_ipython
104 from IPython import get_ipython
105 from IPython.core import debugger
105 from IPython.core import debugger
106 from IPython.core.display_trap import DisplayTrap
106 from IPython.core.display_trap import DisplayTrap
107 from IPython.core.excolors import exception_colors
107 from IPython.core.excolors import exception_colors
108 from IPython.utils import path as util_path
108 from IPython.utils import path as util_path
109 from IPython.utils import py3compat
109 from IPython.utils import py3compat
110 from IPython.utils.terminal import get_terminal_size
110 from IPython.utils.terminal import get_terminal_size
111
111
112 import IPython.utils.colorable as colorable
112 import IPython.utils.colorable as colorable
113
113
114 # Globals
114 # Globals
115 # amount of space to put line numbers before verbose tracebacks
115 # amount of space to put line numbers before verbose tracebacks
116 INDENT_SIZE = 8
116 INDENT_SIZE = 8
117
117
118 # Default color scheme. This is used, for example, by the traceback
118 # Default color scheme. This is used, for example, by the traceback
119 # formatter. When running in an actual IPython instance, the user's rc.colors
119 # formatter. When running in an actual IPython instance, the user's rc.colors
120 # value is used, but having a module global makes this functionality available
120 # value is used, but having a module global makes this functionality available
121 # to users of ultratb who are NOT running inside ipython.
121 # to users of ultratb who are NOT running inside ipython.
122 DEFAULT_SCHEME = 'NoColor'
122 DEFAULT_SCHEME = 'NoColor'
123
123
124 # ---------------------------------------------------------------------------
124 # ---------------------------------------------------------------------------
125 # Code begins
125 # Code begins
126
126
127 # Helper function -- largely belongs to VerboseTB, but we need the same
127 # Helper function -- largely belongs to VerboseTB, but we need the same
128 # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they
128 # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they
129 # can be recognized properly by ipython.el's py-traceback-line-re
129 # can be recognized properly by ipython.el's py-traceback-line-re
130 # (SyntaxErrors have to be treated specially because they have no traceback)
130 # (SyntaxErrors have to be treated specially because they have no traceback)
131
131
132
132
133 def _format_traceback_lines(lines, Colors, has_colors, lvals):
133 def _format_traceback_lines(lines, Colors, has_colors, lvals):
134 """
134 """
135 Format tracebacks lines with pointing arrow, leading numbers...
135 Format tracebacks lines with pointing arrow, leading numbers...
136
136
137 Parameters
137 Parameters
138 ----------
138 ----------
139 lines : list[Line]
139 lines : list[Line]
140 Colors
140 Colors
141 ColorScheme used.
141 ColorScheme used.
142 lvals : str
142 lvals : str
143 Values of local variables, already colored, to inject just after the error line.
143 Values of local variables, already colored, to inject just after the error line.
144 """
144 """
145 numbers_width = INDENT_SIZE - 1
145 numbers_width = INDENT_SIZE - 1
146 res = []
146 res = []
147
147
148 for stack_line in lines:
148 for stack_line in lines:
149 if stack_line is stack_data.LINE_GAP:
149 if stack_line is stack_data.LINE_GAP:
150 res.append('%s (...)%s\n' % (Colors.linenoEm, Colors.Normal))
150 res.append('%s (...)%s\n' % (Colors.linenoEm, Colors.Normal))
151 continue
151 continue
152
152
153 line = stack_line.render(pygmented=has_colors).rstrip('\n') + '\n'
153 line = stack_line.render(pygmented=has_colors).rstrip('\n') + '\n'
154 lineno = stack_line.lineno
154 lineno = stack_line.lineno
155 if stack_line.is_current:
155 if stack_line.is_current:
156 # This is the line with the error
156 # This is the line with the error
157 pad = numbers_width - len(str(lineno))
157 pad = numbers_width - len(str(lineno))
158 num = '%s%s' % (debugger.make_arrow(pad), str(lineno))
158 num = '%s%s' % (debugger.make_arrow(pad), str(lineno))
159 start_color = Colors.linenoEm
159 start_color = Colors.linenoEm
160 else:
160 else:
161 num = '%*s' % (numbers_width, lineno)
161 num = '%*s' % (numbers_width, lineno)
162 start_color = Colors.lineno
162 start_color = Colors.lineno
163
163
164 line = '%s%s%s %s' % (start_color, num, Colors.Normal, line)
164 line = '%s%s%s %s' % (start_color, num, Colors.Normal, line)
165
165
166 res.append(line)
166 res.append(line)
167 if lvals and stack_line.is_current:
167 if lvals and stack_line.is_current:
168 res.append(lvals + '\n')
168 res.append(lvals + '\n')
169 return res
169 return res
170
170
171
171
172 #---------------------------------------------------------------------------
172 #---------------------------------------------------------------------------
173 # Module classes
173 # Module classes
174 class TBTools(colorable.Colorable):
174 class TBTools(colorable.Colorable):
175 """Basic tools used by all traceback printer classes."""
175 """Basic tools used by all traceback printer classes."""
176
176
177 # Number of frames to skip when reporting tracebacks
177 # Number of frames to skip when reporting tracebacks
178 tb_offset = 0
178 tb_offset = 0
179
179
180 def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None, config=None):
180 def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None, config=None):
181 # Whether to call the interactive pdb debugger after printing
181 # Whether to call the interactive pdb debugger after printing
182 # tracebacks or not
182 # tracebacks or not
183 super(TBTools, self).__init__(parent=parent, config=config)
183 super(TBTools, self).__init__(parent=parent, config=config)
184 self.call_pdb = call_pdb
184 self.call_pdb = call_pdb
185
185
186 # Output stream to write to. Note that we store the original value in
186 # Output stream to write to. Note that we store the original value in
187 # a private attribute and then make the public ostream a property, so
187 # a private attribute and then make the public ostream a property, so
188 # that we can delay accessing sys.stdout until runtime. The way
188 # that we can delay accessing sys.stdout until runtime. The way
189 # things are written now, the sys.stdout object is dynamically managed
189 # things are written now, the sys.stdout object is dynamically managed
190 # so a reference to it should NEVER be stored statically. This
190 # so a reference to it should NEVER be stored statically. This
191 # property approach confines this detail to a single location, and all
191 # property approach confines this detail to a single location, and all
192 # subclasses can simply access self.ostream for writing.
192 # subclasses can simply access self.ostream for writing.
193 self._ostream = ostream
193 self._ostream = ostream
194
194
195 # Create color table
195 # Create color table
196 self.color_scheme_table = exception_colors()
196 self.color_scheme_table = exception_colors()
197
197
198 self.set_colors(color_scheme)
198 self.set_colors(color_scheme)
199 self.old_scheme = color_scheme # save initial value for toggles
199 self.old_scheme = color_scheme # save initial value for toggles
200
200
201 if call_pdb:
201 if call_pdb:
202 self.pdb = debugger.Pdb()
202 self.pdb = debugger.Pdb()
203 else:
203 else:
204 self.pdb = None
204 self.pdb = None
205
205
206 def _get_ostream(self):
206 def _get_ostream(self):
207 """Output stream that exceptions are written to.
207 """Output stream that exceptions are written to.
208
208
209 Valid values are:
209 Valid values are:
210
210
211 - None: the default, which means that IPython will dynamically resolve
211 - None: the default, which means that IPython will dynamically resolve
212 to sys.stdout. This ensures compatibility with most tools, including
212 to sys.stdout. This ensures compatibility with most tools, including
213 Windows (where plain stdout doesn't recognize ANSI escapes).
213 Windows (where plain stdout doesn't recognize ANSI escapes).
214
214
215 - Any object with 'write' and 'flush' attributes.
215 - Any object with 'write' and 'flush' attributes.
216 """
216 """
217 return sys.stdout if self._ostream is None else self._ostream
217 return sys.stdout if self._ostream is None else self._ostream
218
218
219 def _set_ostream(self, val):
219 def _set_ostream(self, val):
220 assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush'))
220 assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush'))
221 self._ostream = val
221 self._ostream = val
222
222
223 ostream = property(_get_ostream, _set_ostream)
223 ostream = property(_get_ostream, _set_ostream)
224
224
225 def get_parts_of_chained_exception(self, evalue):
225 def get_parts_of_chained_exception(self, evalue):
226 def get_chained_exception(exception_value):
226 def get_chained_exception(exception_value):
227 cause = getattr(exception_value, '__cause__', None)
227 cause = getattr(exception_value, '__cause__', None)
228 if cause:
228 if cause:
229 return cause
229 return cause
230 if getattr(exception_value, '__suppress_context__', False):
230 if getattr(exception_value, '__suppress_context__', False):
231 return None
231 return None
232 return getattr(exception_value, '__context__', None)
232 return getattr(exception_value, '__context__', None)
233
233
234 chained_evalue = get_chained_exception(evalue)
234 chained_evalue = get_chained_exception(evalue)
235
235
236 if chained_evalue:
236 if chained_evalue:
237 return chained_evalue.__class__, chained_evalue, chained_evalue.__traceback__
237 return chained_evalue.__class__, chained_evalue, chained_evalue.__traceback__
238
238
239 def prepare_chained_exception_message(self, cause):
239 def prepare_chained_exception_message(self, cause):
240 direct_cause = "\nThe above exception was the direct cause of the following exception:\n"
240 direct_cause = "\nThe above exception was the direct cause of the following exception:\n"
241 exception_during_handling = "\nDuring handling of the above exception, another exception occurred:\n"
241 exception_during_handling = "\nDuring handling of the above exception, another exception occurred:\n"
242
242
243 if cause:
243 if cause:
244 message = [[direct_cause]]
244 message = [[direct_cause]]
245 else:
245 else:
246 message = [[exception_during_handling]]
246 message = [[exception_during_handling]]
247 return message
247 return message
248
248
249 @property
249 @property
250 def has_colors(self):
250 def has_colors(self):
251 return self.color_scheme_table.active_scheme_name.lower() != "nocolor"
251 return self.color_scheme_table.active_scheme_name.lower() != "nocolor"
252
252
253 def set_colors(self, *args, **kw):
253 def set_colors(self, *args, **kw):
254 """Shorthand access to the color table scheme selector method."""
254 """Shorthand access to the color table scheme selector method."""
255
255
256 # Set own color table
256 # Set own color table
257 self.color_scheme_table.set_active_scheme(*args, **kw)
257 self.color_scheme_table.set_active_scheme(*args, **kw)
258 # for convenience, set Colors to the active scheme
258 # for convenience, set Colors to the active scheme
259 self.Colors = self.color_scheme_table.active_colors
259 self.Colors = self.color_scheme_table.active_colors
260 # Also set colors of debugger
260 # Also set colors of debugger
261 if hasattr(self, 'pdb') and self.pdb is not None:
261 if hasattr(self, 'pdb') and self.pdb is not None:
262 self.pdb.set_colors(*args, **kw)
262 self.pdb.set_colors(*args, **kw)
263
263
264 def color_toggle(self):
264 def color_toggle(self):
265 """Toggle between the currently active color scheme and NoColor."""
265 """Toggle between the currently active color scheme and NoColor."""
266
266
267 if self.color_scheme_table.active_scheme_name == 'NoColor':
267 if self.color_scheme_table.active_scheme_name == 'NoColor':
268 self.color_scheme_table.set_active_scheme(self.old_scheme)
268 self.color_scheme_table.set_active_scheme(self.old_scheme)
269 self.Colors = self.color_scheme_table.active_colors
269 self.Colors = self.color_scheme_table.active_colors
270 else:
270 else:
271 self.old_scheme = self.color_scheme_table.active_scheme_name
271 self.old_scheme = self.color_scheme_table.active_scheme_name
272 self.color_scheme_table.set_active_scheme('NoColor')
272 self.color_scheme_table.set_active_scheme('NoColor')
273 self.Colors = self.color_scheme_table.active_colors
273 self.Colors = self.color_scheme_table.active_colors
274
274
275 def stb2text(self, stb):
275 def stb2text(self, stb):
276 """Convert a structured traceback (a list) to a string."""
276 """Convert a structured traceback (a list) to a string."""
277 return '\n'.join(stb)
277 return '\n'.join(stb)
278
278
279 def text(self, etype, value, tb, tb_offset=None, context=5):
279 def text(self, etype, value, tb, tb_offset=None, context=5):
280 """Return formatted traceback.
280 """Return formatted traceback.
281
281
282 Subclasses may override this if they add extra arguments.
282 Subclasses may override this if they add extra arguments.
283 """
283 """
284 tb_list = self.structured_traceback(etype, value, tb,
284 tb_list = self.structured_traceback(etype, value, tb,
285 tb_offset, context)
285 tb_offset, context)
286 return self.stb2text(tb_list)
286 return self.stb2text(tb_list)
287
287
288 def structured_traceback(self, etype, evalue, tb, tb_offset=None,
288 def structured_traceback(self, etype, evalue, tb, tb_offset=None,
289 context=5, mode=None):
289 context=5, mode=None):
290 """Return a list of traceback frames.
290 """Return a list of traceback frames.
291
291
292 Must be implemented by each class.
292 Must be implemented by each class.
293 """
293 """
294 raise NotImplementedError()
294 raise NotImplementedError()
295
295
296
296
297 #---------------------------------------------------------------------------
297 #---------------------------------------------------------------------------
298 class ListTB(TBTools):
298 class ListTB(TBTools):
299 """Print traceback information from a traceback list, with optional color.
299 """Print traceback information from a traceback list, with optional color.
300
300
301 Calling requires 3 arguments: (etype, evalue, elist)
301 Calling requires 3 arguments: (etype, evalue, elist)
302 as would be obtained by::
302 as would be obtained by::
303
303
304 etype, evalue, tb = sys.exc_info()
304 etype, evalue, tb = sys.exc_info()
305 if tb:
305 if tb:
306 elist = traceback.extract_tb(tb)
306 elist = traceback.extract_tb(tb)
307 else:
307 else:
308 elist = None
308 elist = None
309
309
310 It can thus be used by programs which need to process the traceback before
310 It can thus be used by programs which need to process the traceback before
311 printing (such as console replacements based on the code module from the
311 printing (such as console replacements based on the code module from the
312 standard library).
312 standard library).
313
313
314 Because they are meant to be called without a full traceback (only a
314 Because they are meant to be called without a full traceback (only a
315 list), instances of this class can't call the interactive pdb debugger."""
315 list), instances of this class can't call the interactive pdb debugger."""
316
316
317 def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None, config=None):
317 def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None, config=None):
318 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
318 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
319 ostream=ostream, parent=parent,config=config)
319 ostream=ostream, parent=parent,config=config)
320
320
321 def __call__(self, etype, value, elist):
321 def __call__(self, etype, value, elist):
322 self.ostream.flush()
322 self.ostream.flush()
323 self.ostream.write(self.text(etype, value, elist))
323 self.ostream.write(self.text(etype, value, elist))
324 self.ostream.write('\n')
324 self.ostream.write('\n')
325
325
326 def _extract_tb(self, tb):
326 def _extract_tb(self, tb):
327 if tb:
327 if tb:
328 return traceback.extract_tb(tb)
328 return traceback.extract_tb(tb)
329 else:
329 else:
330 return None
330 return None
331
331
332 def structured_traceback(self, etype, evalue, etb=None, tb_offset=None,
332 def structured_traceback(self, etype, evalue, etb=None, tb_offset=None,
333 context=5):
333 context=5):
334 """Return a color formatted string with the traceback info.
334 """Return a color formatted string with the traceback info.
335
335
336 Parameters
336 Parameters
337 ----------
337 ----------
338 etype : exception type
338 etype : exception type
339 Type of the exception raised.
339 Type of the exception raised.
340 evalue : object
340 evalue : object
341 Data stored in the exception
341 Data stored in the exception
342 etb : object
342 etb : object
343 If list: List of frames, see class docstring for details.
343 If list: List of frames, see class docstring for details.
344 If Traceback: Traceback of the exception.
344 If Traceback: Traceback of the exception.
345 tb_offset : int, optional
345 tb_offset : int, optional
346 Number of frames in the traceback to skip. If not given, the
346 Number of frames in the traceback to skip. If not given, the
347 instance evalue is used (set in constructor).
347 instance evalue is used (set in constructor).
348 context : int, optional
348 context : int, optional
349 Number of lines of context information to print.
349 Number of lines of context information to print.
350
350
351 Returns
351 Returns
352 -------
352 -------
353 String with formatted exception.
353 String with formatted exception.
354 """
354 """
355 # This is a workaround to get chained_exc_ids in recursive calls
355 # This is a workaround to get chained_exc_ids in recursive calls
356 # etb should not be a tuple if structured_traceback is not recursive
356 # etb should not be a tuple if structured_traceback is not recursive
357 if isinstance(etb, tuple):
357 if isinstance(etb, tuple):
358 etb, chained_exc_ids = etb
358 etb, chained_exc_ids = etb
359 else:
359 else:
360 chained_exc_ids = set()
360 chained_exc_ids = set()
361
361
362 if isinstance(etb, list):
362 if isinstance(etb, list):
363 elist = etb
363 elist = etb
364 elif etb is not None:
364 elif etb is not None:
365 elist = self._extract_tb(etb)
365 elist = self._extract_tb(etb)
366 else:
366 else:
367 elist = []
367 elist = []
368 tb_offset = self.tb_offset if tb_offset is None else tb_offset
368 tb_offset = self.tb_offset if tb_offset is None else tb_offset
369 Colors = self.Colors
369 Colors = self.Colors
370 out_list = []
370 out_list = []
371 if elist:
371 if elist:
372
372
373 if tb_offset and len(elist) > tb_offset:
373 if tb_offset and len(elist) > tb_offset:
374 elist = elist[tb_offset:]
374 elist = elist[tb_offset:]
375
375
376 out_list.append('Traceback %s(most recent call last)%s:' %
376 out_list.append('Traceback %s(most recent call last)%s:' %
377 (Colors.normalEm, Colors.Normal) + '\n')
377 (Colors.normalEm, Colors.Normal) + '\n')
378 out_list.extend(self._format_list(elist))
378 out_list.extend(self._format_list(elist))
379 # The exception info should be a single entry in the list.
379 # The exception info should be a single entry in the list.
380 lines = ''.join(self._format_exception_only(etype, evalue))
380 lines = ''.join(self._format_exception_only(etype, evalue))
381 out_list.append(lines)
381 out_list.append(lines)
382
382
383 exception = self.get_parts_of_chained_exception(evalue)
383 exception = self.get_parts_of_chained_exception(evalue)
384
384
385 if exception and not id(exception[1]) in chained_exc_ids:
385 if exception and not id(exception[1]) in chained_exc_ids:
386 chained_exception_message = self.prepare_chained_exception_message(
386 chained_exception_message = self.prepare_chained_exception_message(
387 evalue.__cause__)[0]
387 evalue.__cause__)[0]
388 etype, evalue, etb = exception
388 etype, evalue, etb = exception
389 # Trace exception to avoid infinite 'cause' loop
389 # Trace exception to avoid infinite 'cause' loop
390 chained_exc_ids.add(id(exception[1]))
390 chained_exc_ids.add(id(exception[1]))
391 chained_exceptions_tb_offset = 0
391 chained_exceptions_tb_offset = 0
392 out_list = (
392 out_list = (
393 self.structured_traceback(
393 self.structured_traceback(
394 etype, evalue, (etb, chained_exc_ids),
394 etype, evalue, (etb, chained_exc_ids),
395 chained_exceptions_tb_offset, context)
395 chained_exceptions_tb_offset, context)
396 + chained_exception_message
396 + chained_exception_message
397 + out_list)
397 + out_list)
398
398
399 return out_list
399 return out_list
400
400
401 def _format_list(self, extracted_list):
401 def _format_list(self, extracted_list):
402 """Format a list of traceback entry tuples for printing.
402 """Format a list of traceback entry tuples for printing.
403
403
404 Given a list of tuples as returned by extract_tb() or
404 Given a list of tuples as returned by extract_tb() or
405 extract_stack(), return a list of strings ready for printing.
405 extract_stack(), return a list of strings ready for printing.
406 Each string in the resulting list corresponds to the item with the
406 Each string in the resulting list corresponds to the item with the
407 same index in the argument list. Each string ends in a newline;
407 same index in the argument list. Each string ends in a newline;
408 the strings may contain internal newlines as well, for those items
408 the strings may contain internal newlines as well, for those items
409 whose source text line is not None.
409 whose source text line is not None.
410
410
411 Lifted almost verbatim from traceback.py
411 Lifted almost verbatim from traceback.py
412 """
412 """
413
413
414 Colors = self.Colors
414 Colors = self.Colors
415 list = []
415 list = []
416 for filename, lineno, name, line in extracted_list[:-1]:
416 for filename, lineno, name, line in extracted_list[:-1]:
417 item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
417 item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
418 (Colors.filename, filename, Colors.Normal,
418 (Colors.filename, filename, Colors.Normal,
419 Colors.lineno, lineno, Colors.Normal,
419 Colors.lineno, lineno, Colors.Normal,
420 Colors.name, name, Colors.Normal)
420 Colors.name, name, Colors.Normal)
421 if line:
421 if line:
422 item += ' %s\n' % line.strip()
422 item += ' %s\n' % line.strip()
423 list.append(item)
423 list.append(item)
424 # Emphasize the last entry
424 # Emphasize the last entry
425 filename, lineno, name, line = extracted_list[-1]
425 filename, lineno, name, line = extracted_list[-1]
426 item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
426 item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
427 (Colors.normalEm,
427 (Colors.normalEm,
428 Colors.filenameEm, filename, Colors.normalEm,
428 Colors.filenameEm, filename, Colors.normalEm,
429 Colors.linenoEm, lineno, Colors.normalEm,
429 Colors.linenoEm, lineno, Colors.normalEm,
430 Colors.nameEm, name, Colors.normalEm,
430 Colors.nameEm, name, Colors.normalEm,
431 Colors.Normal)
431 Colors.Normal)
432 if line:
432 if line:
433 item += '%s %s%s\n' % (Colors.line, line.strip(),
433 item += '%s %s%s\n' % (Colors.line, line.strip(),
434 Colors.Normal)
434 Colors.Normal)
435 list.append(item)
435 list.append(item)
436 return list
436 return list
437
437
438 def _format_exception_only(self, etype, value):
438 def _format_exception_only(self, etype, value):
439 """Format the exception part of a traceback.
439 """Format the exception part of a traceback.
440
440
441 The arguments are the exception type and value such as given by
441 The arguments are the exception type and value such as given by
442 sys.exc_info()[:2]. The return value is a list of strings, each ending
442 sys.exc_info()[:2]. The return value is a list of strings, each ending
443 in a newline. Normally, the list contains a single string; however,
443 in a newline. Normally, the list contains a single string; however,
444 for SyntaxError exceptions, it contains several lines that (when
444 for SyntaxError exceptions, it contains several lines that (when
445 printed) display detailed information about where the syntax error
445 printed) display detailed information about where the syntax error
446 occurred. The message indicating which exception occurred is the
446 occurred. The message indicating which exception occurred is the
447 always last string in the list.
447 always last string in the list.
448
448
449 Also lifted nearly verbatim from traceback.py
449 Also lifted nearly verbatim from traceback.py
450 """
450 """
451 have_filedata = False
451 have_filedata = False
452 Colors = self.Colors
452 Colors = self.Colors
453 list = []
453 list = []
454 stype = py3compat.cast_unicode(Colors.excName + etype.__name__ + Colors.Normal)
454 stype = py3compat.cast_unicode(Colors.excName + etype.__name__ + Colors.Normal)
455 if value is None:
455 if value is None:
456 # Not sure if this can still happen in Python 2.6 and above
456 # Not sure if this can still happen in Python 2.6 and above
457 list.append(stype + '\n')
457 list.append(stype + '\n')
458 else:
458 else:
459 if issubclass(etype, SyntaxError):
459 if issubclass(etype, SyntaxError):
460 have_filedata = True
460 have_filedata = True
461 if not value.filename: value.filename = "<string>"
461 if not value.filename: value.filename = "<string>"
462 if value.lineno:
462 if value.lineno:
463 lineno = value.lineno
463 lineno = value.lineno
464 textline = linecache.getline(value.filename, value.lineno)
464 textline = linecache.getline(value.filename, value.lineno)
465 else:
465 else:
466 lineno = 'unknown'
466 lineno = 'unknown'
467 textline = ''
467 textline = ''
468 list.append('%s File %s"%s"%s, line %s%s%s\n' % \
468 list.append('%s File %s"%s"%s, line %s%s%s\n' % \
469 (Colors.normalEm,
469 (Colors.normalEm,
470 Colors.filenameEm, py3compat.cast_unicode(value.filename), Colors.normalEm,
470 Colors.filenameEm, py3compat.cast_unicode(value.filename), Colors.normalEm,
471 Colors.linenoEm, lineno, Colors.Normal ))
471 Colors.linenoEm, lineno, Colors.Normal ))
472 if textline == '':
472 if textline == '':
473 textline = py3compat.cast_unicode(value.text, "utf-8")
473 textline = py3compat.cast_unicode(value.text, "utf-8")
474
474
475 if textline is not None:
475 if textline is not None:
476 i = 0
476 i = 0
477 while i < len(textline) and textline[i].isspace():
477 while i < len(textline) and textline[i].isspace():
478 i += 1
478 i += 1
479 list.append('%s %s%s\n' % (Colors.line,
479 list.append('%s %s%s\n' % (Colors.line,
480 textline.strip(),
480 textline.strip(),
481 Colors.Normal))
481 Colors.Normal))
482 if value.offset is not None:
482 if value.offset is not None:
483 s = ' '
483 s = ' '
484 for c in textline[i:value.offset - 1]:
484 for c in textline[i:value.offset - 1]:
485 if c.isspace():
485 if c.isspace():
486 s += c
486 s += c
487 else:
487 else:
488 s += ' '
488 s += ' '
489 list.append('%s%s^%s\n' % (Colors.caret, s,
489 list.append('%s%s^%s\n' % (Colors.caret, s,
490 Colors.Normal))
490 Colors.Normal))
491
491
492 try:
492 try:
493 s = value.msg
493 s = value.msg
494 except Exception:
494 except Exception:
495 s = self._some_str(value)
495 s = self._some_str(value)
496 if s:
496 if s:
497 list.append('%s%s:%s %s\n' % (stype, Colors.excName,
497 list.append('%s%s:%s %s\n' % (stype, Colors.excName,
498 Colors.Normal, s))
498 Colors.Normal, s))
499 else:
499 else:
500 list.append('%s\n' % stype)
500 list.append('%s\n' % stype)
501
501
502 # sync with user hooks
502 # sync with user hooks
503 if have_filedata:
503 if have_filedata:
504 ipinst = get_ipython()
504 ipinst = get_ipython()
505 if ipinst is not None:
505 if ipinst is not None:
506 ipinst.hooks.synchronize_with_editor(value.filename, value.lineno, 0)
506 ipinst.hooks.synchronize_with_editor(value.filename, value.lineno, 0)
507
507
508 return list
508 return list
509
509
510 def get_exception_only(self, etype, value):
510 def get_exception_only(self, etype, value):
511 """Only print the exception type and message, without a traceback.
511 """Only print the exception type and message, without a traceback.
512
512
513 Parameters
513 Parameters
514 ----------
514 ----------
515 etype : exception type
515 etype : exception type
516 evalue : exception value
516 evalue : exception value
517 """
517 """
518 return ListTB.structured_traceback(self, etype, value)
518 return ListTB.structured_traceback(self, etype, value)
519
519
520 def show_exception_only(self, etype, evalue):
520 def show_exception_only(self, etype, evalue):
521 """Only print the exception type and message, without a traceback.
521 """Only print the exception type and message, without a traceback.
522
522
523 Parameters
523 Parameters
524 ----------
524 ----------
525 etype : exception type
525 etype : exception type
526 evalue : exception value
526 evalue : exception value
527 """
527 """
528 # This method needs to use __call__ from *this* class, not the one from
528 # This method needs to use __call__ from *this* class, not the one from
529 # a subclass whose signature or behavior may be different
529 # a subclass whose signature or behavior may be different
530 ostream = self.ostream
530 ostream = self.ostream
531 ostream.flush()
531 ostream.flush()
532 ostream.write('\n'.join(self.get_exception_only(etype, evalue)))
532 ostream.write('\n'.join(self.get_exception_only(etype, evalue)))
533 ostream.flush()
533 ostream.flush()
534
534
535 def _some_str(self, value):
535 def _some_str(self, value):
536 # Lifted from traceback.py
536 # Lifted from traceback.py
537 try:
537 try:
538 return py3compat.cast_unicode(str(value))
538 return py3compat.cast_unicode(str(value))
539 except:
539 except:
540 return u'<unprintable %s object>' % type(value).__name__
540 return u'<unprintable %s object>' % type(value).__name__
541
541
542
542
543 #----------------------------------------------------------------------------
543 #----------------------------------------------------------------------------
544 class VerboseTB(TBTools):
544 class VerboseTB(TBTools):
545 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
545 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
546 of HTML. Requires inspect and pydoc. Crazy, man.
546 of HTML. Requires inspect and pydoc. Crazy, man.
547
547
548 Modified version which optionally strips the topmost entries from the
548 Modified version which optionally strips the topmost entries from the
549 traceback, to be used with alternate interpreters (because their own code
549 traceback, to be used with alternate interpreters (because their own code
550 would appear in the traceback)."""
550 would appear in the traceback)."""
551
551
552 def __init__(self, color_scheme='Linux', call_pdb=False, ostream=None,
552 def __init__(self, color_scheme='Linux', call_pdb=False, ostream=None,
553 tb_offset=0, long_header=False, include_vars=True,
553 tb_offset=0, long_header=False, include_vars=True,
554 check_cache=None, debugger_cls = None,
554 check_cache=None, debugger_cls = None,
555 parent=None, config=None):
555 parent=None, config=None):
556 """Specify traceback offset, headers and color scheme.
556 """Specify traceback offset, headers and color scheme.
557
557
558 Define how many frames to drop from the tracebacks. Calling it with
558 Define how many frames to drop from the tracebacks. Calling it with
559 tb_offset=1 allows use of this handler in interpreters which will have
559 tb_offset=1 allows use of this handler in interpreters which will have
560 their own code at the top of the traceback (VerboseTB will first
560 their own code at the top of the traceback (VerboseTB will first
561 remove that frame before printing the traceback info)."""
561 remove that frame before printing the traceback info)."""
562 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
562 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
563 ostream=ostream, parent=parent, config=config)
563 ostream=ostream, parent=parent, config=config)
564 self.tb_offset = tb_offset
564 self.tb_offset = tb_offset
565 self.long_header = long_header
565 self.long_header = long_header
566 self.include_vars = include_vars
566 self.include_vars = include_vars
567 # By default we use linecache.checkcache, but the user can provide a
567 # By default we use linecache.checkcache, but the user can provide a
568 # different check_cache implementation. This is used by the IPython
568 # different check_cache implementation. This is used by the IPython
569 # kernel to provide tracebacks for interactive code that is cached,
569 # kernel to provide tracebacks for interactive code that is cached,
570 # by a compiler instance that flushes the linecache but preserves its
570 # by a compiler instance that flushes the linecache but preserves its
571 # own code cache.
571 # own code cache.
572 if check_cache is None:
572 if check_cache is None:
573 check_cache = linecache.checkcache
573 check_cache = linecache.checkcache
574 self.check_cache = check_cache
574 self.check_cache = check_cache
575
575
576 self.debugger_cls = debugger_cls or debugger.Pdb
576 self.debugger_cls = debugger_cls or debugger.Pdb
577 self.skip_hidden = True
577 self.skip_hidden = True
578
578
579 def format_record(self, frame_info):
579 def format_record(self, frame_info):
580 """Format a single stack frame"""
580 """Format a single stack frame"""
581 Colors = self.Colors # just a shorthand + quicker name lookup
581 Colors = self.Colors # just a shorthand + quicker name lookup
582 ColorsNormal = Colors.Normal # used a lot
582 ColorsNormal = Colors.Normal # used a lot
583
583
584
584
585
585
586 if isinstance(frame_info, stack_data.RepeatedFrames):
586 if isinstance(frame_info, stack_data.RepeatedFrames):
587 return ' %s[... skipping similar frames: %s]%s\n' % (
587 return ' %s[... skipping similar frames: %s]%s\n' % (
588 Colors.excName, frame_info.description, ColorsNormal)
588 Colors.excName, frame_info.description, ColorsNormal)
589
589
590 indent = ' ' * INDENT_SIZE
590 indent = ' ' * INDENT_SIZE
591 em_normal = '%s\n%s%s' % (Colors.valEm, indent, ColorsNormal)
591 em_normal = '%s\n%s%s' % (Colors.valEm, indent, ColorsNormal)
592 tpl_link = '%s%%s%s' % (Colors.filenameEm, ColorsNormal)
592 tpl_link = '%s%%s%s' % (Colors.filenameEm, ColorsNormal)
593 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
593 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
594 ColorsNormal)
594 ColorsNormal)
595 tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
595 tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
596 (Colors.vName, Colors.valEm, ColorsNormal)
596 (Colors.vName, Colors.valEm, ColorsNormal)
597 tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
597 tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
598 tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
598 tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
599
599
600 file = frame_info.filename
600 file = frame_info.filename
601 file = py3compat.cast_unicode(file, util_path.fs_encoding)
601 file = py3compat.cast_unicode(file, util_path.fs_encoding)
602 link = tpl_link % util_path.compress_user(file)
602 link = tpl_link % util_path.compress_user(file)
603 args, varargs, varkw, locals_ = inspect.getargvalues(frame_info.frame)
603 args, varargs, varkw, locals_ = inspect.getargvalues(frame_info.frame)
604
604
605 func = frame_info.executing.code_qualname()
605 func = frame_info.executing.code_qualname()
606 if func == '<module>':
606 if func == '<module>':
607 call = tpl_call % (func, '')
607 call = tpl_call % (func, '')
608 else:
608 else:
609 # Decide whether to include variable details or not
609 # Decide whether to include variable details or not
610 var_repr = eqrepr if self.include_vars else nullrepr
610 var_repr = eqrepr if self.include_vars else nullrepr
611 try:
611 try:
612 call = tpl_call % (func, inspect.formatargvalues(args,
612 call = tpl_call % (func, inspect.formatargvalues(args,
613 varargs, varkw,
613 varargs, varkw,
614 locals_, formatvalue=var_repr))
614 locals_, formatvalue=var_repr))
615 except KeyError:
615 except KeyError:
616 # This happens in situations like errors inside generator
616 # This happens in situations like errors inside generator
617 # expressions, where local variables are listed in the
617 # expressions, where local variables are listed in the
618 # line, but can't be extracted from the frame. I'm not
618 # line, but can't be extracted from the frame. I'm not
619 # 100% sure this isn't actually a bug in inspect itself,
619 # 100% sure this isn't actually a bug in inspect itself,
620 # but since there's no info for us to compute with, the
620 # but since there's no info for us to compute with, the
621 # best we can do is report the failure and move on. Here
621 # best we can do is report the failure and move on. Here
622 # we must *not* call any traceback construction again,
622 # we must *not* call any traceback construction again,
623 # because that would mess up use of %debug later on. So we
623 # because that would mess up use of %debug later on. So we
624 # simply report the failure and move on. The only
624 # simply report the failure and move on. The only
625 # limitation will be that this frame won't have locals
625 # limitation will be that this frame won't have locals
626 # listed in the call signature. Quite subtle problem...
626 # listed in the call signature. Quite subtle problem...
627 # I can't think of a good way to validate this in a unit
627 # I can't think of a good way to validate this in a unit
628 # test, but running a script consisting of:
628 # test, but running a script consisting of:
629 # dict( (k,v.strip()) for (k,v) in range(10) )
629 # dict( (k,v.strip()) for (k,v) in range(10) )
630 # will illustrate the error, if this exception catch is
630 # will illustrate the error, if this exception catch is
631 # disabled.
631 # disabled.
632 call = tpl_call_fail % func
632 call = tpl_call_fail % func
633
633
634 lvals = ''
634 lvals = ''
635 lvals_list = []
635 lvals_list = []
636 if self.include_vars:
636 if self.include_vars:
637 for var in frame_info.variables_in_executing_piece:
637 for var in frame_info.variables_in_executing_piece:
638 lvals_list.append(tpl_name_val % (var.name, repr(var.value)))
638 lvals_list.append(tpl_name_val % (var.name, repr(var.value)))
639 if lvals_list:
639 if lvals_list:
640 lvals = '%s%s' % (indent, em_normal.join(lvals_list))
640 lvals = '%s%s' % (indent, em_normal.join(lvals_list))
641
641
642 result = '%s %s\n' % (link, call)
642 result = '%s %s\n' % (link, call)
643
643
644 result += ''.join(_format_traceback_lines(frame_info.lines, Colors, self.has_colors, lvals))
644 result += ''.join(_format_traceback_lines(frame_info.lines, Colors, self.has_colors, lvals))
645 return result
645 return result
646
646
647 def prepare_header(self, etype, long_version=False):
647 def prepare_header(self, etype, long_version=False):
648 colors = self.Colors # just a shorthand + quicker name lookup
648 colors = self.Colors # just a shorthand + quicker name lookup
649 colorsnormal = colors.Normal # used a lot
649 colorsnormal = colors.Normal # used a lot
650 exc = '%s%s%s' % (colors.excName, etype, colorsnormal)
650 exc = '%s%s%s' % (colors.excName, etype, colorsnormal)
651 width = min(75, get_terminal_size()[0])
651 width = min(75, get_terminal_size()[0])
652 if long_version:
652 if long_version:
653 # Header with the exception type, python version, and date
653 # Header with the exception type, python version, and date
654 pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
654 pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
655 date = time.ctime(time.time())
655 date = time.ctime(time.time())
656
656
657 head = '%s%s%s\n%s%s%s\n%s' % (colors.topline, '-' * width, colorsnormal,
657 head = '%s%s%s\n%s%s%s\n%s' % (colors.topline, '-' * width, colorsnormal,
658 exc, ' ' * (width - len(str(etype)) - len(pyver)),
658 exc, ' ' * (width - len(str(etype)) - len(pyver)),
659 pyver, date.rjust(width) )
659 pyver, date.rjust(width) )
660 head += "\nA problem occurred executing Python code. Here is the sequence of function" \
660 head += "\nA problem occurred executing Python code. Here is the sequence of function" \
661 "\ncalls leading up to the error, with the most recent (innermost) call last."
661 "\ncalls leading up to the error, with the most recent (innermost) call last."
662 else:
662 else:
663 # Simplified header
663 # Simplified header
664 head = '%s%s' % (exc, 'Traceback (most recent call last)'. \
664 head = '%s%s' % (exc, 'Traceback (most recent call last)'. \
665 rjust(width - len(str(etype))) )
665 rjust(width - len(str(etype))) )
666
666
667 return head
667 return head
668
668
669 def format_exception(self, etype, evalue):
669 def format_exception(self, etype, evalue):
670 colors = self.Colors # just a shorthand + quicker name lookup
670 colors = self.Colors # just a shorthand + quicker name lookup
671 colorsnormal = colors.Normal # used a lot
671 colorsnormal = colors.Normal # used a lot
672 # Get (safely) a string form of the exception info
672 # Get (safely) a string form of the exception info
673 try:
673 try:
674 etype_str, evalue_str = map(str, (etype, evalue))
674 etype_str, evalue_str = map(str, (etype, evalue))
675 except:
675 except:
676 # User exception is improperly defined.
676 # User exception is improperly defined.
677 etype, evalue = str, sys.exc_info()[:2]
677 etype, evalue = str, sys.exc_info()[:2]
678 etype_str, evalue_str = map(str, (etype, evalue))
678 etype_str, evalue_str = map(str, (etype, evalue))
679 # ... and format it
679 # ... and format it
680 return ['%s%s%s: %s' % (colors.excName, etype_str,
680 return ['%s%s%s: %s' % (colors.excName, etype_str,
681 colorsnormal, py3compat.cast_unicode(evalue_str))]
681 colorsnormal, py3compat.cast_unicode(evalue_str))]
682
682
683 def format_exception_as_a_whole(self, etype, evalue, etb, number_of_lines_of_context, tb_offset):
683 def format_exception_as_a_whole(self, etype, evalue, etb, number_of_lines_of_context, tb_offset):
684 """Formats the header, traceback and exception message for a single exception.
684 """Formats the header, traceback and exception message for a single exception.
685
685
686 This may be called multiple times by Python 3 exception chaining
686 This may be called multiple times by Python 3 exception chaining
687 (PEP 3134).
687 (PEP 3134).
688 """
688 """
689 # some locals
689 # some locals
690 orig_etype = etype
690 orig_etype = etype
691 try:
691 try:
692 etype = etype.__name__
692 etype = etype.__name__
693 except AttributeError:
693 except AttributeError:
694 pass
694 pass
695
695
696 tb_offset = self.tb_offset if tb_offset is None else tb_offset
696 tb_offset = self.tb_offset if tb_offset is None else tb_offset
697 head = self.prepare_header(etype, self.long_header)
697 head = self.prepare_header(etype, self.long_header)
698 records = self.get_records(etb, number_of_lines_of_context, tb_offset)
698 records = self.get_records(etb, number_of_lines_of_context, tb_offset)
699
699
700 frames = []
700 frames = []
701 skipped = 0
701 skipped = 0
702 for r in records:
702 lastrecord = len(records) - 1
703 for i, r in enumerate(records):
703 if not isinstance(r, stack_data.RepeatedFrames) and self.skip_hidden:
704 if not isinstance(r, stack_data.RepeatedFrames) and self.skip_hidden:
704 if r.frame.f_locals.get("__tracebackhide__", 0):
705 if r.frame.f_locals.get("__tracebackhide__", 0) and i != lastrecord:
705 skipped += 1
706 skipped += 1
706 continue
707 continue
707 if skipped:
708 if skipped:
708 Colors = self.Colors # just a shorthand + quicker name lookup
709 Colors = self.Colors # just a shorthand + quicker name lookup
709 ColorsNormal = Colors.Normal # used a lot
710 ColorsNormal = Colors.Normal # used a lot
710 frames.append(
711 frames.append(
711 " %s[... skipping hidden %s frame]%s\n"
712 " %s[... skipping hidden %s frame]%s\n"
712 % (Colors.excName, skipped, ColorsNormal)
713 % (Colors.excName, skipped, ColorsNormal)
713 )
714 )
714 skipped = 0
715 skipped = 0
715 frames.append(self.format_record(r))
716 frames.append(self.format_record(r))
716 if skipped:
717 if skipped:
717 Colors = self.Colors # just a shorthand + quicker name lookup
718 Colors = self.Colors # just a shorthand + quicker name lookup
718 ColorsNormal = Colors.Normal # used a lot
719 ColorsNormal = Colors.Normal # used a lot
719 frames.append(
720 frames.append(
720 " %s[... skipping hidden %s frame]%s\n"
721 " %s[... skipping hidden %s frame]%s\n"
721 % (Colors.excName, skipped, ColorsNormal)
722 % (Colors.excName, skipped, ColorsNormal)
722 )
723 )
723
724
724 formatted_exception = self.format_exception(etype, evalue)
725 formatted_exception = self.format_exception(etype, evalue)
725 if records:
726 if records:
726 frame_info = records[-1]
727 frame_info = records[-1]
727 ipinst = get_ipython()
728 ipinst = get_ipython()
728 if ipinst is not None:
729 if ipinst is not None:
729 ipinst.hooks.synchronize_with_editor(frame_info.filename, frame_info.lineno, 0)
730 ipinst.hooks.synchronize_with_editor(frame_info.filename, frame_info.lineno, 0)
730
731
731 return [[head] + frames + [''.join(formatted_exception[0])]]
732 return [[head] + frames + [''.join(formatted_exception[0])]]
732
733
733 def get_records(self, etb, number_of_lines_of_context, tb_offset):
734 def get_records(self, etb, number_of_lines_of_context, tb_offset):
734 context = number_of_lines_of_context - 1
735 context = number_of_lines_of_context - 1
735 after = context // 2
736 after = context // 2
736 before = context - after
737 before = context - after
737 if self.has_colors:
738 if self.has_colors:
738 style = get_style_by_name('default')
739 style = get_style_by_name('default')
739 style = stack_data.style_with_executing_node(style, 'bg:#00005f')
740 style = stack_data.style_with_executing_node(style, 'bg:#00005f')
740 formatter = Terminal256Formatter(style=style)
741 formatter = Terminal256Formatter(style=style)
741 else:
742 else:
742 formatter = None
743 formatter = None
743 options = stack_data.Options(
744 options = stack_data.Options(
744 before=before,
745 before=before,
745 after=after,
746 after=after,
746 pygments_formatter=formatter,
747 pygments_formatter=formatter,
747 )
748 )
748 return list(stack_data.FrameInfo.stack_data(etb, options=options))[tb_offset:]
749 return list(stack_data.FrameInfo.stack_data(etb, options=options))[tb_offset:]
749
750
750 def structured_traceback(self, etype, evalue, etb, tb_offset=None,
751 def structured_traceback(self, etype, evalue, etb, tb_offset=None,
751 number_of_lines_of_context=5):
752 number_of_lines_of_context=5):
752 """Return a nice text document describing the traceback."""
753 """Return a nice text document describing the traceback."""
753
754
754 formatted_exception = self.format_exception_as_a_whole(etype, evalue, etb, number_of_lines_of_context,
755 formatted_exception = self.format_exception_as_a_whole(etype, evalue, etb, number_of_lines_of_context,
755 tb_offset)
756 tb_offset)
756
757
757 colors = self.Colors # just a shorthand + quicker name lookup
758 colors = self.Colors # just a shorthand + quicker name lookup
758 colorsnormal = colors.Normal # used a lot
759 colorsnormal = colors.Normal # used a lot
759 head = '%s%s%s' % (colors.topline, '-' * min(75, get_terminal_size()[0]), colorsnormal)
760 head = '%s%s%s' % (colors.topline, '-' * min(75, get_terminal_size()[0]), colorsnormal)
760 structured_traceback_parts = [head]
761 structured_traceback_parts = [head]
761 chained_exceptions_tb_offset = 0
762 chained_exceptions_tb_offset = 0
762 lines_of_context = 3
763 lines_of_context = 3
763 formatted_exceptions = formatted_exception
764 formatted_exceptions = formatted_exception
764 exception = self.get_parts_of_chained_exception(evalue)
765 exception = self.get_parts_of_chained_exception(evalue)
765 if exception:
766 if exception:
766 formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__)
767 formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__)
767 etype, evalue, etb = exception
768 etype, evalue, etb = exception
768 else:
769 else:
769 evalue = None
770 evalue = None
770 chained_exc_ids = set()
771 chained_exc_ids = set()
771 while evalue:
772 while evalue:
772 formatted_exceptions += self.format_exception_as_a_whole(etype, evalue, etb, lines_of_context,
773 formatted_exceptions += self.format_exception_as_a_whole(etype, evalue, etb, lines_of_context,
773 chained_exceptions_tb_offset)
774 chained_exceptions_tb_offset)
774 exception = self.get_parts_of_chained_exception(evalue)
775 exception = self.get_parts_of_chained_exception(evalue)
775
776
776 if exception and not id(exception[1]) in chained_exc_ids:
777 if exception and not id(exception[1]) in chained_exc_ids:
777 chained_exc_ids.add(id(exception[1])) # trace exception to avoid infinite 'cause' loop
778 chained_exc_ids.add(id(exception[1])) # trace exception to avoid infinite 'cause' loop
778 formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__)
779 formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__)
779 etype, evalue, etb = exception
780 etype, evalue, etb = exception
780 else:
781 else:
781 evalue = None
782 evalue = None
782
783
783 # we want to see exceptions in a reversed order:
784 # we want to see exceptions in a reversed order:
784 # the first exception should be on top
785 # the first exception should be on top
785 for formatted_exception in reversed(formatted_exceptions):
786 for formatted_exception in reversed(formatted_exceptions):
786 structured_traceback_parts += formatted_exception
787 structured_traceback_parts += formatted_exception
787
788
788 return structured_traceback_parts
789 return structured_traceback_parts
789
790
790 def debugger(self, force=False):
791 def debugger(self, force=False):
791 """Call up the pdb debugger if desired, always clean up the tb
792 """Call up the pdb debugger if desired, always clean up the tb
792 reference.
793 reference.
793
794
794 Keywords:
795 Keywords:
795
796
796 - force(False): by default, this routine checks the instance call_pdb
797 - force(False): by default, this routine checks the instance call_pdb
797 flag and does not actually invoke the debugger if the flag is false.
798 flag and does not actually invoke the debugger if the flag is false.
798 The 'force' option forces the debugger to activate even if the flag
799 The 'force' option forces the debugger to activate even if the flag
799 is false.
800 is false.
800
801
801 If the call_pdb flag is set, the pdb interactive debugger is
802 If the call_pdb flag is set, the pdb interactive debugger is
802 invoked. In all cases, the self.tb reference to the current traceback
803 invoked. In all cases, the self.tb reference to the current traceback
803 is deleted to prevent lingering references which hamper memory
804 is deleted to prevent lingering references which hamper memory
804 management.
805 management.
805
806
806 Note that each call to pdb() does an 'import readline', so if your app
807 Note that each call to pdb() does an 'import readline', so if your app
807 requires a special setup for the readline completers, you'll have to
808 requires a special setup for the readline completers, you'll have to
808 fix that by hand after invoking the exception handler."""
809 fix that by hand after invoking the exception handler."""
809
810
810 if force or self.call_pdb:
811 if force or self.call_pdb:
811 if self.pdb is None:
812 if self.pdb is None:
812 self.pdb = self.debugger_cls()
813 self.pdb = self.debugger_cls()
813 # the system displayhook may have changed, restore the original
814 # the system displayhook may have changed, restore the original
814 # for pdb
815 # for pdb
815 display_trap = DisplayTrap(hook=sys.__displayhook__)
816 display_trap = DisplayTrap(hook=sys.__displayhook__)
816 with display_trap:
817 with display_trap:
817 self.pdb.reset()
818 self.pdb.reset()
818 # Find the right frame so we don't pop up inside ipython itself
819 # Find the right frame so we don't pop up inside ipython itself
819 if hasattr(self, 'tb') and self.tb is not None:
820 if hasattr(self, 'tb') and self.tb is not None:
820 etb = self.tb
821 etb = self.tb
821 else:
822 else:
822 etb = self.tb = sys.last_traceback
823 etb = self.tb = sys.last_traceback
823 while self.tb is not None and self.tb.tb_next is not None:
824 while self.tb is not None and self.tb.tb_next is not None:
824 self.tb = self.tb.tb_next
825 self.tb = self.tb.tb_next
825 if etb and etb.tb_next:
826 if etb and etb.tb_next:
826 etb = etb.tb_next
827 etb = etb.tb_next
827 self.pdb.botframe = etb.tb_frame
828 self.pdb.botframe = etb.tb_frame
828 self.pdb.interaction(None, etb)
829 self.pdb.interaction(None, etb)
829
830
830 if hasattr(self, 'tb'):
831 if hasattr(self, 'tb'):
831 del self.tb
832 del self.tb
832
833
833 def handler(self, info=None):
834 def handler(self, info=None):
834 (etype, evalue, etb) = info or sys.exc_info()
835 (etype, evalue, etb) = info or sys.exc_info()
835 self.tb = etb
836 self.tb = etb
836 ostream = self.ostream
837 ostream = self.ostream
837 ostream.flush()
838 ostream.flush()
838 ostream.write(self.text(etype, evalue, etb))
839 ostream.write(self.text(etype, evalue, etb))
839 ostream.write('\n')
840 ostream.write('\n')
840 ostream.flush()
841 ostream.flush()
841
842
842 # Changed so an instance can just be called as VerboseTB_inst() and print
843 # Changed so an instance can just be called as VerboseTB_inst() and print
843 # out the right info on its own.
844 # out the right info on its own.
844 def __call__(self, etype=None, evalue=None, etb=None):
845 def __call__(self, etype=None, evalue=None, etb=None):
845 """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
846 """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
846 if etb is None:
847 if etb is None:
847 self.handler()
848 self.handler()
848 else:
849 else:
849 self.handler((etype, evalue, etb))
850 self.handler((etype, evalue, etb))
850 try:
851 try:
851 self.debugger()
852 self.debugger()
852 except KeyboardInterrupt:
853 except KeyboardInterrupt:
853 print("\nKeyboardInterrupt")
854 print("\nKeyboardInterrupt")
854
855
855
856
856 #----------------------------------------------------------------------------
857 #----------------------------------------------------------------------------
857 class FormattedTB(VerboseTB, ListTB):
858 class FormattedTB(VerboseTB, ListTB):
858 """Subclass ListTB but allow calling with a traceback.
859 """Subclass ListTB but allow calling with a traceback.
859
860
860 It can thus be used as a sys.excepthook for Python > 2.1.
861 It can thus be used as a sys.excepthook for Python > 2.1.
861
862
862 Also adds 'Context' and 'Verbose' modes, not available in ListTB.
863 Also adds 'Context' and 'Verbose' modes, not available in ListTB.
863
864
864 Allows a tb_offset to be specified. This is useful for situations where
865 Allows a tb_offset to be specified. This is useful for situations where
865 one needs to remove a number of topmost frames from the traceback (such as
866 one needs to remove a number of topmost frames from the traceback (such as
866 occurs with python programs that themselves execute other python code,
867 occurs with python programs that themselves execute other python code,
867 like Python shells). """
868 like Python shells). """
868
869
869 def __init__(self, mode='Plain', color_scheme='Linux', call_pdb=False,
870 def __init__(self, mode='Plain', color_scheme='Linux', call_pdb=False,
870 ostream=None,
871 ostream=None,
871 tb_offset=0, long_header=False, include_vars=False,
872 tb_offset=0, long_header=False, include_vars=False,
872 check_cache=None, debugger_cls=None,
873 check_cache=None, debugger_cls=None,
873 parent=None, config=None):
874 parent=None, config=None):
874
875
875 # NEVER change the order of this list. Put new modes at the end:
876 # NEVER change the order of this list. Put new modes at the end:
876 self.valid_modes = ['Plain', 'Context', 'Verbose', 'Minimal']
877 self.valid_modes = ['Plain', 'Context', 'Verbose', 'Minimal']
877 self.verbose_modes = self.valid_modes[1:3]
878 self.verbose_modes = self.valid_modes[1:3]
878
879
879 VerboseTB.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
880 VerboseTB.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
880 ostream=ostream, tb_offset=tb_offset,
881 ostream=ostream, tb_offset=tb_offset,
881 long_header=long_header, include_vars=include_vars,
882 long_header=long_header, include_vars=include_vars,
882 check_cache=check_cache, debugger_cls=debugger_cls,
883 check_cache=check_cache, debugger_cls=debugger_cls,
883 parent=parent, config=config)
884 parent=parent, config=config)
884
885
885 # Different types of tracebacks are joined with different separators to
886 # Different types of tracebacks are joined with different separators to
886 # form a single string. They are taken from this dict
887 # form a single string. They are taken from this dict
887 self._join_chars = dict(Plain='', Context='\n', Verbose='\n',
888 self._join_chars = dict(Plain='', Context='\n', Verbose='\n',
888 Minimal='')
889 Minimal='')
889 # set_mode also sets the tb_join_char attribute
890 # set_mode also sets the tb_join_char attribute
890 self.set_mode(mode)
891 self.set_mode(mode)
891
892
892 def structured_traceback(self, etype, value, tb, tb_offset=None, number_of_lines_of_context=5):
893 def structured_traceback(self, etype, value, tb, tb_offset=None, number_of_lines_of_context=5):
893 tb_offset = self.tb_offset if tb_offset is None else tb_offset
894 tb_offset = self.tb_offset if tb_offset is None else tb_offset
894 mode = self.mode
895 mode = self.mode
895 if mode in self.verbose_modes:
896 if mode in self.verbose_modes:
896 # Verbose modes need a full traceback
897 # Verbose modes need a full traceback
897 return VerboseTB.structured_traceback(
898 return VerboseTB.structured_traceback(
898 self, etype, value, tb, tb_offset, number_of_lines_of_context
899 self, etype, value, tb, tb_offset, number_of_lines_of_context
899 )
900 )
900 elif mode == 'Minimal':
901 elif mode == 'Minimal':
901 return ListTB.get_exception_only(self, etype, value)
902 return ListTB.get_exception_only(self, etype, value)
902 else:
903 else:
903 # We must check the source cache because otherwise we can print
904 # We must check the source cache because otherwise we can print
904 # out-of-date source code.
905 # out-of-date source code.
905 self.check_cache()
906 self.check_cache()
906 # Now we can extract and format the exception
907 # Now we can extract and format the exception
907 return ListTB.structured_traceback(
908 return ListTB.structured_traceback(
908 self, etype, value, tb, tb_offset, number_of_lines_of_context
909 self, etype, value, tb, tb_offset, number_of_lines_of_context
909 )
910 )
910
911
911 def stb2text(self, stb):
912 def stb2text(self, stb):
912 """Convert a structured traceback (a list) to a string."""
913 """Convert a structured traceback (a list) to a string."""
913 return self.tb_join_char.join(stb)
914 return self.tb_join_char.join(stb)
914
915
915
916
916 def set_mode(self, mode=None):
917 def set_mode(self, mode=None):
917 """Switch to the desired mode.
918 """Switch to the desired mode.
918
919
919 If mode is not specified, cycles through the available modes."""
920 If mode is not specified, cycles through the available modes."""
920
921
921 if not mode:
922 if not mode:
922 new_idx = (self.valid_modes.index(self.mode) + 1 ) % \
923 new_idx = (self.valid_modes.index(self.mode) + 1 ) % \
923 len(self.valid_modes)
924 len(self.valid_modes)
924 self.mode = self.valid_modes[new_idx]
925 self.mode = self.valid_modes[new_idx]
925 elif mode not in self.valid_modes:
926 elif mode not in self.valid_modes:
926 raise ValueError('Unrecognized mode in FormattedTB: <' + mode + '>\n'
927 raise ValueError('Unrecognized mode in FormattedTB: <' + mode + '>\n'
927 'Valid modes: ' + str(self.valid_modes))
928 'Valid modes: ' + str(self.valid_modes))
928 else:
929 else:
929 self.mode = mode
930 self.mode = mode
930 # include variable details only in 'Verbose' mode
931 # include variable details only in 'Verbose' mode
931 self.include_vars = (self.mode == self.valid_modes[2])
932 self.include_vars = (self.mode == self.valid_modes[2])
932 # Set the join character for generating text tracebacks
933 # Set the join character for generating text tracebacks
933 self.tb_join_char = self._join_chars[self.mode]
934 self.tb_join_char = self._join_chars[self.mode]
934
935
935 # some convenient shortcuts
936 # some convenient shortcuts
936 def plain(self):
937 def plain(self):
937 self.set_mode(self.valid_modes[0])
938 self.set_mode(self.valid_modes[0])
938
939
939 def context(self):
940 def context(self):
940 self.set_mode(self.valid_modes[1])
941 self.set_mode(self.valid_modes[1])
941
942
942 def verbose(self):
943 def verbose(self):
943 self.set_mode(self.valid_modes[2])
944 self.set_mode(self.valid_modes[2])
944
945
945 def minimal(self):
946 def minimal(self):
946 self.set_mode(self.valid_modes[3])
947 self.set_mode(self.valid_modes[3])
947
948
948
949
949 #----------------------------------------------------------------------------
950 #----------------------------------------------------------------------------
950 class AutoFormattedTB(FormattedTB):
951 class AutoFormattedTB(FormattedTB):
951 """A traceback printer which can be called on the fly.
952 """A traceback printer which can be called on the fly.
952
953
953 It will find out about exceptions by itself.
954 It will find out about exceptions by itself.
954
955
955 A brief example::
956 A brief example::
956
957
957 AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
958 AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
958 try:
959 try:
959 ...
960 ...
960 except:
961 except:
961 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
962 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
962 """
963 """
963
964
964 def __call__(self, etype=None, evalue=None, etb=None,
965 def __call__(self, etype=None, evalue=None, etb=None,
965 out=None, tb_offset=None):
966 out=None, tb_offset=None):
966 """Print out a formatted exception traceback.
967 """Print out a formatted exception traceback.
967
968
968 Optional arguments:
969 Optional arguments:
969 - out: an open file-like object to direct output to.
970 - out: an open file-like object to direct output to.
970
971
971 - tb_offset: the number of frames to skip over in the stack, on a
972 - tb_offset: the number of frames to skip over in the stack, on a
972 per-call basis (this overrides temporarily the instance's tb_offset
973 per-call basis (this overrides temporarily the instance's tb_offset
973 given at initialization time."""
974 given at initialization time."""
974
975
975 if out is None:
976 if out is None:
976 out = self.ostream
977 out = self.ostream
977 out.flush()
978 out.flush()
978 out.write(self.text(etype, evalue, etb, tb_offset))
979 out.write(self.text(etype, evalue, etb, tb_offset))
979 out.write('\n')
980 out.write('\n')
980 out.flush()
981 out.flush()
981 # FIXME: we should remove the auto pdb behavior from here and leave
982 # FIXME: we should remove the auto pdb behavior from here and leave
982 # that to the clients.
983 # that to the clients.
983 try:
984 try:
984 self.debugger()
985 self.debugger()
985 except KeyboardInterrupt:
986 except KeyboardInterrupt:
986 print("\nKeyboardInterrupt")
987 print("\nKeyboardInterrupt")
987
988
988 def structured_traceback(self, etype=None, value=None, tb=None,
989 def structured_traceback(self, etype=None, value=None, tb=None,
989 tb_offset=None, number_of_lines_of_context=5):
990 tb_offset=None, number_of_lines_of_context=5):
990 if etype is None:
991 if etype is None:
991 etype, value, tb = sys.exc_info()
992 etype, value, tb = sys.exc_info()
992 if isinstance(tb, tuple):
993 if isinstance(tb, tuple):
993 # tb is a tuple if this is a chained exception.
994 # tb is a tuple if this is a chained exception.
994 self.tb = tb[0]
995 self.tb = tb[0]
995 else:
996 else:
996 self.tb = tb
997 self.tb = tb
997 return FormattedTB.structured_traceback(
998 return FormattedTB.structured_traceback(
998 self, etype, value, tb, tb_offset, number_of_lines_of_context)
999 self, etype, value, tb, tb_offset, number_of_lines_of_context)
999
1000
1000
1001
1001 #---------------------------------------------------------------------------
1002 #---------------------------------------------------------------------------
1002
1003
1003 # A simple class to preserve Nathan's original functionality.
1004 # A simple class to preserve Nathan's original functionality.
1004 class ColorTB(FormattedTB):
1005 class ColorTB(FormattedTB):
1005 """Shorthand to initialize a FormattedTB in Linux colors mode."""
1006 """Shorthand to initialize a FormattedTB in Linux colors mode."""
1006
1007
1007 def __init__(self, color_scheme='Linux', call_pdb=0, **kwargs):
1008 def __init__(self, color_scheme='Linux', call_pdb=0, **kwargs):
1008 FormattedTB.__init__(self, color_scheme=color_scheme,
1009 FormattedTB.__init__(self, color_scheme=color_scheme,
1009 call_pdb=call_pdb, **kwargs)
1010 call_pdb=call_pdb, **kwargs)
1010
1011
1011
1012
1012 class SyntaxTB(ListTB):
1013 class SyntaxTB(ListTB):
1013 """Extension which holds some state: the last exception value"""
1014 """Extension which holds some state: the last exception value"""
1014
1015
1015 def __init__(self, color_scheme='NoColor', parent=None, config=None):
1016 def __init__(self, color_scheme='NoColor', parent=None, config=None):
1016 ListTB.__init__(self, color_scheme, parent=parent, config=config)
1017 ListTB.__init__(self, color_scheme, parent=parent, config=config)
1017 self.last_syntax_error = None
1018 self.last_syntax_error = None
1018
1019
1019 def __call__(self, etype, value, elist):
1020 def __call__(self, etype, value, elist):
1020 self.last_syntax_error = value
1021 self.last_syntax_error = value
1021
1022
1022 ListTB.__call__(self, etype, value, elist)
1023 ListTB.__call__(self, etype, value, elist)
1023
1024
1024 def structured_traceback(self, etype, value, elist, tb_offset=None,
1025 def structured_traceback(self, etype, value, elist, tb_offset=None,
1025 context=5):
1026 context=5):
1026 # If the source file has been edited, the line in the syntax error can
1027 # If the source file has been edited, the line in the syntax error can
1027 # be wrong (retrieved from an outdated cache). This replaces it with
1028 # be wrong (retrieved from an outdated cache). This replaces it with
1028 # the current value.
1029 # the current value.
1029 if isinstance(value, SyntaxError) \
1030 if isinstance(value, SyntaxError) \
1030 and isinstance(value.filename, str) \
1031 and isinstance(value.filename, str) \
1031 and isinstance(value.lineno, int):
1032 and isinstance(value.lineno, int):
1032 linecache.checkcache(value.filename)
1033 linecache.checkcache(value.filename)
1033 newtext = linecache.getline(value.filename, value.lineno)
1034 newtext = linecache.getline(value.filename, value.lineno)
1034 if newtext:
1035 if newtext:
1035 value.text = newtext
1036 value.text = newtext
1036 self.last_syntax_error = value
1037 self.last_syntax_error = value
1037 return super(SyntaxTB, self).structured_traceback(etype, value, elist,
1038 return super(SyntaxTB, self).structured_traceback(etype, value, elist,
1038 tb_offset=tb_offset, context=context)
1039 tb_offset=tb_offset, context=context)
1039
1040
1040 def clear_err_state(self):
1041 def clear_err_state(self):
1041 """Return the current error state and clear it"""
1042 """Return the current error state and clear it"""
1042 e = self.last_syntax_error
1043 e = self.last_syntax_error
1043 self.last_syntax_error = None
1044 self.last_syntax_error = None
1044 return e
1045 return e
1045
1046
1046 def stb2text(self, stb):
1047 def stb2text(self, stb):
1047 """Convert a structured traceback (a list) to a string."""
1048 """Convert a structured traceback (a list) to a string."""
1048 return ''.join(stb)
1049 return ''.join(stb)
1049
1050
1050
1051
1051 # some internal-use functions
1052 # some internal-use functions
1052 def text_repr(value):
1053 def text_repr(value):
1053 """Hopefully pretty robust repr equivalent."""
1054 """Hopefully pretty robust repr equivalent."""
1054 # this is pretty horrible but should always return *something*
1055 # this is pretty horrible but should always return *something*
1055 try:
1056 try:
1056 return pydoc.text.repr(value)
1057 return pydoc.text.repr(value)
1057 except KeyboardInterrupt:
1058 except KeyboardInterrupt:
1058 raise
1059 raise
1059 except:
1060 except:
1060 try:
1061 try:
1061 return repr(value)
1062 return repr(value)
1062 except KeyboardInterrupt:
1063 except KeyboardInterrupt:
1063 raise
1064 raise
1064 except:
1065 except:
1065 try:
1066 try:
1066 # all still in an except block so we catch
1067 # all still in an except block so we catch
1067 # getattr raising
1068 # getattr raising
1068 name = getattr(value, '__name__', None)
1069 name = getattr(value, '__name__', None)
1069 if name:
1070 if name:
1070 # ick, recursion
1071 # ick, recursion
1071 return text_repr(name)
1072 return text_repr(name)
1072 klass = getattr(value, '__class__', None)
1073 klass = getattr(value, '__class__', None)
1073 if klass:
1074 if klass:
1074 return '%s instance' % text_repr(klass)
1075 return '%s instance' % text_repr(klass)
1075 except KeyboardInterrupt:
1076 except KeyboardInterrupt:
1076 raise
1077 raise
1077 except:
1078 except:
1078 return 'UNRECOVERABLE REPR FAILURE'
1079 return 'UNRECOVERABLE REPR FAILURE'
1079
1080
1080
1081
1081 def eqrepr(value, repr=text_repr):
1082 def eqrepr(value, repr=text_repr):
1082 return '=%s' % repr(value)
1083 return '=%s' % repr(value)
1083
1084
1084
1085
1085 def nullrepr(value, repr=text_repr):
1086 def nullrepr(value, repr=text_repr):
1086 return ''
1087 return ''
General Comments 0
You need to be logged in to leave comments. Login now