update pydoc topics
[python/dscho.git] / Lib / pdb.py
blob23bc6dfa16b7a2e43d1919e0e5c983a57210140a
1 #! /usr/bin/env python
3 """A Python debugger."""
5 # (See pdb.doc for documentation.)
7 import sys
8 import linecache
9 import cmd
10 import bdb
11 from reprlib import Repr
12 import os
13 import re
14 import pprint
15 import traceback
18 class Restart(Exception):
19 """Causes a debugger to be restarted for the debugged python program."""
20 pass
22 # Create a custom safe Repr instance and increase its maxstring.
23 # The default of 30 truncates error messages too easily.
24 _repr = Repr()
25 _repr.maxstring = 200
26 _saferepr = _repr.repr
28 __all__ = ["run", "pm", "Pdb", "runeval", "runctx", "runcall", "set_trace",
29 "post_mortem", "help"]
31 def find_function(funcname, filename):
32 cre = re.compile(r'def\s+%s\s*[(]' % re.escape(funcname))
33 try:
34 fp = open(filename)
35 except IOError:
36 return None
37 # consumer of this info expects the first line to be 1
38 lineno = 1
39 answer = None
40 while 1:
41 line = fp.readline()
42 if line == '':
43 break
44 if cre.match(line):
45 answer = funcname, filename, lineno
46 break
47 lineno = lineno + 1
48 fp.close()
49 return answer
52 # Interaction prompt line will separate file and call info from code
53 # text using value of line_prefix string. A newline and arrow may
54 # be to your liking. You can set it once pdb is imported using the
55 # command "pdb.line_prefix = '\n% '".
56 # line_prefix = ': ' # Use this to get the old situation back
57 line_prefix = '\n-> ' # Probably a better default
59 class Pdb(bdb.Bdb, cmd.Cmd):
61 def __init__(self, completekey='tab', stdin=None, stdout=None, skip=None):
62 bdb.Bdb.__init__(self, skip=skip)
63 cmd.Cmd.__init__(self, completekey, stdin, stdout)
64 if stdout:
65 self.use_rawinput = 0
66 self.prompt = '(Pdb) '
67 self.aliases = {}
68 self.mainpyfile = ''
69 self._wait_for_mainpyfile = 0
70 # Try to load readline if it exists
71 try:
72 import readline
73 except ImportError:
74 pass
76 # Read $HOME/.pdbrc and ./.pdbrc
77 self.rcLines = []
78 if 'HOME' in os.environ:
79 envHome = os.environ['HOME']
80 try:
81 rcFile = open(os.path.join(envHome, ".pdbrc"))
82 except IOError:
83 pass
84 else:
85 for line in rcFile.readlines():
86 self.rcLines.append(line)
87 rcFile.close()
88 try:
89 rcFile = open(".pdbrc")
90 except IOError:
91 pass
92 else:
93 for line in rcFile.readlines():
94 self.rcLines.append(line)
95 rcFile.close()
97 self.commands = {} # associates a command list to breakpoint numbers
98 self.commands_doprompt = {} # for each bp num, tells if the prompt
99 # must be disp. after execing the cmd list
100 self.commands_silent = {} # for each bp num, tells if the stack trace
101 # must be disp. after execing the cmd list
102 self.commands_defining = False # True while in the process of defining
103 # a command list
104 self.commands_bnum = None # The breakpoint number for which we are
105 # defining a list
107 def reset(self):
108 bdb.Bdb.reset(self)
109 self.forget()
111 def forget(self):
112 self.lineno = None
113 self.stack = []
114 self.curindex = 0
115 self.curframe = None
117 def setup(self, f, t):
118 self.forget()
119 self.stack, self.curindex = self.get_stack(f, t)
120 self.curframe = self.stack[self.curindex][0]
121 # The f_locals dictionary is updated from the actual frame
122 # locals whenever the .f_locals accessor is called, so we
123 # cache it here to ensure that modifications are not overwritten.
124 self.curframe_locals = self.curframe.f_locals
125 self.execRcLines()
127 # Can be executed earlier than 'setup' if desired
128 def execRcLines(self):
129 if self.rcLines:
130 # Make local copy because of recursion
131 rcLines = self.rcLines
132 # executed only once
133 self.rcLines = []
134 for line in rcLines:
135 line = line[:-1]
136 if len(line) > 0 and line[0] != '#':
137 self.onecmd(line)
139 # Override Bdb methods
141 def user_call(self, frame, argument_list):
142 """This method is called when there is the remote possibility
143 that we ever need to stop in this function."""
144 if self._wait_for_mainpyfile:
145 return
146 if self.stop_here(frame):
147 print('--Call--', file=self.stdout)
148 self.interaction(frame, None)
150 def user_line(self, frame):
151 """This function is called when we stop or break at this line."""
152 if self._wait_for_mainpyfile:
153 if (self.mainpyfile != self.canonic(frame.f_code.co_filename)
154 or frame.f_lineno<= 0):
155 return
156 self._wait_for_mainpyfile = 0
157 if self.bp_commands(frame):
158 self.interaction(frame, None)
160 def bp_commands(self,frame):
161 """Call every command that was set for the current active breakpoint
162 (if there is one).
164 Returns True if the normal interaction function must be called,
165 False otherwise."""
166 # self.currentbp is set in bdb in Bdb.break_here if a breakpoint was hit
167 if getattr(self, "currentbp", False) and \
168 self.currentbp in self.commands:
169 currentbp = self.currentbp
170 self.currentbp = 0
171 lastcmd_back = self.lastcmd
172 self.setup(frame, None)
173 for line in self.commands[currentbp]:
174 self.onecmd(line)
175 self.lastcmd = lastcmd_back
176 if not self.commands_silent[currentbp]:
177 self.print_stack_entry(self.stack[self.curindex])
178 if self.commands_doprompt[currentbp]:
179 self.cmdloop()
180 self.forget()
181 return
182 return 1
184 def user_return(self, frame, return_value):
185 """This function is called when a return trap is set here."""
186 frame.f_locals['__return__'] = return_value
187 print('--Return--', file=self.stdout)
188 self.interaction(frame, None)
190 def user_exception(self, frame, exc_info):
191 """This function is called if an exception occurs,
192 but only if we are to stop at or just below this level."""
193 exc_type, exc_value, exc_traceback = exc_info
194 frame.f_locals['__exception__'] = exc_type, exc_value
195 exc_type_name = exc_type.__name__
196 print(exc_type_name + ':', _saferepr(exc_value), file=self.stdout)
197 self.interaction(frame, exc_traceback)
199 # General interaction function
201 def interaction(self, frame, traceback):
202 self.setup(frame, traceback)
203 self.print_stack_entry(self.stack[self.curindex])
204 self.cmdloop()
205 self.forget()
207 def displayhook(self, obj):
208 """Custom displayhook for the exec in default(), which prevents
209 assignment of the _ variable in the builtins.
211 print(repr(obj))
213 def default(self, line):
214 if line[:1] == '!': line = line[1:]
215 locals = self.curframe_locals
216 globals = self.curframe.f_globals
217 try:
218 code = compile(line + '\n', '<stdin>', 'single')
219 save_stdout = sys.stdout
220 save_stdin = sys.stdin
221 save_displayhook = sys.displayhook
222 try:
223 sys.stdin = self.stdin
224 sys.stdout = self.stdout
225 sys.displayhook = self.displayhook
226 exec(code, globals, locals)
227 finally:
228 sys.stdout = save_stdout
229 sys.stdin = save_stdin
230 sys.displayhook = save_displayhook
231 except:
232 t, v = sys.exc_info()[:2]
233 if type(t) == type(''):
234 exc_type_name = t
235 else: exc_type_name = t.__name__
236 print('***', exc_type_name + ':', v, file=self.stdout)
238 def precmd(self, line):
239 """Handle alias expansion and ';;' separator."""
240 if not line.strip():
241 return line
242 args = line.split()
243 while args[0] in self.aliases:
244 line = self.aliases[args[0]]
245 ii = 1
246 for tmpArg in args[1:]:
247 line = line.replace("%" + str(ii),
248 tmpArg)
249 ii = ii + 1
250 line = line.replace("%*", ' '.join(args[1:]))
251 args = line.split()
252 # split into ';;' separated commands
253 # unless it's an alias command
254 if args[0] != 'alias':
255 marker = line.find(';;')
256 if marker >= 0:
257 # queue up everything after marker
258 next = line[marker+2:].lstrip()
259 self.cmdqueue.append(next)
260 line = line[:marker].rstrip()
261 return line
263 def onecmd(self, line):
264 """Interpret the argument as though it had been typed in response
265 to the prompt.
267 Checks whether this line is typed at the normal prompt or in
268 a breakpoint command list definition.
270 if not self.commands_defining:
271 return cmd.Cmd.onecmd(self, line)
272 else:
273 return self.handle_command_def(line)
275 def handle_command_def(self,line):
276 """ Handles one command line during command list definition. """
277 cmd, arg, line = self.parseline(line)
278 if cmd == 'silent':
279 self.commands_silent[self.commands_bnum] = True
280 return # continue to handle other cmd def in the cmd list
281 elif cmd == 'end':
282 self.cmdqueue = []
283 return 1 # end of cmd list
284 cmdlist = self.commands[self.commands_bnum]
285 if (arg):
286 cmdlist.append(cmd+' '+arg)
287 else:
288 cmdlist.append(cmd)
289 # Determine if we must stop
290 try:
291 func = getattr(self, 'do_' + cmd)
292 except AttributeError:
293 func = self.default
294 # one of the resuming commands
295 if func.__name__ in self.commands_resuming:
296 self.commands_doprompt[self.commands_bnum] = False
297 self.cmdqueue = []
298 return 1
299 return
301 # Command definitions, called by cmdloop()
302 # The argument is the remaining string on the command line
303 # Return true to exit from the command loop
305 do_h = cmd.Cmd.do_help
307 def do_commands(self, arg):
308 """Defines a list of commands associated to a breakpoint.
310 Those commands will be executed whenever the breakpoint causes
311 the program to stop execution."""
312 if not arg:
313 bnum = len(bdb.Breakpoint.bpbynumber)-1
314 else:
315 try:
316 bnum = int(arg)
317 except:
318 print("Usage : commands [bnum]\n ...\n end",
319 file=self.stdout)
320 return
321 self.commands_bnum = bnum
322 self.commands[bnum] = []
323 self.commands_doprompt[bnum] = True
324 self.commands_silent[bnum] = False
325 prompt_back = self.prompt
326 self.prompt = '(com) '
327 self.commands_defining = True
328 self.cmdloop()
329 self.commands_defining = False
330 self.prompt = prompt_back
332 def do_break(self, arg, temporary = 0):
333 # break [ ([filename:]lineno | function) [, "condition"] ]
334 if not arg:
335 if self.breaks: # There's at least one
336 print("Num Type Disp Enb Where", file=self.stdout)
337 for bp in bdb.Breakpoint.bpbynumber:
338 if bp:
339 bp.bpprint(self.stdout)
340 return
341 # parse arguments; comma has lowest precedence
342 # and cannot occur in filename
343 filename = None
344 lineno = None
345 cond = None
346 comma = arg.find(',')
347 if comma > 0:
348 # parse stuff after comma: "condition"
349 cond = arg[comma+1:].lstrip()
350 arg = arg[:comma].rstrip()
351 # parse stuff before comma: [filename:]lineno | function
352 colon = arg.rfind(':')
353 funcname = None
354 if colon >= 0:
355 filename = arg[:colon].rstrip()
356 f = self.lookupmodule(filename)
357 if not f:
358 print('*** ', repr(filename), end=' ', file=self.stdout)
359 print('not found from sys.path', file=self.stdout)
360 return
361 else:
362 filename = f
363 arg = arg[colon+1:].lstrip()
364 try:
365 lineno = int(arg)
366 except ValueError as msg:
367 print('*** Bad lineno:', arg, file=self.stdout)
368 return
369 else:
370 # no colon; can be lineno or function
371 try:
372 lineno = int(arg)
373 except ValueError:
374 try:
375 func = eval(arg,
376 self.curframe.f_globals,
377 self.curframe_locals)
378 except:
379 func = arg
380 try:
381 if hasattr(func, '__func__'):
382 func = func.__func__
383 code = func.__code__
384 #use co_name to identify the bkpt (function names
385 #could be aliased, but co_name is invariant)
386 funcname = code.co_name
387 lineno = code.co_firstlineno
388 filename = code.co_filename
389 except:
390 # last thing to try
391 (ok, filename, ln) = self.lineinfo(arg)
392 if not ok:
393 print('*** The specified object', end=' ', file=self.stdout)
394 print(repr(arg), end=' ', file=self.stdout)
395 print('is not a function', file=self.stdout)
396 print('or was not found along sys.path.', file=self.stdout)
397 return
398 funcname = ok # ok contains a function name
399 lineno = int(ln)
400 if not filename:
401 filename = self.defaultFile()
402 # Check for reasonable breakpoint
403 line = self.checkline(filename, lineno)
404 if line:
405 # now set the break point
406 err = self.set_break(filename, line, temporary, cond, funcname)
407 if err: print('***', err, file=self.stdout)
408 else:
409 bp = self.get_breaks(filename, line)[-1]
410 print("Breakpoint %d at %s:%d" % (bp.number,
411 bp.file,
412 bp.line), file=self.stdout)
414 # To be overridden in derived debuggers
415 def defaultFile(self):
416 """Produce a reasonable default."""
417 filename = self.curframe.f_code.co_filename
418 if filename == '<string>' and self.mainpyfile:
419 filename = self.mainpyfile
420 return filename
422 do_b = do_break
424 def do_tbreak(self, arg):
425 self.do_break(arg, 1)
427 def lineinfo(self, identifier):
428 failed = (None, None, None)
429 # Input is identifier, may be in single quotes
430 idstring = identifier.split("'")
431 if len(idstring) == 1:
432 # not in single quotes
433 id = idstring[0].strip()
434 elif len(idstring) == 3:
435 # quoted
436 id = idstring[1].strip()
437 else:
438 return failed
439 if id == '': return failed
440 parts = id.split('.')
441 # Protection for derived debuggers
442 if parts[0] == 'self':
443 del parts[0]
444 if len(parts) == 0:
445 return failed
446 # Best first guess at file to look at
447 fname = self.defaultFile()
448 if len(parts) == 1:
449 item = parts[0]
450 else:
451 # More than one part.
452 # First is module, second is method/class
453 f = self.lookupmodule(parts[0])
454 if f:
455 fname = f
456 item = parts[1]
457 answer = find_function(item, fname)
458 return answer or failed
460 def checkline(self, filename, lineno):
461 """Check whether specified line seems to be executable.
463 Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
464 line or EOF). Warning: testing is not comprehensive.
466 line = linecache.getline(filename, lineno, self.curframe.f_globals)
467 if not line:
468 print('End of file', file=self.stdout)
469 return 0
470 line = line.strip()
471 # Don't allow setting breakpoint at a blank line
472 if (not line or (line[0] == '#') or
473 (line[:3] == '"""') or line[:3] == "'''"):
474 print('*** Blank or comment', file=self.stdout)
475 return 0
476 return lineno
478 def do_enable(self, arg):
479 args = arg.split()
480 for i in args:
481 try:
482 i = int(i)
483 except ValueError:
484 print('Breakpoint index %r is not a number' % i, file=self.stdout)
485 continue
487 if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
488 print('No breakpoint numbered', i, file=self.stdout)
489 continue
491 bp = bdb.Breakpoint.bpbynumber[i]
492 if bp:
493 bp.enable()
495 def do_disable(self, arg):
496 args = arg.split()
497 for i in args:
498 try:
499 i = int(i)
500 except ValueError:
501 print('Breakpoint index %r is not a number' % i, file=self.stdout)
502 continue
504 if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
505 print('No breakpoint numbered', i, file=self.stdout)
506 continue
508 bp = bdb.Breakpoint.bpbynumber[i]
509 if bp:
510 bp.disable()
512 def do_condition(self, arg):
513 # arg is breakpoint number and condition
514 args = arg.split(' ', 1)
515 try:
516 bpnum = int(args[0].strip())
517 except ValueError:
518 # something went wrong
519 print('Breakpoint index %r is not a number' % args[0], file=self.stdout)
520 return
521 try:
522 cond = args[1]
523 except:
524 cond = None
525 try:
526 bp = bdb.Breakpoint.bpbynumber[bpnum]
527 except IndexError:
528 print('Breakpoint index %r is not valid' % args[0],
529 file=self.stdout)
530 return
531 if bp:
532 bp.cond = cond
533 if not cond:
534 print('Breakpoint', bpnum, end=' ', file=self.stdout)
535 print('is now unconditional.', file=self.stdout)
537 def do_ignore(self,arg):
538 """arg is bp number followed by ignore count."""
539 args = arg.split()
540 try:
541 bpnum = int(args[0].strip())
542 except ValueError:
543 # something went wrong
544 print('Breakpoint index %r is not a number' % args[0], file=self.stdout)
545 return
546 try:
547 count = int(args[1].strip())
548 except:
549 count = 0
550 try:
551 bp = bdb.Breakpoint.bpbynumber[bpnum]
552 except IndexError:
553 print('Breakpoint index %r is not valid' % args[0],
554 file=self.stdout)
555 return
556 if bp:
557 bp.ignore = count
558 if count > 0:
559 reply = 'Will ignore next '
560 if count > 1:
561 reply = reply + '%d crossings' % count
562 else:
563 reply = reply + '1 crossing'
564 print(reply + ' of breakpoint %d.' % bpnum, file=self.stdout)
565 else:
566 print('Will stop next time breakpoint', end=' ', file=self.stdout)
567 print(bpnum, 'is reached.', file=self.stdout)
569 def do_clear(self, arg):
570 """Three possibilities, tried in this order:
571 clear -> clear all breaks, ask for confirmation
572 clear file:lineno -> clear all breaks at file:lineno
573 clear bpno bpno ... -> clear breakpoints by number"""
574 if not arg:
575 try:
576 reply = input('Clear all breaks? ')
577 except EOFError:
578 reply = 'no'
579 reply = reply.strip().lower()
580 if reply in ('y', 'yes'):
581 self.clear_all_breaks()
582 return
583 if ':' in arg:
584 # Make sure it works for "clear C:\foo\bar.py:12"
585 i = arg.rfind(':')
586 filename = arg[:i]
587 arg = arg[i+1:]
588 try:
589 lineno = int(arg)
590 except ValueError:
591 err = "Invalid line number (%s)" % arg
592 else:
593 err = self.clear_break(filename, lineno)
594 if err: print('***', err, file=self.stdout)
595 return
596 numberlist = arg.split()
597 for i in numberlist:
598 try:
599 i = int(i)
600 except ValueError:
601 print('Breakpoint index %r is not a number' % i, file=self.stdout)
602 continue
604 if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
605 print('No breakpoint numbered', i, file=self.stdout)
606 continue
607 err = self.clear_bpbynumber(i)
608 if err:
609 print('***', err, file=self.stdout)
610 else:
611 print('Deleted breakpoint', i, file=self.stdout)
612 do_cl = do_clear # 'c' is already an abbreviation for 'continue'
614 def do_where(self, arg):
615 self.print_stack_trace()
616 do_w = do_where
617 do_bt = do_where
619 def do_up(self, arg):
620 if self.curindex == 0:
621 print('*** Oldest frame', file=self.stdout)
622 else:
623 self.curindex = self.curindex - 1
624 self.curframe = self.stack[self.curindex][0]
625 self.curframe_locals = self.curframe.f_locals
626 self.print_stack_entry(self.stack[self.curindex])
627 self.lineno = None
628 do_u = do_up
630 def do_down(self, arg):
631 if self.curindex + 1 == len(self.stack):
632 print('*** Newest frame', file=self.stdout)
633 else:
634 self.curindex = self.curindex + 1
635 self.curframe = self.stack[self.curindex][0]
636 self.curframe_locals = self.curframe.f_locals
637 self.print_stack_entry(self.stack[self.curindex])
638 self.lineno = None
639 do_d = do_down
641 def do_until(self, arg):
642 self.set_until(self.curframe)
643 return 1
644 do_unt = do_until
646 def do_step(self, arg):
647 self.set_step()
648 return 1
649 do_s = do_step
651 def do_next(self, arg):
652 self.set_next(self.curframe)
653 return 1
654 do_n = do_next
656 def do_run(self, arg):
657 """Restart program by raising an exception to be caught in the main
658 debugger loop. If arguments were given, set them in sys.argv."""
659 if arg:
660 import shlex
661 argv0 = sys.argv[0:1]
662 sys.argv = shlex.split(arg)
663 sys.argv[:0] = argv0
664 raise Restart
666 do_restart = do_run
668 def do_return(self, arg):
669 self.set_return(self.curframe)
670 return 1
671 do_r = do_return
673 def do_continue(self, arg):
674 self.set_continue()
675 return 1
676 do_c = do_cont = do_continue
678 def do_jump(self, arg):
679 if self.curindex + 1 != len(self.stack):
680 print("*** You can only jump within the bottom frame", file=self.stdout)
681 return
682 try:
683 arg = int(arg)
684 except ValueError:
685 print("*** The 'jump' command requires a line number.", file=self.stdout)
686 else:
687 try:
688 # Do the jump, fix up our copy of the stack, and display the
689 # new position
690 self.curframe.f_lineno = arg
691 self.stack[self.curindex] = self.stack[self.curindex][0], arg
692 self.print_stack_entry(self.stack[self.curindex])
693 except ValueError as e:
694 print('*** Jump failed:', e, file=self.stdout)
695 do_j = do_jump
697 def do_debug(self, arg):
698 sys.settrace(None)
699 globals = self.curframe.f_globals
700 locals = self.curframe_locals
701 p = Pdb(self.completekey, self.stdin, self.stdout)
702 p.prompt = "(%s) " % self.prompt.strip()
703 print("ENTERING RECURSIVE DEBUGGER", file=self.stdout)
704 sys.call_tracing(p.run, (arg, globals, locals))
705 print("LEAVING RECURSIVE DEBUGGER", file=self.stdout)
706 sys.settrace(self.trace_dispatch)
707 self.lastcmd = p.lastcmd
709 def do_quit(self, arg):
710 self._user_requested_quit = 1
711 self.set_quit()
712 return 1
714 do_q = do_quit
715 do_exit = do_quit
717 def do_EOF(self, arg):
718 print(file=self.stdout)
719 self._user_requested_quit = 1
720 self.set_quit()
721 return 1
723 def do_args(self, arg):
724 co = self.curframe.f_code
725 dict = self.curframe_locals
726 n = co.co_argcount
727 if co.co_flags & 4: n = n+1
728 if co.co_flags & 8: n = n+1
729 for i in range(n):
730 name = co.co_varnames[i]
731 print(name, '=', end=' ', file=self.stdout)
732 if name in dict: print(dict[name], file=self.stdout)
733 else: print("*** undefined ***", file=self.stdout)
734 do_a = do_args
736 def do_retval(self, arg):
737 if '__return__' in self.curframe_locals:
738 print(self.curframe_locals['__return__'], file=self.stdout)
739 else:
740 print('*** Not yet returned!', file=self.stdout)
741 do_rv = do_retval
743 def _getval(self, arg):
744 try:
745 return eval(arg, self.curframe.f_globals, self.curframe_locals)
746 except:
747 t, v = sys.exc_info()[:2]
748 if isinstance(t, str):
749 exc_type_name = t
750 else: exc_type_name = t.__name__
751 print('***', exc_type_name + ':', repr(v), file=self.stdout)
752 raise
754 def do_p(self, arg):
755 try:
756 print(repr(self._getval(arg)), file=self.stdout)
757 except:
758 pass
759 # make "print" an alias of "p" since print isn't a Python statement anymore
760 do_print = do_p
762 def do_pp(self, arg):
763 try:
764 pprint.pprint(self._getval(arg), self.stdout)
765 except:
766 pass
768 def do_list(self, arg):
769 self.lastcmd = 'list'
770 last = None
771 if arg:
772 try:
773 x = eval(arg, {}, {})
774 if type(x) == type(()):
775 first, last = x
776 first = int(first)
777 last = int(last)
778 if last < first:
779 # Assume it's a count
780 last = first + last
781 else:
782 first = max(1, int(x) - 5)
783 except:
784 print('*** Error in argument:', repr(arg), file=self.stdout)
785 return
786 elif self.lineno is None:
787 first = max(1, self.curframe.f_lineno - 5)
788 else:
789 first = self.lineno + 1
790 if last is None:
791 last = first + 10
792 filename = self.curframe.f_code.co_filename
793 breaklist = self.get_file_breaks(filename)
794 try:
795 for lineno in range(first, last+1):
796 line = linecache.getline(filename, lineno,
797 self.curframe.f_globals)
798 if not line:
799 print('[EOF]', file=self.stdout)
800 break
801 else:
802 s = repr(lineno).rjust(3)
803 if len(s) < 4: s = s + ' '
804 if lineno in breaklist: s = s + 'B'
805 else: s = s + ' '
806 if lineno == self.curframe.f_lineno:
807 s = s + '->'
808 print(s + '\t' + line, end='', file=self.stdout)
809 self.lineno = lineno
810 except KeyboardInterrupt:
811 pass
812 do_l = do_list
814 def do_whatis(self, arg):
815 try:
816 value = eval(arg, self.curframe.f_globals,
817 self.curframe_locals)
818 except:
819 t, v = sys.exc_info()[:2]
820 if type(t) == type(''):
821 exc_type_name = t
822 else: exc_type_name = t.__name__
823 print('***', exc_type_name + ':', repr(v), file=self.stdout)
824 return
825 code = None
826 # Is it a function?
827 try: code = value.__code__
828 except: pass
829 if code:
830 print('Function', code.co_name, file=self.stdout)
831 return
832 # Is it an instance method?
833 try: code = value.__func__.__code__
834 except: pass
835 if code:
836 print('Method', code.co_name, file=self.stdout)
837 return
838 # None of the above...
839 print(type(value), file=self.stdout)
841 def do_alias(self, arg):
842 args = arg.split()
843 if len(args) == 0:
844 keys = self.aliases.keys()
845 keys.sort()
846 for alias in keys:
847 print("%s = %s" % (alias, self.aliases[alias]), file=self.stdout)
848 return
849 if args[0] in self.aliases and len(args) == 1:
850 print("%s = %s" % (args[0], self.aliases[args[0]]), file=self.stdout)
851 else:
852 self.aliases[args[0]] = ' '.join(args[1:])
854 def do_unalias(self, arg):
855 args = arg.split()
856 if len(args) == 0: return
857 if args[0] in self.aliases:
858 del self.aliases[args[0]]
860 #list of all the commands making the program resume execution.
861 commands_resuming = ['do_continue', 'do_step', 'do_next', 'do_return',
862 'do_quit', 'do_jump']
864 # Print a traceback starting at the top stack frame.
865 # The most recently entered frame is printed last;
866 # this is different from dbx and gdb, but consistent with
867 # the Python interpreter's stack trace.
868 # It is also consistent with the up/down commands (which are
869 # compatible with dbx and gdb: up moves towards 'main()'
870 # and down moves towards the most recent stack frame).
872 def print_stack_trace(self):
873 try:
874 for frame_lineno in self.stack:
875 self.print_stack_entry(frame_lineno)
876 except KeyboardInterrupt:
877 pass
879 def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix):
880 frame, lineno = frame_lineno
881 if frame is self.curframe:
882 print('>', end=' ', file=self.stdout)
883 else:
884 print(' ', end=' ', file=self.stdout)
885 print(self.format_stack_entry(frame_lineno,
886 prompt_prefix), file=self.stdout)
889 # Help methods (derived from pdb.doc)
891 def help_help(self):
892 self.help_h()
894 def help_h(self):
895 print("""h(elp)
896 Without argument, print the list of available commands.
897 With a command name as argument, print help about that command
898 "help pdb" pipes the full documentation file to the $PAGER
899 "help exec" gives help on the ! command""", file=self.stdout)
901 def help_where(self):
902 self.help_w()
904 def help_w(self):
905 print("""w(here)
906 Print a stack trace, with the most recent frame at the bottom.
907 An arrow indicates the "current frame", which determines the
908 context of most commands. 'bt' is an alias for this command.""", file=self.stdout)
910 help_bt = help_w
912 def help_down(self):
913 self.help_d()
915 def help_d(self):
916 print("""d(own)
917 Move the current frame one level down in the stack trace
918 (to a newer frame).""", file=self.stdout)
920 def help_up(self):
921 self.help_u()
923 def help_u(self):
924 print("""u(p)
925 Move the current frame one level up in the stack trace
926 (to an older frame).""", file=self.stdout)
928 def help_break(self):
929 self.help_b()
931 def help_b(self):
932 print("""b(reak) ([file:]lineno | function) [, condition]
933 With a line number argument, set a break there in the current
934 file. With a function name, set a break at first executable line
935 of that function. Without argument, list all breaks. If a second
936 argument is present, it is a string specifying an expression
937 which must evaluate to true before the breakpoint is honored.
939 The line number may be prefixed with a filename and a colon,
940 to specify a breakpoint in another file (probably one that
941 hasn't been loaded yet). The file is searched for on sys.path;
942 the .py suffix may be omitted.""", file=self.stdout)
944 def help_clear(self):
945 self.help_cl()
947 def help_cl(self):
948 print("cl(ear) filename:lineno", file=self.stdout)
949 print("""cl(ear) [bpnumber [bpnumber...]]
950 With a space separated list of breakpoint numbers, clear
951 those breakpoints. Without argument, clear all breaks (but
952 first ask confirmation). With a filename:lineno argument,
953 clear all breaks at that line in that file.""", file=self.stdout)
955 def help_tbreak(self):
956 print("""tbreak same arguments as break, but breakpoint is
957 removed when first hit.""", file=self.stdout)
959 def help_enable(self):
960 print("""enable bpnumber [bpnumber ...]
961 Enables the breakpoints given as a space separated list of
962 bp numbers.""", file=self.stdout)
964 def help_disable(self):
965 print("""disable bpnumber [bpnumber ...]
966 Disables the breakpoints given as a space separated list of
967 bp numbers.""", file=self.stdout)
969 def help_ignore(self):
970 print("""ignore bpnumber count
971 Sets the ignore count for the given breakpoint number. A breakpoint
972 becomes active when the ignore count is zero. When non-zero, the
973 count is decremented each time the breakpoint is reached and the
974 breakpoint is not disabled and any associated condition evaluates
975 to true.""", file=self.stdout)
977 def help_condition(self):
978 print("""condition bpnumber str_condition
979 str_condition is a string specifying an expression which
980 must evaluate to true before the breakpoint is honored.
981 If str_condition is absent, any existing condition is removed;
982 i.e., the breakpoint is made unconditional.""", file=self.stdout)
984 def help_step(self):
985 self.help_s()
987 def help_s(self):
988 print("""s(tep)
989 Execute the current line, stop at the first possible occasion
990 (either in a function that is called or in the current function).""", file=self.stdout)
992 def help_until(self):
993 self.help_unt()
995 def help_unt(self):
996 print("""unt(il)
997 Continue execution until the line with a number greater than the current
998 one is reached or until the current frame returns""")
1000 def help_next(self):
1001 self.help_n()
1003 def help_n(self):
1004 print("""n(ext)
1005 Continue execution until the next line in the current function
1006 is reached or it returns.""", file=self.stdout)
1008 def help_return(self):
1009 self.help_r()
1011 def help_r(self):
1012 print("""r(eturn)
1013 Continue execution until the current function returns.""", file=self.stdout)
1015 def help_continue(self):
1016 self.help_c()
1018 def help_cont(self):
1019 self.help_c()
1021 def help_c(self):
1022 print("""c(ont(inue))
1023 Continue execution, only stop when a breakpoint is encountered.""", file=self.stdout)
1025 def help_jump(self):
1026 self.help_j()
1028 def help_j(self):
1029 print("""j(ump) lineno
1030 Set the next line that will be executed.""", file=self.stdout)
1032 def help_debug(self):
1033 print("""debug code
1034 Enter a recursive debugger that steps through the code argument
1035 (which is an arbitrary expression or statement to be executed
1036 in the current environment).""", file=self.stdout)
1038 def help_list(self):
1039 self.help_l()
1041 def help_l(self):
1042 print("""l(ist) [first [,last]]
1043 List source code for the current file.
1044 Without arguments, list 11 lines around the current line
1045 or continue the previous listing.
1046 With one argument, list 11 lines starting at that line.
1047 With two arguments, list the given range;
1048 if the second argument is less than the first, it is a count.""", file=self.stdout)
1050 def help_args(self):
1051 self.help_a()
1053 def help_a(self):
1054 print("""a(rgs)
1055 Print the arguments of the current function.""", file=self.stdout)
1057 def help_p(self):
1058 print("""p(rint) expression
1059 Print the value of the expression.""", file=self.stdout)
1061 def help_pp(self):
1062 print("""pp expression
1063 Pretty-print the value of the expression.""", file=self.stdout)
1065 def help_exec(self):
1066 print("""(!) statement
1067 Execute the (one-line) statement in the context of
1068 the current stack frame.
1069 The exclamation point can be omitted unless the first word
1070 of the statement resembles a debugger command.
1071 To assign to a global variable you must always prefix the
1072 command with a 'global' command, e.g.:
1073 (Pdb) global list_options; list_options = ['-l']
1074 (Pdb)""", file=self.stdout)
1076 def help_run(self):
1077 print("""run [args...]
1078 Restart the debugged python program. If a string is supplied, it is
1079 splitted with "shlex" and the result is used as the new sys.argv.
1080 History, breakpoints, actions and debugger options are preserved.
1081 "restart" is an alias for "run".""")
1083 help_restart = help_run
1085 def help_quit(self):
1086 self.help_q()
1088 def help_q(self):
1089 print("""q(uit) or exit - Quit from the debugger.
1090 The program being executed is aborted.""", file=self.stdout)
1092 help_exit = help_q
1094 def help_whatis(self):
1095 print("""whatis arg
1096 Prints the type of the argument.""", file=self.stdout)
1098 def help_EOF(self):
1099 print("""EOF
1100 Handles the receipt of EOF as a command.""", file=self.stdout)
1102 def help_alias(self):
1103 print("""alias [name [command [parameter parameter ...] ]]
1104 Creates an alias called 'name' the executes 'command'. The command
1105 must *not* be enclosed in quotes. Replaceable parameters are
1106 indicated by %1, %2, and so on, while %* is replaced by all the
1107 parameters. If no command is given, the current alias for name
1108 is shown. If no name is given, all aliases are listed.
1110 Aliases may be nested and can contain anything that can be
1111 legally typed at the pdb prompt. Note! You *can* override
1112 internal pdb commands with aliases! Those internal commands
1113 are then hidden until the alias is removed. Aliasing is recursively
1114 applied to the first word of the command line; all other words
1115 in the line are left alone.
1117 Some useful aliases (especially when placed in the .pdbrc file) are:
1119 #Print instance variables (usage "pi classInst")
1120 alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
1122 #Print instance variables in self
1123 alias ps pi self
1124 """, file=self.stdout)
1126 def help_unalias(self):
1127 print("""unalias name
1128 Deletes the specified alias.""", file=self.stdout)
1130 def help_commands(self):
1131 print("""commands [bpnumber]
1132 (com) ...
1133 (com) end
1134 (Pdb)
1136 Specify a list of commands for breakpoint number bpnumber. The
1137 commands themselves appear on the following lines. Type a line
1138 containing just 'end' to terminate the commands.
1140 To remove all commands from a breakpoint, type commands and
1141 follow it immediately with end; that is, give no commands.
1143 With no bpnumber argument, commands refers to the last
1144 breakpoint set.
1146 You can use breakpoint commands to start your program up again.
1147 Simply use the continue command, or step, or any other
1148 command that resumes execution.
1150 Specifying any command resuming execution (currently continue,
1151 step, next, return, jump, quit and their abbreviations) terminates
1152 the command list (as if that command was immediately followed by end).
1153 This is because any time you resume execution
1154 (even with a simple next or step), you may encounter
1155 another breakpoint--which could have its own command list, leading to
1156 ambiguities about which list to execute.
1158 If you use the 'silent' command in the command list, the
1159 usual message about stopping at a breakpoint is not printed. This may
1160 be desirable for breakpoints that are to print a specific message and
1161 then continue. If none of the other commands print anything, you
1162 see no sign that the breakpoint was reached.
1163 """, file=self.stdout)
1165 def help_pdb(self):
1166 help()
1168 def lookupmodule(self, filename):
1169 """Helper function for break/clear parsing -- may be overridden.
1171 lookupmodule() translates (possibly incomplete) file or module name
1172 into an absolute file name.
1174 if os.path.isabs(filename) and os.path.exists(filename):
1175 return filename
1176 f = os.path.join(sys.path[0], filename)
1177 if os.path.exists(f) and self.canonic(f) == self.mainpyfile:
1178 return f
1179 root, ext = os.path.splitext(filename)
1180 if ext == '':
1181 filename = filename + '.py'
1182 if os.path.isabs(filename):
1183 return filename
1184 for dirname in sys.path:
1185 while os.path.islink(dirname):
1186 dirname = os.readlink(dirname)
1187 fullname = os.path.join(dirname, filename)
1188 if os.path.exists(fullname):
1189 return fullname
1190 return None
1192 def _runscript(self, filename):
1193 # The script has to run in __main__ namespace (or imports from
1194 # __main__ will break).
1196 # So we clear up the __main__ and set several special variables
1197 # (this gets rid of pdb's globals and cleans old variables on restarts).
1198 import __main__
1199 __main__.__dict__.clear()
1200 __main__.__dict__.update({"__name__" : "__main__",
1201 "__file__" : filename,
1202 "__builtins__": __builtins__,
1205 # When bdb sets tracing, a number of call and line events happens
1206 # BEFORE debugger even reaches user's code (and the exact sequence of
1207 # events depends on python version). So we take special measures to
1208 # avoid stopping before we reach the main script (see user_line and
1209 # user_call for details).
1210 self._wait_for_mainpyfile = 1
1211 self.mainpyfile = self.canonic(filename)
1212 self._user_requested_quit = 0
1213 with open(filename) as fp:
1214 statement = fp.read()
1215 self.run(statement)
1217 # Simplified interface
1219 def run(statement, globals=None, locals=None):
1220 Pdb().run(statement, globals, locals)
1222 def runeval(expression, globals=None, locals=None):
1223 return Pdb().runeval(expression, globals, locals)
1225 def runctx(statement, globals, locals):
1226 # B/W compatibility
1227 run(statement, globals, locals)
1229 def runcall(*args, **kwds):
1230 return Pdb().runcall(*args, **kwds)
1232 def set_trace():
1233 Pdb().set_trace(sys._getframe().f_back)
1235 # Post-Mortem interface
1237 def post_mortem(t=None):
1238 # handling the default
1239 if t is None:
1240 # sys.exc_info() returns (type, value, traceback) if an exception is
1241 # being handled, otherwise it returns None
1242 t = sys.exc_info()[2]
1243 if t is None:
1244 raise ValueError("A valid traceback must be passed if no "
1245 "exception is being handled")
1247 p = Pdb()
1248 p.reset()
1249 p.interaction(None, t)
1251 def pm():
1252 post_mortem(sys.last_traceback)
1255 # Main program for testing
1257 TESTCMD = 'import x; x.main()'
1259 def test():
1260 run(TESTCMD)
1262 # print help
1263 def help():
1264 for dirname in sys.path:
1265 fullname = os.path.join(dirname, 'pdb.doc')
1266 if os.path.exists(fullname):
1267 sts = os.system('${PAGER-more} '+fullname)
1268 if sts: print('*** Pager exit status:', sts)
1269 break
1270 else:
1271 print('Sorry, can\'t find the help file "pdb.doc"', end=' ')
1272 print('along the Python search path')
1274 def main():
1275 if not sys.argv[1:] or sys.argv[1] in ("--help", "-h"):
1276 print("usage: pdb.py scriptfile [arg] ...")
1277 sys.exit(2)
1279 mainpyfile = sys.argv[1] # Get script filename
1280 if not os.path.exists(mainpyfile):
1281 print('Error:', mainpyfile, 'does not exist')
1282 sys.exit(1)
1284 del sys.argv[0] # Hide "pdb.py" from argument list
1286 # Replace pdb's dir with script's dir in front of module search path.
1287 sys.path[0] = os.path.dirname(mainpyfile)
1289 # Note on saving/restoring sys.argv: it's a good idea when sys.argv was
1290 # modified by the script being debugged. It's a bad idea when it was
1291 # changed by the user from the command line. There is a "restart" command
1292 # which allows explicit specification of command line arguments.
1293 pdb = Pdb()
1294 while 1:
1295 try:
1296 pdb._runscript(mainpyfile)
1297 if pdb._user_requested_quit:
1298 break
1299 print("The program finished and will be restarted")
1300 except Restart:
1301 print("Restarting", mainpyfile, "with arguments:")
1302 print("\t" + " ".join(sys.argv[1:]))
1303 except SystemExit:
1304 # In most cases SystemExit does not warrant a post-mortem session.
1305 print("The program exited via sys.exit(). Exit status: ", end=' ')
1306 print(sys.exc_info()[1])
1307 except:
1308 traceback.print_exc()
1309 print("Uncaught exception. Entering post mortem debugging")
1310 print("Running 'cont' or 'step' will restart the program")
1311 t = sys.exc_info()[2]
1312 pdb.interaction(None, t)
1313 print("Post mortem debugger finished. The " + mainpyfile +
1314 " will be restarted")
1317 # When invoked as main program, invoke the debugger on a script
1318 if __name__ == '__main__':
1319 import pdb
1320 pdb.main()