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