##// END OF EJS Templates
Merge pull request #12631 from Carreau/last-frame-debugger...
Matthias Bussonnier -
r26150:93d31bb9 merge
parent child Browse files
Show More

The requested changes are too big and content was truncated. Show full diff

@@ -1,813 +1,820 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 Pdb debugger class.
4 4
5 5 Modified from the standard pdb.Pdb class to avoid including readline, so that
6 6 the command line completion of other programs which include this isn't
7 7 damaged.
8 8
9 9 In the future, this class will be expanded with improvements over the standard
10 10 pdb.
11 11
12 12 The code in this file is mainly lifted out of cmd.py in Python 2.2, with minor
13 13 changes. Licensing should therefore be under the standard Python terms. For
14 14 details on the PSF (Python Software Foundation) standard license, see:
15 15
16 16 https://docs.python.org/2/license.html
17 17 """
18 18
19 19 #*****************************************************************************
20 20 #
21 21 # This file is licensed under the PSF license.
22 22 #
23 23 # Copyright (C) 2001 Python Software Foundation, www.python.org
24 24 # Copyright (C) 2005-2006 Fernando Perez. <fperez@colorado.edu>
25 25 #
26 26 #
27 27 #*****************************************************************************
28 28
29 29 import bdb
30 30 import functools
31 31 import inspect
32 32 import linecache
33 33 import sys
34 34 import warnings
35 35 import re
36 36
37 37 from IPython import get_ipython
38 38 from IPython.utils import PyColorize
39 39 from IPython.utils import coloransi, py3compat
40 40 from IPython.core.excolors import exception_colors
41 41 from IPython.testing.skipdoctest import skip_doctest
42 42
43 43
44 44 prompt = 'ipdb> '
45 45
46 46 #We have to check this directly from sys.argv, config struct not yet available
47 47 from pdb import Pdb as OldPdb
48 48
49 49 # Allow the set_trace code to operate outside of an ipython instance, even if
50 50 # it does so with some limitations. The rest of this support is implemented in
51 51 # the Tracer constructor.
52 52
53 53 def make_arrow(pad):
54 54 """generate the leading arrow in front of traceback or debugger"""
55 55 if pad >= 2:
56 56 return '-'*(pad-2) + '> '
57 57 elif pad == 1:
58 58 return '>'
59 59 return ''
60 60
61 61
62 62 def BdbQuit_excepthook(et, ev, tb, excepthook=None):
63 63 """Exception hook which handles `BdbQuit` exceptions.
64 64
65 65 All other exceptions are processed using the `excepthook`
66 66 parameter.
67 67 """
68 68 warnings.warn("`BdbQuit_excepthook` is deprecated since version 5.1",
69 69 DeprecationWarning, stacklevel=2)
70 70 if et==bdb.BdbQuit:
71 71 print('Exiting Debugger.')
72 72 elif excepthook is not None:
73 73 excepthook(et, ev, tb)
74 74 else:
75 75 # Backwards compatibility. Raise deprecation warning?
76 76 BdbQuit_excepthook.excepthook_ori(et,ev,tb)
77 77
78 78
79 79 def BdbQuit_IPython_excepthook(self,et,ev,tb,tb_offset=None):
80 80 warnings.warn(
81 81 "`BdbQuit_IPython_excepthook` is deprecated since version 5.1",
82 82 DeprecationWarning, stacklevel=2)
83 83 print('Exiting Debugger.')
84 84
85 85
86 86 class Tracer(object):
87 87 """
88 88 DEPRECATED
89 89
90 90 Class for local debugging, similar to pdb.set_trace.
91 91
92 92 Instances of this class, when called, behave like pdb.set_trace, but
93 93 providing IPython's enhanced capabilities.
94 94
95 95 This is implemented as a class which must be initialized in your own code
96 96 and not as a standalone function because we need to detect at runtime
97 97 whether IPython is already active or not. That detection is done in the
98 98 constructor, ensuring that this code plays nicely with a running IPython,
99 99 while functioning acceptably (though with limitations) if outside of it.
100 100 """
101 101
102 102 @skip_doctest
103 103 def __init__(self, colors=None):
104 104 """
105 105 DEPRECATED
106 106
107 107 Create a local debugger instance.
108 108
109 109 Parameters
110 110 ----------
111 111
112 112 colors : str, optional
113 113 The name of the color scheme to use, it must be one of IPython's
114 114 valid color schemes. If not given, the function will default to
115 115 the current IPython scheme when running inside IPython, and to
116 116 'NoColor' otherwise.
117 117
118 118 Examples
119 119 --------
120 120 ::
121 121
122 122 from IPython.core.debugger import Tracer; debug_here = Tracer()
123 123
124 124 Later in your code::
125 125
126 126 debug_here() # -> will open up the debugger at that point.
127 127
128 128 Once the debugger activates, you can use all of its regular commands to
129 129 step through code, set breakpoints, etc. See the pdb documentation
130 130 from the Python standard library for usage details.
131 131 """
132 132 warnings.warn("`Tracer` is deprecated since version 5.1, directly use "
133 133 "`IPython.core.debugger.Pdb.set_trace()`",
134 134 DeprecationWarning, stacklevel=2)
135 135
136 136 ip = get_ipython()
137 137 if ip is None:
138 138 # Outside of ipython, we set our own exception hook manually
139 139 sys.excepthook = functools.partial(BdbQuit_excepthook,
140 140 excepthook=sys.excepthook)
141 141 def_colors = 'NoColor'
142 142 else:
143 143 # In ipython, we use its custom exception handler mechanism
144 144 def_colors = ip.colors
145 145 ip.set_custom_exc((bdb.BdbQuit,), BdbQuit_IPython_excepthook)
146 146
147 147 if colors is None:
148 148 colors = def_colors
149 149
150 150 # The stdlib debugger internally uses a modified repr from the `repr`
151 151 # module, that limits the length of printed strings to a hardcoded
152 152 # limit of 30 characters. That much trimming is too aggressive, let's
153 153 # at least raise that limit to 80 chars, which should be enough for
154 154 # most interactive uses.
155 155 try:
156 156 from reprlib import aRepr
157 157 aRepr.maxstring = 80
158 158 except:
159 159 # This is only a user-facing convenience, so any error we encounter
160 160 # here can be warned about but can be otherwise ignored. These
161 161 # printouts will tell us about problems if this API changes
162 162 import traceback
163 163 traceback.print_exc()
164 164
165 165 self.debugger = Pdb(colors)
166 166
167 167 def __call__(self):
168 168 """Starts an interactive debugger at the point where called.
169 169
170 170 This is similar to the pdb.set_trace() function from the std lib, but
171 171 using IPython's enhanced debugger."""
172 172
173 173 self.debugger.set_trace(sys._getframe().f_back)
174 174
175 175
176 176 RGX_EXTRA_INDENT = re.compile(r'(?<=\n)\s+')
177 177
178 178
179 179 def strip_indentation(multiline_string):
180 180 return RGX_EXTRA_INDENT.sub('', multiline_string)
181 181
182 182
183 183 def decorate_fn_with_doc(new_fn, old_fn, additional_text=""):
184 184 """Make new_fn have old_fn's doc string. This is particularly useful
185 185 for the ``do_...`` commands that hook into the help system.
186 186 Adapted from from a comp.lang.python posting
187 187 by Duncan Booth."""
188 188 def wrapper(*args, **kw):
189 189 return new_fn(*args, **kw)
190 190 if old_fn.__doc__:
191 191 wrapper.__doc__ = strip_indentation(old_fn.__doc__) + additional_text
192 192 return wrapper
193 193
194 194
195 195 class Pdb(OldPdb):
196 196 """Modified Pdb class, does not load readline.
197 197
198 198 for a standalone version that uses prompt_toolkit, see
199 199 `IPython.terminal.debugger.TerminalPdb` and
200 200 `IPython.terminal.debugger.set_trace()`
201 201 """
202 202
203 203 def __init__(self, color_scheme=None, completekey=None,
204 204 stdin=None, stdout=None, context=5, **kwargs):
205 205 """Create a new IPython debugger.
206 206
207 207 :param color_scheme: Deprecated, do not use.
208 208 :param completekey: Passed to pdb.Pdb.
209 209 :param stdin: Passed to pdb.Pdb.
210 210 :param stdout: Passed to pdb.Pdb.
211 211 :param context: Number of lines of source code context to show when
212 212 displaying stacktrace information.
213 213 :param kwargs: Passed to pdb.Pdb.
214 214 The possibilities are python version dependent, see the python
215 215 docs for more info.
216 216 """
217 217
218 218 # Parent constructor:
219 219 try:
220 220 self.context = int(context)
221 221 if self.context <= 0:
222 222 raise ValueError("Context must be a positive integer")
223 223 except (TypeError, ValueError) as e:
224 224 raise ValueError("Context must be a positive integer") from e
225 225
226 226 # `kwargs` ensures full compatibility with stdlib's `pdb.Pdb`.
227 227 OldPdb.__init__(self, completekey, stdin, stdout, **kwargs)
228 228
229 229 # IPython changes...
230 230 self.shell = get_ipython()
231 231
232 232 if self.shell is None:
233 233 save_main = sys.modules['__main__']
234 234 # No IPython instance running, we must create one
235 235 from IPython.terminal.interactiveshell import \
236 236 TerminalInteractiveShell
237 237 self.shell = TerminalInteractiveShell.instance()
238 238 # needed by any code which calls __import__("__main__") after
239 239 # the debugger was entered. See also #9941.
240 240 sys.modules['__main__'] = save_main
241 241
242 242 if color_scheme is not None:
243 243 warnings.warn(
244 244 "The `color_scheme` argument is deprecated since version 5.1",
245 245 DeprecationWarning, stacklevel=2)
246 246 else:
247 247 color_scheme = self.shell.colors
248 248
249 249 self.aliases = {}
250 250
251 251 # Create color table: we copy the default one from the traceback
252 252 # module and add a few attributes needed for debugging
253 253 self.color_scheme_table = exception_colors()
254 254
255 255 # shorthands
256 256 C = coloransi.TermColors
257 257 cst = self.color_scheme_table
258 258
259 259 cst['NoColor'].colors.prompt = C.NoColor
260 260 cst['NoColor'].colors.breakpoint_enabled = C.NoColor
261 261 cst['NoColor'].colors.breakpoint_disabled = C.NoColor
262 262
263 263 cst['Linux'].colors.prompt = C.Green
264 264 cst['Linux'].colors.breakpoint_enabled = C.LightRed
265 265 cst['Linux'].colors.breakpoint_disabled = C.Red
266 266
267 267 cst['LightBG'].colors.prompt = C.Blue
268 268 cst['LightBG'].colors.breakpoint_enabled = C.LightRed
269 269 cst['LightBG'].colors.breakpoint_disabled = C.Red
270 270
271 271 cst['Neutral'].colors.prompt = C.Blue
272 272 cst['Neutral'].colors.breakpoint_enabled = C.LightRed
273 273 cst['Neutral'].colors.breakpoint_disabled = C.Red
274 274
275 275
276 276 # Add a python parser so we can syntax highlight source while
277 277 # debugging.
278 278 self.parser = PyColorize.Parser(style=color_scheme)
279 279 self.set_colors(color_scheme)
280 280
281 281 # Set the prompt - the default prompt is '(Pdb)'
282 282 self.prompt = prompt
283 283 self.skip_hidden = True
284 284
285 285 def set_colors(self, scheme):
286 286 """Shorthand access to the color table scheme selector method."""
287 287 self.color_scheme_table.set_active_scheme(scheme)
288 288 self.parser.style = scheme
289 289
290 def set_trace(self, frame=None):
291 if frame is None:
292 frame = sys._getframe().f_back
293 self.initial_frame = frame
294 return super().set_trace(frame)
290 295
291 296 def hidden_frames(self, stack):
292 297 """
293 298 Given an index in the stack return whether it should be skipped.
294 299
295 300 This is used in up/down and where to skip frames.
296 301 """
297 302 # The f_locals dictionary is updated from the actual frame
298 303 # locals whenever the .f_locals accessor is called, so we
299 304 # avoid calling it here to preserve self.curframe_locals.
300 305 # Futhermore, there is no good reason to hide the current frame.
301 306 ip_hide = [
302 False if s[0] is self.curframe else s[0].f_locals.get(
303 "__tracebackhide__", False)
304 for s in stack]
307 False
308 if s[0] in (self.curframe, getattr(self, "initial_frame", None))
309 else s[0].f_locals.get("__tracebackhide__", False)
310 for s in stack
311 ]
305 312 ip_start = [i for i, s in enumerate(ip_hide) if s == "__ipython_bottom__"]
306 313 if ip_start:
307 314 ip_hide = [h if i > ip_start[0] else True for (i, h) in enumerate(ip_hide)]
308 315 return ip_hide
309 316
310 317 def interaction(self, frame, traceback):
311 318 try:
312 319 OldPdb.interaction(self, frame, traceback)
313 320 except KeyboardInterrupt:
314 321 self.stdout.write("\n" + self.shell.get_exception_only())
315 322
316 323 def new_do_frame(self, arg):
317 324 OldPdb.do_frame(self, arg)
318 325
319 326 def new_do_quit(self, arg):
320 327
321 328 if hasattr(self, 'old_all_completions'):
322 329 self.shell.Completer.all_completions=self.old_all_completions
323 330
324 331 return OldPdb.do_quit(self, arg)
325 332
326 333 do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit)
327 334
328 335 def new_do_restart(self, arg):
329 336 """Restart command. In the context of ipython this is exactly the same
330 337 thing as 'quit'."""
331 338 self.msg("Restart doesn't make sense here. Using 'quit' instead.")
332 339 return self.do_quit(arg)
333 340
334 341 def print_stack_trace(self, context=None):
335 342 Colors = self.color_scheme_table.active_colors
336 343 ColorsNormal = Colors.Normal
337 344 if context is None:
338 345 context = self.context
339 346 try:
340 347 context=int(context)
341 348 if context <= 0:
342 349 raise ValueError("Context must be a positive integer")
343 350 except (TypeError, ValueError) as e:
344 351 raise ValueError("Context must be a positive integer") from e
345 352 try:
346 353 skipped = 0
347 354 for hidden, frame_lineno in zip(self.hidden_frames(self.stack), self.stack):
348 355 if hidden and self.skip_hidden:
349 356 skipped += 1
350 357 continue
351 358 if skipped:
352 359 print(
353 360 f"{Colors.excName} [... skipping {skipped} hidden frame(s)]{ColorsNormal}\n"
354 361 )
355 362 skipped = 0
356 363 self.print_stack_entry(frame_lineno, context=context)
357 364 if skipped:
358 365 print(
359 366 f"{Colors.excName} [... skipping {skipped} hidden frame(s)]{ColorsNormal}\n"
360 367 )
361 368 except KeyboardInterrupt:
362 369 pass
363 370
364 371 def print_stack_entry(self, frame_lineno, prompt_prefix='\n-> ',
365 372 context=None):
366 373 if context is None:
367 374 context = self.context
368 375 try:
369 376 context=int(context)
370 377 if context <= 0:
371 378 raise ValueError("Context must be a positive integer")
372 379 except (TypeError, ValueError) as e:
373 380 raise ValueError("Context must be a positive integer") from e
374 381 print(self.format_stack_entry(frame_lineno, '', context), file=self.stdout)
375 382
376 383 # vds: >>
377 384 frame, lineno = frame_lineno
378 385 filename = frame.f_code.co_filename
379 386 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
380 387 # vds: <<
381 388
382 389 def format_stack_entry(self, frame_lineno, lprefix=': ', context=None):
383 390 if context is None:
384 391 context = self.context
385 392 try:
386 393 context=int(context)
387 394 if context <= 0:
388 395 print("Context must be a positive integer", file=self.stdout)
389 396 except (TypeError, ValueError):
390 397 print("Context must be a positive integer", file=self.stdout)
391 398
392 399 import reprlib
393 400
394 401 ret = []
395 402
396 403 Colors = self.color_scheme_table.active_colors
397 404 ColorsNormal = Colors.Normal
398 405 tpl_link = u'%s%%s%s' % (Colors.filenameEm, ColorsNormal)
399 406 tpl_call = u'%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal)
400 407 tpl_line = u'%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
401 408 tpl_line_em = u'%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line,
402 409 ColorsNormal)
403 410
404 411 frame, lineno = frame_lineno
405 412
406 413 return_value = ''
407 414 if '__return__' in frame.f_locals:
408 415 rv = frame.f_locals['__return__']
409 416 #return_value += '->'
410 417 return_value += reprlib.repr(rv) + '\n'
411 418 ret.append(return_value)
412 419
413 420 #s = filename + '(' + `lineno` + ')'
414 421 filename = self.canonic(frame.f_code.co_filename)
415 422 link = tpl_link % py3compat.cast_unicode(filename)
416 423
417 424 if frame.f_code.co_name:
418 425 func = frame.f_code.co_name
419 426 else:
420 427 func = "<lambda>"
421 428
422 429 call = ''
423 430 if func != '?':
424 431 if '__args__' in frame.f_locals:
425 432 args = reprlib.repr(frame.f_locals['__args__'])
426 433 else:
427 434 args = '()'
428 435 call = tpl_call % (func, args)
429 436
430 437 # The level info should be generated in the same format pdb uses, to
431 438 # avoid breaking the pdbtrack functionality of python-mode in *emacs.
432 439 if frame is self.curframe:
433 440 ret.append('> ')
434 441 else:
435 442 ret.append(' ')
436 443 ret.append(u'%s(%s)%s\n' % (link,lineno,call))
437 444
438 445 start = lineno - 1 - context//2
439 446 lines = linecache.getlines(filename)
440 447 start = min(start, len(lines) - context)
441 448 start = max(start, 0)
442 449 lines = lines[start : start + context]
443 450
444 451 for i,line in enumerate(lines):
445 452 show_arrow = (start + 1 + i == lineno)
446 453 linetpl = (frame is self.curframe or show_arrow) \
447 454 and tpl_line_em \
448 455 or tpl_line
449 456 ret.append(self.__format_line(linetpl, filename,
450 457 start + 1 + i, line,
451 458 arrow = show_arrow) )
452 459 return ''.join(ret)
453 460
454 461 def __format_line(self, tpl_line, filename, lineno, line, arrow = False):
455 462 bp_mark = ""
456 463 bp_mark_color = ""
457 464
458 465 new_line, err = self.parser.format2(line, 'str')
459 466 if not err:
460 467 line = new_line
461 468
462 469 bp = None
463 470 if lineno in self.get_file_breaks(filename):
464 471 bps = self.get_breaks(filename, lineno)
465 472 bp = bps[-1]
466 473
467 474 if bp:
468 475 Colors = self.color_scheme_table.active_colors
469 476 bp_mark = str(bp.number)
470 477 bp_mark_color = Colors.breakpoint_enabled
471 478 if not bp.enabled:
472 479 bp_mark_color = Colors.breakpoint_disabled
473 480
474 481 numbers_width = 7
475 482 if arrow:
476 483 # This is the line with the error
477 484 pad = numbers_width - len(str(lineno)) - len(bp_mark)
478 485 num = '%s%s' % (make_arrow(pad), str(lineno))
479 486 else:
480 487 num = '%*s' % (numbers_width - len(bp_mark), str(lineno))
481 488
482 489 return tpl_line % (bp_mark_color + bp_mark, num, line)
483 490
484 491
485 492 def print_list_lines(self, filename, first, last):
486 493 """The printing (as opposed to the parsing part of a 'list'
487 494 command."""
488 495 try:
489 496 Colors = self.color_scheme_table.active_colors
490 497 ColorsNormal = Colors.Normal
491 498 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
492 499 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal)
493 500 src = []
494 501 if filename == "<string>" and hasattr(self, "_exec_filename"):
495 502 filename = self._exec_filename
496 503
497 504 for lineno in range(first, last+1):
498 505 line = linecache.getline(filename, lineno)
499 506 if not line:
500 507 break
501 508
502 509 if lineno == self.curframe.f_lineno:
503 510 line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True)
504 511 else:
505 512 line = self.__format_line(tpl_line, filename, lineno, line, arrow = False)
506 513
507 514 src.append(line)
508 515 self.lineno = lineno
509 516
510 517 print(''.join(src), file=self.stdout)
511 518
512 519 except KeyboardInterrupt:
513 520 pass
514 521
515 522 def do_skip_hidden(self, arg):
516 523 """
517 524 Change whether or not we should skip frames with the
518 525 __tracebackhide__ attribute.
519 526 """
520 527 if arg.strip().lower() in ("true", "yes"):
521 528 self.skip_hidden = True
522 529 elif arg.strip().lower() in ("false", "no"):
523 530 self.skip_hidden = False
524 531
525 532 def do_list(self, arg):
526 533 """Print lines of code from the current stack frame
527 534 """
528 535 self.lastcmd = 'list'
529 536 last = None
530 537 if arg:
531 538 try:
532 539 x = eval(arg, {}, {})
533 540 if type(x) == type(()):
534 541 first, last = x
535 542 first = int(first)
536 543 last = int(last)
537 544 if last < first:
538 545 # Assume it's a count
539 546 last = first + last
540 547 else:
541 548 first = max(1, int(x) - 5)
542 549 except:
543 550 print('*** Error in argument:', repr(arg), file=self.stdout)
544 551 return
545 552 elif self.lineno is None:
546 553 first = max(1, self.curframe.f_lineno - 5)
547 554 else:
548 555 first = self.lineno + 1
549 556 if last is None:
550 557 last = first + 10
551 558 self.print_list_lines(self.curframe.f_code.co_filename, first, last)
552 559
553 560 # vds: >>
554 561 lineno = first
555 562 filename = self.curframe.f_code.co_filename
556 563 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
557 564 # vds: <<
558 565
559 566 do_l = do_list
560 567
561 568 def getsourcelines(self, obj):
562 569 lines, lineno = inspect.findsource(obj)
563 570 if inspect.isframe(obj) and obj.f_globals is obj.f_locals:
564 571 # must be a module frame: do not try to cut a block out of it
565 572 return lines, 1
566 573 elif inspect.ismodule(obj):
567 574 return lines, 1
568 575 return inspect.getblock(lines[lineno:]), lineno+1
569 576
570 577 def do_longlist(self, arg):
571 578 """Print lines of code from the current stack frame.
572 579
573 580 Shows more lines than 'list' does.
574 581 """
575 582 self.lastcmd = 'longlist'
576 583 try:
577 584 lines, lineno = self.getsourcelines(self.curframe)
578 585 except OSError as err:
579 586 self.error(err)
580 587 return
581 588 last = lineno + len(lines)
582 589 self.print_list_lines(self.curframe.f_code.co_filename, lineno, last)
583 590 do_ll = do_longlist
584 591
585 592 def do_debug(self, arg):
586 593 """debug code
587 594 Enter a recursive debugger that steps through the code
588 595 argument (which is an arbitrary expression or statement to be
589 596 executed in the current environment).
590 597 """
591 598 sys.settrace(None)
592 599 globals = self.curframe.f_globals
593 600 locals = self.curframe_locals
594 601 p = self.__class__(completekey=self.completekey,
595 602 stdin=self.stdin, stdout=self.stdout)
596 603 p.use_rawinput = self.use_rawinput
597 604 p.prompt = "(%s) " % self.prompt.strip()
598 605 self.message("ENTERING RECURSIVE DEBUGGER")
599 606 sys.call_tracing(p.run, (arg, globals, locals))
600 607 self.message("LEAVING RECURSIVE DEBUGGER")
601 608 sys.settrace(self.trace_dispatch)
602 609 self.lastcmd = p.lastcmd
603 610
604 611 def do_pdef(self, arg):
605 612 """Print the call signature for any callable object.
606 613
607 614 The debugger interface to %pdef"""
608 615 namespaces = [('Locals', self.curframe.f_locals),
609 616 ('Globals', self.curframe.f_globals)]
610 617 self.shell.find_line_magic('pdef')(arg, namespaces=namespaces)
611 618
612 619 def do_pdoc(self, arg):
613 620 """Print the docstring for an object.
614 621
615 622 The debugger interface to %pdoc."""
616 623 namespaces = [('Locals', self.curframe.f_locals),
617 624 ('Globals', self.curframe.f_globals)]
618 625 self.shell.find_line_magic('pdoc')(arg, namespaces=namespaces)
619 626
620 627 def do_pfile(self, arg):
621 628 """Print (or run through pager) the file where an object is defined.
622 629
623 630 The debugger interface to %pfile.
624 631 """
625 632 namespaces = [('Locals', self.curframe.f_locals),
626 633 ('Globals', self.curframe.f_globals)]
627 634 self.shell.find_line_magic('pfile')(arg, namespaces=namespaces)
628 635
629 636 def do_pinfo(self, arg):
630 637 """Provide detailed information about an object.
631 638
632 639 The debugger interface to %pinfo, i.e., obj?."""
633 640 namespaces = [('Locals', self.curframe.f_locals),
634 641 ('Globals', self.curframe.f_globals)]
635 642 self.shell.find_line_magic('pinfo')(arg, namespaces=namespaces)
636 643
637 644 def do_pinfo2(self, arg):
638 645 """Provide extra detailed information about an object.
639 646
640 647 The debugger interface to %pinfo2, i.e., obj??."""
641 648 namespaces = [('Locals', self.curframe.f_locals),
642 649 ('Globals', self.curframe.f_globals)]
643 650 self.shell.find_line_magic('pinfo2')(arg, namespaces=namespaces)
644 651
645 652 def do_psource(self, arg):
646 653 """Print (or run through pager) the source code for an object."""
647 654 namespaces = [('Locals', self.curframe.f_locals),
648 655 ('Globals', self.curframe.f_globals)]
649 656 self.shell.find_line_magic('psource')(arg, namespaces=namespaces)
650 657
651 658 def do_where(self, arg):
652 659 """w(here)
653 660 Print a stack trace, with the most recent frame at the bottom.
654 661 An arrow indicates the "current frame", which determines the
655 662 context of most commands. 'bt' is an alias for this command.
656 663
657 664 Take a number as argument as an (optional) number of context line to
658 665 print"""
659 666 if arg:
660 667 try:
661 668 context = int(arg)
662 669 except ValueError as err:
663 670 self.error(err)
664 671 return
665 672 self.print_stack_trace(context)
666 673 else:
667 674 self.print_stack_trace()
668 675
669 676 do_w = do_where
670 677
671 678 def stop_here(self, frame):
672 679 hidden = False
673 680 if self.skip_hidden:
674 681 hidden = frame.f_locals.get("__tracebackhide__", False)
675 682 if hidden:
676 683 Colors = self.color_scheme_table.active_colors
677 684 ColorsNormal = Colors.Normal
678 685 print(f"{Colors.excName} [... skipped 1 hidden frame]{ColorsNormal}\n")
679 686
680 687 return super().stop_here(frame)
681 688
682 689 def do_up(self, arg):
683 690 """u(p) [count]
684 691 Move the current frame count (default one) levels up in the
685 692 stack trace (to an older frame).
686 693
687 694 Will skip hidden frames.
688 695 """
689 696 ## modified version of upstream that skips
690 697 # frames with __tracebackide__
691 698 if self.curindex == 0:
692 699 self.error("Oldest frame")
693 700 return
694 701 try:
695 702 count = int(arg or 1)
696 703 except ValueError:
697 704 self.error("Invalid frame count (%s)" % arg)
698 705 return
699 706 skipped = 0
700 707 if count < 0:
701 708 _newframe = 0
702 709 else:
703 710 _newindex = self.curindex
704 711 counter = 0
705 712 hidden_frames = self.hidden_frames(self.stack)
706 713 for i in range(self.curindex - 1, -1, -1):
707 714 frame = self.stack[i][0]
708 715 if hidden_frames[i] and self.skip_hidden:
709 716 skipped += 1
710 717 continue
711 718 counter += 1
712 719 if counter >= count:
713 720 break
714 721 else:
715 722 # if no break occured.
716 723 self.error(
717 724 "all frames above hidden, use `skip_hidden False` to get get into those."
718 725 )
719 726 return
720 727
721 728 Colors = self.color_scheme_table.active_colors
722 729 ColorsNormal = Colors.Normal
723 730 _newframe = i
724 731 self._select_frame(_newframe)
725 732 if skipped:
726 733 print(
727 734 f"{Colors.excName} [... skipped {skipped} hidden frame(s)]{ColorsNormal}\n"
728 735 )
729 736
730 737 def do_down(self, arg):
731 738 """d(own) [count]
732 739 Move the current frame count (default one) levels down in the
733 740 stack trace (to a newer frame).
734 741
735 742 Will skip hidden frames.
736 743 """
737 744 if self.curindex + 1 == len(self.stack):
738 745 self.error("Newest frame")
739 746 return
740 747 try:
741 748 count = int(arg or 1)
742 749 except ValueError:
743 750 self.error("Invalid frame count (%s)" % arg)
744 751 return
745 752 if count < 0:
746 753 _newframe = len(self.stack) - 1
747 754 else:
748 755 _newindex = self.curindex
749 756 counter = 0
750 757 skipped = 0
751 758 hidden_frames = self.hidden_frames(self.stack)
752 759 for i in range(self.curindex + 1, len(self.stack)):
753 760 frame = self.stack[i][0]
754 761 if hidden_frames[i] and self.skip_hidden:
755 762 skipped += 1
756 763 continue
757 764 counter += 1
758 765 if counter >= count:
759 766 break
760 767 else:
761 768 self.error(
762 769 "all frames bellow hidden, use `skip_hidden False` to get get into those."
763 770 )
764 771 return
765 772
766 773 Colors = self.color_scheme_table.active_colors
767 774 ColorsNormal = Colors.Normal
768 775 if skipped:
769 776 print(
770 777 f"{Colors.excName} [... skipped {skipped} hidden frame(s)]{ColorsNormal}\n"
771 778 )
772 779 _newframe = i
773 780
774 781 self._select_frame(_newframe)
775 782
776 783 do_d = do_down
777 784 do_u = do_up
778 785
779 786 class InterruptiblePdb(Pdb):
780 787 """Version of debugger where KeyboardInterrupt exits the debugger altogether."""
781 788
782 789 def cmdloop(self):
783 790 """Wrap cmdloop() such that KeyboardInterrupt stops the debugger."""
784 791 try:
785 792 return OldPdb.cmdloop(self)
786 793 except KeyboardInterrupt:
787 794 self.stop_here = lambda frame: False
788 795 self.do_quit("")
789 796 sys.settrace(None)
790 797 self.quitting = False
791 798 raise
792 799
793 800 def _cmdloop(self):
794 801 while True:
795 802 try:
796 803 # keyboard interrupts allow for an easy way to cancel
797 804 # the current command, so allow them during interactive input
798 805 self.allow_kbdint = True
799 806 self.cmdloop()
800 807 self.allow_kbdint = False
801 808 break
802 809 except KeyboardInterrupt:
803 810 self.message('--KeyboardInterrupt--')
804 811 raise
805 812
806 813
807 814 def set_trace(frame=None):
808 815 """
809 816 Start debugging from `frame`.
810 817
811 818 If frame is not specified, debugging starts from caller's frame.
812 819 """
813 820 Pdb().set_trace(frame or sys._getframe().f_back)
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
General Comments 0
You need to be logged in to leave comments. Login now