##// END OF EJS Templates
A maybe better-working interruptible Pdb. Also make separate class so we don't...
Itamar Turner-Trauring -
Show More
@@ -1,650 +1,665 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
284 284 def set_colors(self, scheme):
285 285 """Shorthand access to the color table scheme selector method."""
286 286 self.color_scheme_table.set_active_scheme(scheme)
287 287 self.parser.style = scheme
288 288
289 289 def interaction(self, frame, traceback):
290 290 try:
291 291 OldPdb.interaction(self, frame, traceback)
292 292 except KeyboardInterrupt:
293 raise
293 self.stdout.write('\n' + self.shell.get_exception_only())
294 294
295 295 def new_do_up(self, arg):
296 296 OldPdb.do_up(self, arg)
297 297 do_u = do_up = decorate_fn_with_doc(new_do_up, OldPdb.do_up)
298 298
299 299 def new_do_down(self, arg):
300 300 OldPdb.do_down(self, arg)
301 301
302 302 do_d = do_down = decorate_fn_with_doc(new_do_down, OldPdb.do_down)
303 303
304 304 def new_do_frame(self, arg):
305 305 OldPdb.do_frame(self, arg)
306 306
307 307 def new_do_quit(self, arg):
308 308
309 309 if hasattr(self, 'old_all_completions'):
310 310 self.shell.Completer.all_completions=self.old_all_completions
311 311
312 312 return OldPdb.do_quit(self, arg)
313 313
314 314 do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit)
315 315
316 316 def new_do_restart(self, arg):
317 317 """Restart command. In the context of ipython this is exactly the same
318 318 thing as 'quit'."""
319 319 self.msg("Restart doesn't make sense here. Using 'quit' instead.")
320 320 return self.do_quit(arg)
321 321
322 322 def print_stack_trace(self, context=None):
323 323 if context is None:
324 324 context = self.context
325 325 try:
326 326 context=int(context)
327 327 if context <= 0:
328 328 raise ValueError("Context must be a positive integer")
329 329 except (TypeError, ValueError):
330 330 raise ValueError("Context must be a positive integer")
331 331 try:
332 332 for frame_lineno in self.stack:
333 333 self.print_stack_entry(frame_lineno, context=context)
334 334 except KeyboardInterrupt:
335 335 pass
336 336
337 337 def print_stack_entry(self, frame_lineno, prompt_prefix='\n-> ',
338 338 context=None):
339 339 if context is None:
340 340 context = self.context
341 341 try:
342 342 context=int(context)
343 343 if context <= 0:
344 344 raise ValueError("Context must be a positive integer")
345 345 except (TypeError, ValueError):
346 346 raise ValueError("Context must be a positive integer")
347 347 print(self.format_stack_entry(frame_lineno, '', context), file=self.stdout)
348 348
349 349 # vds: >>
350 350 frame, lineno = frame_lineno
351 351 filename = frame.f_code.co_filename
352 352 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
353 353 # vds: <<
354 354
355 355 def format_stack_entry(self, frame_lineno, lprefix=': ', context=None):
356 356 if context is None:
357 357 context = self.context
358 358 try:
359 359 context=int(context)
360 360 if context <= 0:
361 361 print("Context must be a positive integer", file=self.stdout)
362 362 except (TypeError, ValueError):
363 363 print("Context must be a positive integer", file=self.stdout)
364 364
365 365 import reprlib
366 366
367 367 ret = []
368 368
369 369 Colors = self.color_scheme_table.active_colors
370 370 ColorsNormal = Colors.Normal
371 371 tpl_link = u'%s%%s%s' % (Colors.filenameEm, ColorsNormal)
372 372 tpl_call = u'%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal)
373 373 tpl_line = u'%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
374 374 tpl_line_em = u'%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line,
375 375 ColorsNormal)
376 376
377 377 frame, lineno = frame_lineno
378 378
379 379 return_value = ''
380 380 if '__return__' in frame.f_locals:
381 381 rv = frame.f_locals['__return__']
382 382 #return_value += '->'
383 383 return_value += reprlib.repr(rv) + '\n'
384 384 ret.append(return_value)
385 385
386 386 #s = filename + '(' + `lineno` + ')'
387 387 filename = self.canonic(frame.f_code.co_filename)
388 388 link = tpl_link % py3compat.cast_unicode(filename)
389 389
390 390 if frame.f_code.co_name:
391 391 func = frame.f_code.co_name
392 392 else:
393 393 func = "<lambda>"
394 394
395 395 call = ''
396 396 if func != '?':
397 397 if '__args__' in frame.f_locals:
398 398 args = reprlib.repr(frame.f_locals['__args__'])
399 399 else:
400 400 args = '()'
401 401 call = tpl_call % (func, args)
402 402
403 403 # The level info should be generated in the same format pdb uses, to
404 404 # avoid breaking the pdbtrack functionality of python-mode in *emacs.
405 405 if frame is self.curframe:
406 406 ret.append('> ')
407 407 else:
408 408 ret.append(' ')
409 409 ret.append(u'%s(%s)%s\n' % (link,lineno,call))
410 410
411 411 start = lineno - 1 - context//2
412 412 lines = linecache.getlines(filename)
413 413 start = min(start, len(lines) - context)
414 414 start = max(start, 0)
415 415 lines = lines[start : start + context]
416 416
417 417 for i,line in enumerate(lines):
418 418 show_arrow = (start + 1 + i == lineno)
419 419 linetpl = (frame is self.curframe or show_arrow) \
420 420 and tpl_line_em \
421 421 or tpl_line
422 422 ret.append(self.__format_line(linetpl, filename,
423 423 start + 1 + i, line,
424 424 arrow = show_arrow) )
425 425 return ''.join(ret)
426 426
427 427 def __format_line(self, tpl_line, filename, lineno, line, arrow = False):
428 428 bp_mark = ""
429 429 bp_mark_color = ""
430 430
431 431 new_line, err = self.parser.format2(line, 'str')
432 432 if not err:
433 433 line = new_line
434 434
435 435 bp = None
436 436 if lineno in self.get_file_breaks(filename):
437 437 bps = self.get_breaks(filename, lineno)
438 438 bp = bps[-1]
439 439
440 440 if bp:
441 441 Colors = self.color_scheme_table.active_colors
442 442 bp_mark = str(bp.number)
443 443 bp_mark_color = Colors.breakpoint_enabled
444 444 if not bp.enabled:
445 445 bp_mark_color = Colors.breakpoint_disabled
446 446
447 447 numbers_width = 7
448 448 if arrow:
449 449 # This is the line with the error
450 450 pad = numbers_width - len(str(lineno)) - len(bp_mark)
451 451 num = '%s%s' % (make_arrow(pad), str(lineno))
452 452 else:
453 453 num = '%*s' % (numbers_width - len(bp_mark), str(lineno))
454 454
455 455 return tpl_line % (bp_mark_color + bp_mark, num, line)
456 456
457 457
458 458 def print_list_lines(self, filename, first, last):
459 459 """The printing (as opposed to the parsing part of a 'list'
460 460 command."""
461 461 try:
462 462 Colors = self.color_scheme_table.active_colors
463 463 ColorsNormal = Colors.Normal
464 464 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
465 465 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal)
466 466 src = []
467 467 if filename == "<string>" and hasattr(self, "_exec_filename"):
468 468 filename = self._exec_filename
469 469
470 470 for lineno in range(first, last+1):
471 471 line = linecache.getline(filename, lineno)
472 472 if not line:
473 473 break
474 474
475 475 if lineno == self.curframe.f_lineno:
476 476 line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True)
477 477 else:
478 478 line = self.__format_line(tpl_line, filename, lineno, line, arrow = False)
479 479
480 480 src.append(line)
481 481 self.lineno = lineno
482 482
483 483 print(''.join(src), file=self.stdout)
484 484
485 485 except KeyboardInterrupt:
486 486 pass
487 487
488 488 def do_list(self, arg):
489 489 """Print lines of code from the current stack frame
490 490 """
491 491 self.lastcmd = 'list'
492 492 last = None
493 493 if arg:
494 494 try:
495 495 x = eval(arg, {}, {})
496 496 if type(x) == type(()):
497 497 first, last = x
498 498 first = int(first)
499 499 last = int(last)
500 500 if last < first:
501 501 # Assume it's a count
502 502 last = first + last
503 503 else:
504 504 first = max(1, int(x) - 5)
505 505 except:
506 506 print('*** Error in argument:', repr(arg), file=self.stdout)
507 507 return
508 508 elif self.lineno is None:
509 509 first = max(1, self.curframe.f_lineno - 5)
510 510 else:
511 511 first = self.lineno + 1
512 512 if last is None:
513 513 last = first + 10
514 514 self.print_list_lines(self.curframe.f_code.co_filename, first, last)
515 515
516 516 # vds: >>
517 517 lineno = first
518 518 filename = self.curframe.f_code.co_filename
519 519 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
520 520 # vds: <<
521 521
522 522 do_l = do_list
523 523
524 524 def getsourcelines(self, obj):
525 525 lines, lineno = inspect.findsource(obj)
526 526 if inspect.isframe(obj) and obj.f_globals is obj.f_locals:
527 527 # must be a module frame: do not try to cut a block out of it
528 528 return lines, 1
529 529 elif inspect.ismodule(obj):
530 530 return lines, 1
531 531 return inspect.getblock(lines[lineno:]), lineno+1
532 532
533 533 def do_longlist(self, arg):
534 534 """Print lines of code from the current stack frame.
535 535
536 536 Shows more lines than 'list' does.
537 537 """
538 538 self.lastcmd = 'longlist'
539 539 try:
540 540 lines, lineno = self.getsourcelines(self.curframe)
541 541 except OSError as err:
542 542 self.error(err)
543 543 return
544 544 last = lineno + len(lines)
545 545 self.print_list_lines(self.curframe.f_code.co_filename, lineno, last)
546 546 do_ll = do_longlist
547 547
548 548 def do_debug(self, arg):
549 549 """debug code
550 550 Enter a recursive debugger that steps through the code
551 551 argument (which is an arbitrary expression or statement to be
552 552 executed in the current environment).
553 553 """
554 554 sys.settrace(None)
555 555 globals = self.curframe.f_globals
556 556 locals = self.curframe_locals
557 557 p = self.__class__(completekey=self.completekey,
558 558 stdin=self.stdin, stdout=self.stdout)
559 559 p.use_rawinput = self.use_rawinput
560 560 p.prompt = "(%s) " % self.prompt.strip()
561 561 self.message("ENTERING RECURSIVE DEBUGGER")
562 562 sys.call_tracing(p.run, (arg, globals, locals))
563 563 self.message("LEAVING RECURSIVE DEBUGGER")
564 564 sys.settrace(self.trace_dispatch)
565 565 self.lastcmd = p.lastcmd
566 566
567 567 def do_pdef(self, arg):
568 568 """Print the call signature for any callable object.
569 569
570 570 The debugger interface to %pdef"""
571 571 namespaces = [('Locals', self.curframe.f_locals),
572 572 ('Globals', self.curframe.f_globals)]
573 573 self.shell.find_line_magic('pdef')(arg, namespaces=namespaces)
574 574
575 575 def do_pdoc(self, arg):
576 576 """Print the docstring for an object.
577 577
578 578 The debugger interface to %pdoc."""
579 579 namespaces = [('Locals', self.curframe.f_locals),
580 580 ('Globals', self.curframe.f_globals)]
581 581 self.shell.find_line_magic('pdoc')(arg, namespaces=namespaces)
582 582
583 583 def do_pfile(self, arg):
584 584 """Print (or run through pager) the file where an object is defined.
585 585
586 586 The debugger interface to %pfile.
587 587 """
588 588 namespaces = [('Locals', self.curframe.f_locals),
589 589 ('Globals', self.curframe.f_globals)]
590 590 self.shell.find_line_magic('pfile')(arg, namespaces=namespaces)
591 591
592 592 def do_pinfo(self, arg):
593 593 """Provide detailed information about an object.
594 594
595 595 The debugger interface to %pinfo, i.e., obj?."""
596 596 namespaces = [('Locals', self.curframe.f_locals),
597 597 ('Globals', self.curframe.f_globals)]
598 598 self.shell.find_line_magic('pinfo')(arg, namespaces=namespaces)
599 599
600 600 def do_pinfo2(self, arg):
601 601 """Provide extra detailed information about an object.
602 602
603 603 The debugger interface to %pinfo2, i.e., obj??."""
604 604 namespaces = [('Locals', self.curframe.f_locals),
605 605 ('Globals', self.curframe.f_globals)]
606 606 self.shell.find_line_magic('pinfo2')(arg, namespaces=namespaces)
607 607
608 608 def do_psource(self, arg):
609 609 """Print (or run through pager) the source code for an object."""
610 610 namespaces = [('Locals', self.curframe.f_locals),
611 611 ('Globals', self.curframe.f_globals)]
612 612 self.shell.find_line_magic('psource')(arg, namespaces=namespaces)
613 613
614 614 def do_where(self, arg):
615 615 """w(here)
616 616 Print a stack trace, with the most recent frame at the bottom.
617 617 An arrow indicates the "current frame", which determines the
618 618 context of most commands. 'bt' is an alias for this command.
619 619
620 620 Take a number as argument as an (optional) number of context line to
621 621 print"""
622 622 if arg:
623 623 context = int(arg)
624 624 self.print_stack_trace(context)
625 625 else:
626 626 self.print_stack_trace()
627 627
628 628 do_w = do_where
629 629
630
631 class InterruptiblePdb(Pdb):
632 """Version of debugger where KeyboardInterrupt exits the debugger altogether."""
633
634 def cmdloop(self):
635 """Wrap cmdloop() such that KeyboardInterrupt stops the debugger."""
636 try:
637 return OldPdb.cmdloop(self)
638 except KeyboardInterrupt:
639 self.stop_here = lambda frame: False
640 self.do_quit("")
641 sys.settrace(None)
642 self.quitting = False
643 raise
644
630 645 def _cmdloop(self):
631 # Variant that doesn't catch KeyboardInterrupts.
632 646 while True:
633 647 try:
634 648 # keyboard interrupts allow for an easy way to cancel
635 649 # the current command, so allow them during interactive input
636 650 self.allow_kbdint = True
637 651 self.cmdloop()
638 652 self.allow_kbdint = False
639 653 break
640 654 except KeyboardInterrupt:
655 self.message('--KeyboardInterrupt--')
641 656 raise
642 657
643 658
644 659 def set_trace(frame=None):
645 660 """
646 661 Start debugging from `frame`.
647 662
648 663 If frame is not specified, debugging starts from caller's frame.
649 664 """
650 665 Pdb().set_trace(frame or sys._getframe().f_back)
@@ -1,248 +1,253 b''
1 1 """Tests for debugging machinery.
2 2 """
3 3
4 4 # Copyright (c) IPython Development Team.
5 5 # Distributed under the terms of the Modified BSD License.
6 6
7 7 import signal
8 8 import sys
9 9 import time
10 10 import warnings
11 11 from tempfile import NamedTemporaryFile
12 12 from subprocess import check_output, CalledProcessError, PIPE
13 13 import subprocess
14 14 from unittest.mock import patch
15 15 import builtins
16 import bdb
16 17
17 18 import nose.tools as nt
18 19
19 20 from IPython.core import debugger
20 21
21 22 #-----------------------------------------------------------------------------
22 23 # Helper classes, from CPython's Pdb test suite
23 24 #-----------------------------------------------------------------------------
24 25
25 26 class _FakeInput(object):
26 27 """
27 28 A fake input stream for pdb's interactive debugger. Whenever a
28 29 line is read, print it (to simulate the user typing it), and then
29 30 return it. The set of lines to return is specified in the
30 31 constructor; they should not have trailing newlines.
31 32 """
32 33 def __init__(self, lines):
33 34 self.lines = iter(lines)
34 35
35 36 def readline(self):
36 37 line = next(self.lines)
37 38 print(line)
38 39 return line+'\n'
39 40
40 41 class PdbTestInput(object):
41 42 """Context manager that makes testing Pdb in doctests easier."""
42 43
43 44 def __init__(self, input):
44 45 self.input = input
45 46
46 47 def __enter__(self):
47 48 self.real_stdin = sys.stdin
48 49 sys.stdin = _FakeInput(self.input)
49 50
50 51 def __exit__(self, *exc):
51 52 sys.stdin = self.real_stdin
52 53
53 54 #-----------------------------------------------------------------------------
54 55 # Tests
55 56 #-----------------------------------------------------------------------------
56 57
57 58 def test_longer_repr():
58 59 from reprlib import repr as trepr
59 60
60 61 a = '1234567890'* 7
61 62 ar = "'1234567890123456789012345678901234567890123456789012345678901234567890'"
62 63 a_trunc = "'123456789012...8901234567890'"
63 64 nt.assert_equal(trepr(a), a_trunc)
64 65 # The creation of our tracer modifies the repr module's repr function
65 66 # in-place, since that global is used directly by the stdlib's pdb module.
66 67 with warnings.catch_warnings():
67 68 warnings.simplefilter('ignore', DeprecationWarning)
68 69 debugger.Tracer()
69 70 nt.assert_equal(trepr(a), ar)
70 71
71 72 def test_ipdb_magics():
72 73 '''Test calling some IPython magics from ipdb.
73 74
74 75 First, set up some test functions and classes which we can inspect.
75 76
76 77 >>> class ExampleClass(object):
77 78 ... """Docstring for ExampleClass."""
78 79 ... def __init__(self):
79 80 ... """Docstring for ExampleClass.__init__"""
80 81 ... pass
81 82 ... def __str__(self):
82 83 ... return "ExampleClass()"
83 84
84 85 >>> def example_function(x, y, z="hello"):
85 86 ... """Docstring for example_function."""
86 87 ... pass
87 88
88 89 >>> old_trace = sys.gettrace()
89 90
90 91 Create a function which triggers ipdb.
91 92
92 93 >>> def trigger_ipdb():
93 94 ... a = ExampleClass()
94 95 ... debugger.Pdb().set_trace()
95 96
96 97 >>> with PdbTestInput([
97 98 ... 'pdef example_function',
98 99 ... 'pdoc ExampleClass',
99 100 ... 'up',
100 101 ... 'down',
101 102 ... 'list',
102 103 ... 'pinfo a',
103 104 ... 'll',
104 105 ... 'continue',
105 106 ... ]):
106 107 ... trigger_ipdb()
107 108 --Return--
108 109 None
109 110 > <doctest ...>(3)trigger_ipdb()
110 111 1 def trigger_ipdb():
111 112 2 a = ExampleClass()
112 113 ----> 3 debugger.Pdb().set_trace()
113 114 <BLANKLINE>
114 115 ipdb> pdef example_function
115 116 example_function(x, y, z='hello')
116 117 ipdb> pdoc ExampleClass
117 118 Class docstring:
118 119 Docstring for ExampleClass.
119 120 Init docstring:
120 121 Docstring for ExampleClass.__init__
121 122 ipdb> up
122 123 > <doctest ...>(11)<module>()
123 124 7 'pinfo a',
124 125 8 'll',
125 126 9 'continue',
126 127 10 ]):
127 128 ---> 11 trigger_ipdb()
128 129 <BLANKLINE>
129 130 ipdb> down
130 131 None
131 132 > <doctest ...>(3)trigger_ipdb()
132 133 1 def trigger_ipdb():
133 134 2 a = ExampleClass()
134 135 ----> 3 debugger.Pdb().set_trace()
135 136 <BLANKLINE>
136 137 ipdb> list
137 138 1 def trigger_ipdb():
138 139 2 a = ExampleClass()
139 140 ----> 3 debugger.Pdb().set_trace()
140 141 <BLANKLINE>
141 142 ipdb> pinfo a
142 143 Type: ExampleClass
143 144 String form: ExampleClass()
144 145 Namespace: Local...
145 146 Docstring: Docstring for ExampleClass.
146 147 Init docstring: Docstring for ExampleClass.__init__
147 148 ipdb> ll
148 149 1 def trigger_ipdb():
149 150 2 a = ExampleClass()
150 151 ----> 3 debugger.Pdb().set_trace()
151 152 <BLANKLINE>
152 153 ipdb> continue
153 154
154 155 Restore previous trace function, e.g. for coverage.py
155 156
156 157 >>> sys.settrace(old_trace)
157 158 '''
158 159
159 160 def test_ipdb_magics2():
160 161 '''Test ipdb with a very short function.
161 162
162 163 >>> old_trace = sys.gettrace()
163 164
164 165 >>> def bar():
165 166 ... pass
166 167
167 168 Run ipdb.
168 169
169 170 >>> with PdbTestInput([
170 171 ... 'continue',
171 172 ... ]):
172 173 ... debugger.Pdb().runcall(bar)
173 174 > <doctest ...>(2)bar()
174 175 1 def bar():
175 176 ----> 2 pass
176 177 <BLANKLINE>
177 178 ipdb> continue
178 179
179 180 Restore previous trace function, e.g. for coverage.py
180 181
181 182 >>> sys.settrace(old_trace)
182 183 '''
183 184
184 185 def can_quit():
185 186 '''Test that quit work in ipydb
186 187
187 188 >>> old_trace = sys.gettrace()
188 189
189 190 >>> def bar():
190 191 ... pass
191 192
192 193 >>> with PdbTestInput([
193 194 ... 'quit',
194 195 ... ]):
195 196 ... debugger.Pdb().runcall(bar)
196 197 > <doctest ...>(2)bar()
197 198 1 def bar():
198 199 ----> 2 pass
199 200 <BLANKLINE>
200 201 ipdb> quit
201 202
202 203 Restore previous trace function, e.g. for coverage.py
203 204
204 205 >>> sys.settrace(old_trace)
205 206 '''
206 207
207 208
208 209 def can_exit():
209 210 '''Test that quit work in ipydb
210 211
211 212 >>> old_trace = sys.gettrace()
212 213
213 214 >>> def bar():
214 215 ... pass
215 216
216 217 >>> with PdbTestInput([
217 218 ... 'exit',
218 219 ... ]):
219 220 ... debugger.Pdb().runcall(bar)
220 221 > <doctest ...>(2)bar()
221 222 1 def bar():
222 223 ----> 2 pass
223 224 <BLANKLINE>
224 225 ipdb> exit
225 226
226 227 Restore previous trace function, e.g. for coverage.py
227 228
228 229 >>> sys.settrace(old_trace)
229 230 '''
230 231
231 232
232 233 def test_interruptible_core_debugger():
233 234 """The debugger can be interrupted.
234 235
235 236 The presumption is there is some mechanism that causes a KeyboardInterrupt
236 237 (this is implemented in ipykernel). We want to ensure the
237 238 KeyboardInterrupt cause debugging to cease.
238 239 """
239 def raising_input(msg=""):
240 raise KeyboardInterrupt()
240 def raising_input(msg="", called=[0]):
241 called[0] += 1
242 if called[0] == 1:
243 raise KeyboardInterrupt()
244 else:
245 raise AssertionError("input() should only be called once!")
241 246
242 247 with patch.object(builtins, "input", raising_input):
243 debugger.set_trace()
248 debugger.InterruptiblePdb().set_trace()
244 249 # The way this test will fail is by set_trace() never exiting,
245 250 # resulting in a timeout by the test runner. The alternative
246 251 # implementation would involve a subprocess, but that adds issues with
247 252 # interrupting subprocesses that are rather complex, so it's simpler
248 253 # just to do it this way.
General Comments 0
You need to be logged in to leave comments. Login now