##// END OF EJS Templates
Merge pull request #12627 from impact27/patch-8
Matthias Bussonnier -
r26176:a0cd6206 merge
parent child Browse files
Show More
@@ -1,821 +1,833 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 def set_trace(self, frame=None):
290 def set_trace(self, frame=None):
291 if frame is None:
291 if frame is None:
292 frame = sys._getframe().f_back
292 frame = sys._getframe().f_back
293 self.initial_frame = frame
293 self.initial_frame = frame
294 return super().set_trace(frame)
294 return super().set_trace(frame)
295
295
296 def hidden_frames(self, stack):
296 def hidden_frames(self, stack):
297 """
297 """
298 Given an index in the stack return whether it should be skipped.
298 Given an index in the stack return whether it should be skipped.
299
299
300 This is used in up/down and where to skip frames.
300 This is used in up/down and where to skip frames.
301 """
301 """
302 # The f_locals dictionary is updated from the actual frame
302 # The f_locals dictionary is updated from the actual frame
303 # locals whenever the .f_locals accessor is called, so we
303 # locals whenever the .f_locals accessor is called, so we
304 # avoid calling it here to preserve self.curframe_locals.
304 # avoid calling it here to preserve self.curframe_locals.
305 # Futhermore, there is no good reason to hide the current frame.
305 # Futhermore, there is no good reason to hide the current frame.
306 ip_hide = [
306 ip_hide = [
307 False
307 False
308 if s[0] in (self.curframe, getattr(self, "initial_frame", None))
308 if s[0] in (self.curframe, getattr(self, "initial_frame", None))
309 else s[0].f_locals.get("__tracebackhide__", False)
309 else s[0].f_locals.get("__tracebackhide__", False)
310 for s in stack
310 for s in stack
311 ]
311 ]
312 ip_start = [i for i, s in enumerate(ip_hide) if s == "__ipython_bottom__"]
312 ip_start = [i for i, s in enumerate(ip_hide) if s == "__ipython_bottom__"]
313 if ip_start:
313 if ip_start:
314 ip_hide = [h if i > ip_start[0] else True for (i, h) in enumerate(ip_hide)]
314 ip_hide = [h if i > ip_start[0] else True for (i, h) in enumerate(ip_hide)]
315 return ip_hide
315 return ip_hide
316
316
317 def interaction(self, frame, traceback):
317 def interaction(self, frame, traceback):
318 try:
318 try:
319 OldPdb.interaction(self, frame, traceback)
319 OldPdb.interaction(self, frame, traceback)
320 except KeyboardInterrupt:
320 except KeyboardInterrupt:
321 self.stdout.write("\n" + self.shell.get_exception_only())
321 self.stdout.write("\n" + self.shell.get_exception_only())
322
322
323 def new_do_frame(self, arg):
323 def new_do_frame(self, arg):
324 OldPdb.do_frame(self, arg)
324 OldPdb.do_frame(self, arg)
325
325
326 def new_do_quit(self, arg):
326 def new_do_quit(self, arg):
327
327
328 if hasattr(self, 'old_all_completions'):
328 if hasattr(self, 'old_all_completions'):
329 self.shell.Completer.all_completions=self.old_all_completions
329 self.shell.Completer.all_completions=self.old_all_completions
330
330
331 return OldPdb.do_quit(self, arg)
331 return OldPdb.do_quit(self, arg)
332
332
333 do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit)
333 do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit)
334
334
335 def new_do_restart(self, arg):
335 def new_do_restart(self, arg):
336 """Restart command. In the context of ipython this is exactly the same
336 """Restart command. In the context of ipython this is exactly the same
337 thing as 'quit'."""
337 thing as 'quit'."""
338 self.msg("Restart doesn't make sense here. Using 'quit' instead.")
338 self.msg("Restart doesn't make sense here. Using 'quit' instead.")
339 return self.do_quit(arg)
339 return self.do_quit(arg)
340
340
341 def print_stack_trace(self, context=None):
341 def print_stack_trace(self, context=None):
342 Colors = self.color_scheme_table.active_colors
342 Colors = self.color_scheme_table.active_colors
343 ColorsNormal = Colors.Normal
343 ColorsNormal = Colors.Normal
344 if context is None:
344 if context is None:
345 context = self.context
345 context = self.context
346 try:
346 try:
347 context=int(context)
347 context=int(context)
348 if context <= 0:
348 if context <= 0:
349 raise ValueError("Context must be a positive integer")
349 raise ValueError("Context must be a positive integer")
350 except (TypeError, ValueError) as e:
350 except (TypeError, ValueError) as e:
351 raise ValueError("Context must be a positive integer") from e
351 raise ValueError("Context must be a positive integer") from e
352 try:
352 try:
353 skipped = 0
353 skipped = 0
354 for hidden, frame_lineno in zip(self.hidden_frames(self.stack), self.stack):
354 for hidden, frame_lineno in zip(self.hidden_frames(self.stack), self.stack):
355 if hidden and self.skip_hidden:
355 if hidden and self.skip_hidden:
356 skipped += 1
356 skipped += 1
357 continue
357 continue
358 if skipped:
358 if skipped:
359 print(
359 print(
360 f"{Colors.excName} [... skipping {skipped} hidden frame(s)]{ColorsNormal}\n"
360 f"{Colors.excName} [... skipping {skipped} hidden frame(s)]{ColorsNormal}\n"
361 )
361 )
362 skipped = 0
362 skipped = 0
363 self.print_stack_entry(frame_lineno, context=context)
363 self.print_stack_entry(frame_lineno, context=context)
364 if skipped:
364 if skipped:
365 print(
365 print(
366 f"{Colors.excName} [... skipping {skipped} hidden frame(s)]{ColorsNormal}\n"
366 f"{Colors.excName} [... skipping {skipped} hidden frame(s)]{ColorsNormal}\n"
367 )
367 )
368 except KeyboardInterrupt:
368 except KeyboardInterrupt:
369 pass
369 pass
370
370
371 def print_stack_entry(self, frame_lineno, prompt_prefix='\n-> ',
371 def print_stack_entry(self, frame_lineno, prompt_prefix='\n-> ',
372 context=None):
372 context=None):
373 if context is None:
373 if context is None:
374 context = self.context
374 context = self.context
375 try:
375 try:
376 context=int(context)
376 context=int(context)
377 if context <= 0:
377 if context <= 0:
378 raise ValueError("Context must be a positive integer")
378 raise ValueError("Context must be a positive integer")
379 except (TypeError, ValueError) as e:
379 except (TypeError, ValueError) as e:
380 raise ValueError("Context must be a positive integer") from e
380 raise ValueError("Context must be a positive integer") from e
381 print(self.format_stack_entry(frame_lineno, '', context), file=self.stdout)
381 print(self.format_stack_entry(frame_lineno, '', context), file=self.stdout)
382
382
383 # vds: >>
383 # vds: >>
384 frame, lineno = frame_lineno
384 frame, lineno = frame_lineno
385 filename = frame.f_code.co_filename
385 filename = frame.f_code.co_filename
386 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
386 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
387 # vds: <<
387 # vds: <<
388
388
389 def format_stack_entry(self, frame_lineno, lprefix=': ', context=None):
389 def format_stack_entry(self, frame_lineno, lprefix=': ', context=None):
390 if context is None:
390 if context is None:
391 context = self.context
391 context = self.context
392 try:
392 try:
393 context=int(context)
393 context=int(context)
394 if context <= 0:
394 if context <= 0:
395 print("Context must be a positive integer", file=self.stdout)
395 print("Context must be a positive integer", file=self.stdout)
396 except (TypeError, ValueError):
396 except (TypeError, ValueError):
397 print("Context must be a positive integer", file=self.stdout)
397 print("Context must be a positive integer", file=self.stdout)
398
398
399 import reprlib
399 import reprlib
400
400
401 ret = []
401 ret = []
402
402
403 Colors = self.color_scheme_table.active_colors
403 Colors = self.color_scheme_table.active_colors
404 ColorsNormal = Colors.Normal
404 ColorsNormal = Colors.Normal
405 tpl_link = u'%s%%s%s' % (Colors.filenameEm, ColorsNormal)
405 tpl_link = u'%s%%s%s' % (Colors.filenameEm, ColorsNormal)
406 tpl_call = u'%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal)
406 tpl_call = u'%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal)
407 tpl_line = u'%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
407 tpl_line = u'%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
408 tpl_line_em = u'%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line,
408 tpl_line_em = u'%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line,
409 ColorsNormal)
409 ColorsNormal)
410
410
411 frame, lineno = frame_lineno
411 frame, lineno = frame_lineno
412
412
413 return_value = ''
413 return_value = ''
414 if '__return__' in frame.f_locals:
414 if '__return__' in frame.f_locals:
415 rv = frame.f_locals['__return__']
415 rv = frame.f_locals['__return__']
416 #return_value += '->'
416 #return_value += '->'
417 return_value += reprlib.repr(rv) + '\n'
417 return_value += reprlib.repr(rv) + '\n'
418 ret.append(return_value)
418 ret.append(return_value)
419
419
420 #s = filename + '(' + `lineno` + ')'
420 #s = filename + '(' + `lineno` + ')'
421 filename = self.canonic(frame.f_code.co_filename)
421 filename = self.canonic(frame.f_code.co_filename)
422 link = tpl_link % py3compat.cast_unicode(filename)
422 link = tpl_link % py3compat.cast_unicode(filename)
423
423
424 if frame.f_code.co_name:
424 if frame.f_code.co_name:
425 func = frame.f_code.co_name
425 func = frame.f_code.co_name
426 else:
426 else:
427 func = "<lambda>"
427 func = "<lambda>"
428
428
429 call = ''
429 call = ''
430 if func != '?':
430 if func != '?':
431 if '__args__' in frame.f_locals:
431 if '__args__' in frame.f_locals:
432 args = reprlib.repr(frame.f_locals['__args__'])
432 args = reprlib.repr(frame.f_locals['__args__'])
433 else:
433 else:
434 args = '()'
434 args = '()'
435 call = tpl_call % (func, args)
435 call = tpl_call % (func, args)
436
436
437 # The level info should be generated in the same format pdb uses, to
437 # The level info should be generated in the same format pdb uses, to
438 # avoid breaking the pdbtrack functionality of python-mode in *emacs.
438 # avoid breaking the pdbtrack functionality of python-mode in *emacs.
439 if frame is self.curframe:
439 if frame is self.curframe:
440 ret.append('> ')
440 ret.append('> ')
441 else:
441 else:
442 ret.append(' ')
442 ret.append(' ')
443 ret.append(u'%s(%s)%s\n' % (link,lineno,call))
443 ret.append(u'%s(%s)%s\n' % (link,lineno,call))
444
444
445 start = lineno - 1 - context//2
445 start = lineno - 1 - context//2
446 lines = linecache.getlines(filename)
446 lines = linecache.getlines(filename)
447 start = min(start, len(lines) - context)
447 start = min(start, len(lines) - context)
448 start = max(start, 0)
448 start = max(start, 0)
449 lines = lines[start : start + context]
449 lines = lines[start : start + context]
450
450
451 for i,line in enumerate(lines):
451 for i,line in enumerate(lines):
452 show_arrow = (start + 1 + i == lineno)
452 show_arrow = (start + 1 + i == lineno)
453 linetpl = (frame is self.curframe or show_arrow) \
453 linetpl = (frame is self.curframe or show_arrow) \
454 and tpl_line_em \
454 and tpl_line_em \
455 or tpl_line
455 or tpl_line
456 ret.append(self.__format_line(linetpl, filename,
456 ret.append(self.__format_line(linetpl, filename,
457 start + 1 + i, line,
457 start + 1 + i, line,
458 arrow = show_arrow) )
458 arrow = show_arrow) )
459 return ''.join(ret)
459 return ''.join(ret)
460
460
461 def __format_line(self, tpl_line, filename, lineno, line, arrow = False):
461 def __format_line(self, tpl_line, filename, lineno, line, arrow = False):
462 bp_mark = ""
462 bp_mark = ""
463 bp_mark_color = ""
463 bp_mark_color = ""
464
464
465 new_line, err = self.parser.format2(line, 'str')
465 new_line, err = self.parser.format2(line, 'str')
466 if not err:
466 if not err:
467 line = new_line
467 line = new_line
468
468
469 bp = None
469 bp = None
470 if lineno in self.get_file_breaks(filename):
470 if lineno in self.get_file_breaks(filename):
471 bps = self.get_breaks(filename, lineno)
471 bps = self.get_breaks(filename, lineno)
472 bp = bps[-1]
472 bp = bps[-1]
473
473
474 if bp:
474 if bp:
475 Colors = self.color_scheme_table.active_colors
475 Colors = self.color_scheme_table.active_colors
476 bp_mark = str(bp.number)
476 bp_mark = str(bp.number)
477 bp_mark_color = Colors.breakpoint_enabled
477 bp_mark_color = Colors.breakpoint_enabled
478 if not bp.enabled:
478 if not bp.enabled:
479 bp_mark_color = Colors.breakpoint_disabled
479 bp_mark_color = Colors.breakpoint_disabled
480
480
481 numbers_width = 7
481 numbers_width = 7
482 if arrow:
482 if arrow:
483 # This is the line with the error
483 # This is the line with the error
484 pad = numbers_width - len(str(lineno)) - len(bp_mark)
484 pad = numbers_width - len(str(lineno)) - len(bp_mark)
485 num = '%s%s' % (make_arrow(pad), str(lineno))
485 num = '%s%s' % (make_arrow(pad), str(lineno))
486 else:
486 else:
487 num = '%*s' % (numbers_width - len(bp_mark), str(lineno))
487 num = '%*s' % (numbers_width - len(bp_mark), str(lineno))
488
488
489 return tpl_line % (bp_mark_color + bp_mark, num, line)
489 return tpl_line % (bp_mark_color + bp_mark, num, line)
490
490
491
491
492 def print_list_lines(self, filename, first, last):
492 def print_list_lines(self, filename, first, last):
493 """The printing (as opposed to the parsing part of a 'list'
493 """The printing (as opposed to the parsing part of a 'list'
494 command."""
494 command."""
495 try:
495 try:
496 Colors = self.color_scheme_table.active_colors
496 Colors = self.color_scheme_table.active_colors
497 ColorsNormal = Colors.Normal
497 ColorsNormal = Colors.Normal
498 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
498 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
499 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal)
499 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal)
500 src = []
500 src = []
501 if filename == "<string>" and hasattr(self, "_exec_filename"):
501 if filename == "<string>" and hasattr(self, "_exec_filename"):
502 filename = self._exec_filename
502 filename = self._exec_filename
503
503
504 for lineno in range(first, last+1):
504 for lineno in range(first, last+1):
505 line = linecache.getline(filename, lineno)
505 line = linecache.getline(filename, lineno)
506 if not line:
506 if not line:
507 break
507 break
508
508
509 if lineno == self.curframe.f_lineno:
509 if lineno == self.curframe.f_lineno:
510 line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True)
510 line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True)
511 else:
511 else:
512 line = self.__format_line(tpl_line, filename, lineno, line, arrow = False)
512 line = self.__format_line(tpl_line, filename, lineno, line, arrow = False)
513
513
514 src.append(line)
514 src.append(line)
515 self.lineno = lineno
515 self.lineno = lineno
516
516
517 print(''.join(src), file=self.stdout)
517 print(''.join(src), file=self.stdout)
518
518
519 except KeyboardInterrupt:
519 except KeyboardInterrupt:
520 pass
520 pass
521
521
522 def do_skip_hidden(self, arg):
522 def do_skip_hidden(self, arg):
523 """
523 """
524 Change whether or not we should skip frames with the
524 Change whether or not we should skip frames with the
525 __tracebackhide__ attribute.
525 __tracebackhide__ attribute.
526 """
526 """
527 if arg.strip().lower() in ("true", "yes"):
527 if arg.strip().lower() in ("true", "yes"):
528 self.skip_hidden = True
528 self.skip_hidden = True
529 elif arg.strip().lower() in ("false", "no"):
529 elif arg.strip().lower() in ("false", "no"):
530 self.skip_hidden = False
530 self.skip_hidden = False
531
531
532 def do_list(self, arg):
532 def do_list(self, arg):
533 """Print lines of code from the current stack frame
533 """Print lines of code from the current stack frame
534 """
534 """
535 self.lastcmd = 'list'
535 self.lastcmd = 'list'
536 last = None
536 last = None
537 if arg:
537 if arg:
538 try:
538 try:
539 x = eval(arg, {}, {})
539 x = eval(arg, {}, {})
540 if type(x) == type(()):
540 if type(x) == type(()):
541 first, last = x
541 first, last = x
542 first = int(first)
542 first = int(first)
543 last = int(last)
543 last = int(last)
544 if last < first:
544 if last < first:
545 # Assume it's a count
545 # Assume it's a count
546 last = first + last
546 last = first + last
547 else:
547 else:
548 first = max(1, int(x) - 5)
548 first = max(1, int(x) - 5)
549 except:
549 except:
550 print('*** Error in argument:', repr(arg), file=self.stdout)
550 print('*** Error in argument:', repr(arg), file=self.stdout)
551 return
551 return
552 elif self.lineno is None:
552 elif self.lineno is None:
553 first = max(1, self.curframe.f_lineno - 5)
553 first = max(1, self.curframe.f_lineno - 5)
554 else:
554 else:
555 first = self.lineno + 1
555 first = self.lineno + 1
556 if last is None:
556 if last is None:
557 last = first + 10
557 last = first + 10
558 self.print_list_lines(self.curframe.f_code.co_filename, first, last)
558 self.print_list_lines(self.curframe.f_code.co_filename, first, last)
559
559
560 # vds: >>
560 # vds: >>
561 lineno = first
561 lineno = first
562 filename = self.curframe.f_code.co_filename
562 filename = self.curframe.f_code.co_filename
563 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
563 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
564 # vds: <<
564 # vds: <<
565
565
566 do_l = do_list
566 do_l = do_list
567
567
568 def getsourcelines(self, obj):
568 def getsourcelines(self, obj):
569 lines, lineno = inspect.findsource(obj)
569 lines, lineno = inspect.findsource(obj)
570 if inspect.isframe(obj) and obj.f_globals is obj.f_locals:
570 if inspect.isframe(obj) and obj.f_globals is obj.f_locals:
571 # must be a module frame: do not try to cut a block out of it
571 # must be a module frame: do not try to cut a block out of it
572 return lines, 1
572 return lines, 1
573 elif inspect.ismodule(obj):
573 elif inspect.ismodule(obj):
574 return lines, 1
574 return lines, 1
575 return inspect.getblock(lines[lineno:]), lineno+1
575 return inspect.getblock(lines[lineno:]), lineno+1
576
576
577 def do_longlist(self, arg):
577 def do_longlist(self, arg):
578 """Print lines of code from the current stack frame.
578 """Print lines of code from the current stack frame.
579
579
580 Shows more lines than 'list' does.
580 Shows more lines than 'list' does.
581 """
581 """
582 self.lastcmd = 'longlist'
582 self.lastcmd = 'longlist'
583 try:
583 try:
584 lines, lineno = self.getsourcelines(self.curframe)
584 lines, lineno = self.getsourcelines(self.curframe)
585 except OSError as err:
585 except OSError as err:
586 self.error(err)
586 self.error(err)
587 return
587 return
588 last = lineno + len(lines)
588 last = lineno + len(lines)
589 self.print_list_lines(self.curframe.f_code.co_filename, lineno, last)
589 self.print_list_lines(self.curframe.f_code.co_filename, lineno, last)
590 do_ll = do_longlist
590 do_ll = do_longlist
591
591
592 def do_debug(self, arg):
592 def do_debug(self, arg):
593 """debug code
593 """debug code
594 Enter a recursive debugger that steps through the code
594 Enter a recursive debugger that steps through the code
595 argument (which is an arbitrary expression or statement to be
595 argument (which is an arbitrary expression or statement to be
596 executed in the current environment).
596 executed in the current environment).
597 """
597 """
598 trace_function = sys.gettrace()
598 trace_function = sys.gettrace()
599 sys.settrace(None)
599 sys.settrace(None)
600 globals = self.curframe.f_globals
600 globals = self.curframe.f_globals
601 locals = self.curframe_locals
601 locals = self.curframe_locals
602 p = self.__class__(completekey=self.completekey,
602 p = self.__class__(completekey=self.completekey,
603 stdin=self.stdin, stdout=self.stdout)
603 stdin=self.stdin, stdout=self.stdout)
604 p.use_rawinput = self.use_rawinput
604 p.use_rawinput = self.use_rawinput
605 p.prompt = "(%s) " % self.prompt.strip()
605 p.prompt = "(%s) " % self.prompt.strip()
606 self.message("ENTERING RECURSIVE DEBUGGER")
606 self.message("ENTERING RECURSIVE DEBUGGER")
607 sys.call_tracing(p.run, (arg, globals, locals))
607 sys.call_tracing(p.run, (arg, globals, locals))
608 self.message("LEAVING RECURSIVE DEBUGGER")
608 self.message("LEAVING RECURSIVE DEBUGGER")
609 sys.settrace(trace_function)
609 sys.settrace(trace_function)
610 self.lastcmd = p.lastcmd
610 self.lastcmd = p.lastcmd
611
611
612 def do_pdef(self, arg):
612 def do_pdef(self, arg):
613 """Print the call signature for any callable object.
613 """Print the call signature for any callable object.
614
614
615 The debugger interface to %pdef"""
615 The debugger interface to %pdef"""
616 namespaces = [('Locals', self.curframe.f_locals),
616 namespaces = [
617 ('Globals', self.curframe.f_globals)]
617 ("Locals", self.curframe_locals),
618 self.shell.find_line_magic('pdef')(arg, namespaces=namespaces)
618 ("Globals", self.curframe.f_globals),
619 ]
620 self.shell.find_line_magic("pdef")(arg, namespaces=namespaces)
619
621
620 def do_pdoc(self, arg):
622 def do_pdoc(self, arg):
621 """Print the docstring for an object.
623 """Print the docstring for an object.
622
624
623 The debugger interface to %pdoc."""
625 The debugger interface to %pdoc."""
624 namespaces = [('Locals', self.curframe.f_locals),
626 namespaces = [
625 ('Globals', self.curframe.f_globals)]
627 ("Locals", self.curframe_locals),
626 self.shell.find_line_magic('pdoc')(arg, namespaces=namespaces)
628 ("Globals", self.curframe.f_globals),
629 ]
630 self.shell.find_line_magic("pdoc")(arg, namespaces=namespaces)
627
631
628 def do_pfile(self, arg):
632 def do_pfile(self, arg):
629 """Print (or run through pager) the file where an object is defined.
633 """Print (or run through pager) the file where an object is defined.
630
634
631 The debugger interface to %pfile.
635 The debugger interface to %pfile.
632 """
636 """
633 namespaces = [('Locals', self.curframe.f_locals),
637 namespaces = [
634 ('Globals', self.curframe.f_globals)]
638 ("Locals", self.curframe_locals),
635 self.shell.find_line_magic('pfile')(arg, namespaces=namespaces)
639 ("Globals", self.curframe.f_globals),
640 ]
641 self.shell.find_line_magic("pfile")(arg, namespaces=namespaces)
636
642
637 def do_pinfo(self, arg):
643 def do_pinfo(self, arg):
638 """Provide detailed information about an object.
644 """Provide detailed information about an object.
639
645
640 The debugger interface to %pinfo, i.e., obj?."""
646 The debugger interface to %pinfo, i.e., obj?."""
641 namespaces = [('Locals', self.curframe.f_locals),
647 namespaces = [
642 ('Globals', self.curframe.f_globals)]
648 ("Locals", self.curframe_locals),
643 self.shell.find_line_magic('pinfo')(arg, namespaces=namespaces)
649 ("Globals", self.curframe.f_globals),
650 ]
651 self.shell.find_line_magic("pinfo")(arg, namespaces=namespaces)
644
652
645 def do_pinfo2(self, arg):
653 def do_pinfo2(self, arg):
646 """Provide extra detailed information about an object.
654 """Provide extra detailed information about an object.
647
655
648 The debugger interface to %pinfo2, i.e., obj??."""
656 The debugger interface to %pinfo2, i.e., obj??."""
649 namespaces = [('Locals', self.curframe.f_locals),
657 namespaces = [
650 ('Globals', self.curframe.f_globals)]
658 ("Locals", self.curframe_locals),
651 self.shell.find_line_magic('pinfo2')(arg, namespaces=namespaces)
659 ("Globals", self.curframe.f_globals),
660 ]
661 self.shell.find_line_magic("pinfo2")(arg, namespaces=namespaces)
652
662
653 def do_psource(self, arg):
663 def do_psource(self, arg):
654 """Print (or run through pager) the source code for an object."""
664 """Print (or run through pager) the source code for an object."""
655 namespaces = [('Locals', self.curframe.f_locals),
665 namespaces = [
656 ('Globals', self.curframe.f_globals)]
666 ("Locals", self.curframe_locals),
657 self.shell.find_line_magic('psource')(arg, namespaces=namespaces)
667 ("Globals", self.curframe.f_globals),
668 ]
669 self.shell.find_line_magic("psource")(arg, namespaces=namespaces)
658
670
659 def do_where(self, arg):
671 def do_where(self, arg):
660 """w(here)
672 """w(here)
661 Print a stack trace, with the most recent frame at the bottom.
673 Print a stack trace, with the most recent frame at the bottom.
662 An arrow indicates the "current frame", which determines the
674 An arrow indicates the "current frame", which determines the
663 context of most commands. 'bt' is an alias for this command.
675 context of most commands. 'bt' is an alias for this command.
664
676
665 Take a number as argument as an (optional) number of context line to
677 Take a number as argument as an (optional) number of context line to
666 print"""
678 print"""
667 if arg:
679 if arg:
668 try:
680 try:
669 context = int(arg)
681 context = int(arg)
670 except ValueError as err:
682 except ValueError as err:
671 self.error(err)
683 self.error(err)
672 return
684 return
673 self.print_stack_trace(context)
685 self.print_stack_trace(context)
674 else:
686 else:
675 self.print_stack_trace()
687 self.print_stack_trace()
676
688
677 do_w = do_where
689 do_w = do_where
678
690
679 def stop_here(self, frame):
691 def stop_here(self, frame):
680 hidden = False
692 hidden = False
681 if self.skip_hidden:
693 if self.skip_hidden:
682 hidden = frame.f_locals.get("__tracebackhide__", False)
694 hidden = frame.f_locals.get("__tracebackhide__", False)
683 if hidden:
695 if hidden:
684 Colors = self.color_scheme_table.active_colors
696 Colors = self.color_scheme_table.active_colors
685 ColorsNormal = Colors.Normal
697 ColorsNormal = Colors.Normal
686 print(f"{Colors.excName} [... skipped 1 hidden frame]{ColorsNormal}\n")
698 print(f"{Colors.excName} [... skipped 1 hidden frame]{ColorsNormal}\n")
687
699
688 return super().stop_here(frame)
700 return super().stop_here(frame)
689
701
690 def do_up(self, arg):
702 def do_up(self, arg):
691 """u(p) [count]
703 """u(p) [count]
692 Move the current frame count (default one) levels up in the
704 Move the current frame count (default one) levels up in the
693 stack trace (to an older frame).
705 stack trace (to an older frame).
694
706
695 Will skip hidden frames.
707 Will skip hidden frames.
696 """
708 """
697 ## modified version of upstream that skips
709 ## modified version of upstream that skips
698 # frames with __tracebackide__
710 # frames with __tracebackide__
699 if self.curindex == 0:
711 if self.curindex == 0:
700 self.error("Oldest frame")
712 self.error("Oldest frame")
701 return
713 return
702 try:
714 try:
703 count = int(arg or 1)
715 count = int(arg or 1)
704 except ValueError:
716 except ValueError:
705 self.error("Invalid frame count (%s)" % arg)
717 self.error("Invalid frame count (%s)" % arg)
706 return
718 return
707 skipped = 0
719 skipped = 0
708 if count < 0:
720 if count < 0:
709 _newframe = 0
721 _newframe = 0
710 else:
722 else:
711 _newindex = self.curindex
723 _newindex = self.curindex
712 counter = 0
724 counter = 0
713 hidden_frames = self.hidden_frames(self.stack)
725 hidden_frames = self.hidden_frames(self.stack)
714 for i in range(self.curindex - 1, -1, -1):
726 for i in range(self.curindex - 1, -1, -1):
715 frame = self.stack[i][0]
727 frame = self.stack[i][0]
716 if hidden_frames[i] and self.skip_hidden:
728 if hidden_frames[i] and self.skip_hidden:
717 skipped += 1
729 skipped += 1
718 continue
730 continue
719 counter += 1
731 counter += 1
720 if counter >= count:
732 if counter >= count:
721 break
733 break
722 else:
734 else:
723 # if no break occured.
735 # if no break occured.
724 self.error(
736 self.error(
725 "all frames above hidden, use `skip_hidden False` to get get into those."
737 "all frames above hidden, use `skip_hidden False` to get get into those."
726 )
738 )
727 return
739 return
728
740
729 Colors = self.color_scheme_table.active_colors
741 Colors = self.color_scheme_table.active_colors
730 ColorsNormal = Colors.Normal
742 ColorsNormal = Colors.Normal
731 _newframe = i
743 _newframe = i
732 self._select_frame(_newframe)
744 self._select_frame(_newframe)
733 if skipped:
745 if skipped:
734 print(
746 print(
735 f"{Colors.excName} [... skipped {skipped} hidden frame(s)]{ColorsNormal}\n"
747 f"{Colors.excName} [... skipped {skipped} hidden frame(s)]{ColorsNormal}\n"
736 )
748 )
737
749
738 def do_down(self, arg):
750 def do_down(self, arg):
739 """d(own) [count]
751 """d(own) [count]
740 Move the current frame count (default one) levels down in the
752 Move the current frame count (default one) levels down in the
741 stack trace (to a newer frame).
753 stack trace (to a newer frame).
742
754
743 Will skip hidden frames.
755 Will skip hidden frames.
744 """
756 """
745 if self.curindex + 1 == len(self.stack):
757 if self.curindex + 1 == len(self.stack):
746 self.error("Newest frame")
758 self.error("Newest frame")
747 return
759 return
748 try:
760 try:
749 count = int(arg or 1)
761 count = int(arg or 1)
750 except ValueError:
762 except ValueError:
751 self.error("Invalid frame count (%s)" % arg)
763 self.error("Invalid frame count (%s)" % arg)
752 return
764 return
753 if count < 0:
765 if count < 0:
754 _newframe = len(self.stack) - 1
766 _newframe = len(self.stack) - 1
755 else:
767 else:
756 _newindex = self.curindex
768 _newindex = self.curindex
757 counter = 0
769 counter = 0
758 skipped = 0
770 skipped = 0
759 hidden_frames = self.hidden_frames(self.stack)
771 hidden_frames = self.hidden_frames(self.stack)
760 for i in range(self.curindex + 1, len(self.stack)):
772 for i in range(self.curindex + 1, len(self.stack)):
761 frame = self.stack[i][0]
773 frame = self.stack[i][0]
762 if hidden_frames[i] and self.skip_hidden:
774 if hidden_frames[i] and self.skip_hidden:
763 skipped += 1
775 skipped += 1
764 continue
776 continue
765 counter += 1
777 counter += 1
766 if counter >= count:
778 if counter >= count:
767 break
779 break
768 else:
780 else:
769 self.error(
781 self.error(
770 "all frames bellow hidden, use `skip_hidden False` to get get into those."
782 "all frames bellow hidden, use `skip_hidden False` to get get into those."
771 )
783 )
772 return
784 return
773
785
774 Colors = self.color_scheme_table.active_colors
786 Colors = self.color_scheme_table.active_colors
775 ColorsNormal = Colors.Normal
787 ColorsNormal = Colors.Normal
776 if skipped:
788 if skipped:
777 print(
789 print(
778 f"{Colors.excName} [... skipped {skipped} hidden frame(s)]{ColorsNormal}\n"
790 f"{Colors.excName} [... skipped {skipped} hidden frame(s)]{ColorsNormal}\n"
779 )
791 )
780 _newframe = i
792 _newframe = i
781
793
782 self._select_frame(_newframe)
794 self._select_frame(_newframe)
783
795
784 do_d = do_down
796 do_d = do_down
785 do_u = do_up
797 do_u = do_up
786
798
787 class InterruptiblePdb(Pdb):
799 class InterruptiblePdb(Pdb):
788 """Version of debugger where KeyboardInterrupt exits the debugger altogether."""
800 """Version of debugger where KeyboardInterrupt exits the debugger altogether."""
789
801
790 def cmdloop(self):
802 def cmdloop(self):
791 """Wrap cmdloop() such that KeyboardInterrupt stops the debugger."""
803 """Wrap cmdloop() such that KeyboardInterrupt stops the debugger."""
792 try:
804 try:
793 return OldPdb.cmdloop(self)
805 return OldPdb.cmdloop(self)
794 except KeyboardInterrupt:
806 except KeyboardInterrupt:
795 self.stop_here = lambda frame: False
807 self.stop_here = lambda frame: False
796 self.do_quit("")
808 self.do_quit("")
797 sys.settrace(None)
809 sys.settrace(None)
798 self.quitting = False
810 self.quitting = False
799 raise
811 raise
800
812
801 def _cmdloop(self):
813 def _cmdloop(self):
802 while True:
814 while True:
803 try:
815 try:
804 # keyboard interrupts allow for an easy way to cancel
816 # keyboard interrupts allow for an easy way to cancel
805 # the current command, so allow them during interactive input
817 # the current command, so allow them during interactive input
806 self.allow_kbdint = True
818 self.allow_kbdint = True
807 self.cmdloop()
819 self.cmdloop()
808 self.allow_kbdint = False
820 self.allow_kbdint = False
809 break
821 break
810 except KeyboardInterrupt:
822 except KeyboardInterrupt:
811 self.message('--KeyboardInterrupt--')
823 self.message('--KeyboardInterrupt--')
812 raise
824 raise
813
825
814
826
815 def set_trace(frame=None):
827 def set_trace(frame=None):
816 """
828 """
817 Start debugging from `frame`.
829 Start debugging from `frame`.
818
830
819 If frame is not specified, debugging starts from caller's frame.
831 If frame is not specified, debugging starts from caller's frame.
820 """
832 """
821 Pdb().set_trace(frame or sys._getframe().f_back)
833 Pdb().set_trace(frame or sys._getframe().f_back)
General Comments 0
You need to be logged in to leave comments. Login now