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