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