3 """A Python debugger."""
5 # (See pdb.doc for documentation.)
16 # Create a custom safe Repr instance and increase its maxstring.
17 # The default of 30 truncates error messages too easily.
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*[(]' % funcname
)
31 # consumer of this info expects the first line to be 1
39 answer
= funcname
, filename
, lineno
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
):
56 bdb
.Bdb
.__init
__(self
)
57 cmd
.Cmd
.__init
__(self
)
58 self
.prompt
= '(Pdb) '
60 # Try to load readline if it exists
66 # Read $HOME/.pdbrc and ./.pdbrc
68 if 'HOME' in os
.environ
:
69 envHome
= os
.environ
['HOME']
71 rcFile
= open(os
.path
.join(envHome
, ".pdbrc"))
75 for line
in rcFile
.readlines():
76 self
.rcLines
.append(line
)
79 rcFile
= open(".pdbrc")
83 for line
in rcFile
.readlines():
84 self
.rcLines
.append(line
)
97 def setup(self
, f
, t
):
99 self
.stack
, self
.curindex
= self
.get_stack(f
, t
)
100 self
.curframe
= self
.stack
[self
.curindex
][0]
103 # Can be executed earlier than 'setup' if desired
104 def execRcLines(self
):
106 # Make local copy because of recursion
107 rcLines
= self
.rcLines
112 if len(line
) > 0 and line
[0] != '#':
115 # Override Bdb methods
117 def user_call(self
, frame
, argument_list
):
118 """This method is called when there is the remote possibility
119 that we ever need to stop in this function."""
121 self
.interaction(frame
, None)
123 def user_line(self
, frame
):
124 """This function is called when we stop or break at this line."""
125 self
.interaction(frame
, None)
127 def user_return(self
, frame
, return_value
):
128 """This function is called when a return trap is set here."""
129 frame
.f_locals
['__return__'] = return_value
131 self
.interaction(frame
, None)
133 def user_exception(self
, frame
, (exc_type
, exc_value
, exc_traceback
)):
134 """This function is called if an exception occurs,
135 but only if we are to stop at or just below this level."""
136 frame
.f_locals
['__exception__'] = exc_type
, exc_value
137 if type(exc_type
) == type(''):
138 exc_type_name
= exc_type
139 else: exc_type_name
= exc_type
.__name
__
140 print exc_type_name
+ ':', _saferepr(exc_value
)
141 self
.interaction(frame
, exc_traceback
)
143 # General interaction function
145 def interaction(self
, frame
, traceback
):
146 self
.setup(frame
, traceback
)
147 self
.print_stack_entry(self
.stack
[self
.curindex
])
151 def default(self
, line
):
152 if line
[:1] == '!': line
= line
[1:]
153 locals = self
.curframe
.f_locals
154 globals = self
.curframe
.f_globals
156 code
= compile(line
+ '\n', '<stdin>', 'single')
157 exec code
in globals, locals
159 t
, v
= sys
.exc_info()[:2]
160 if type(t
) == type(''):
162 else: exc_type_name
= t
.__name
__
163 print '***', exc_type_name
+ ':', v
165 def precmd(self
, line
):
166 """Handle alias expansion and ';;' separator."""
170 while args
[0] in self
.aliases
:
171 line
= self
.aliases
[args
[0]]
173 for tmpArg
in args
[1:]:
174 line
= line
.replace("%" + str(ii
),
177 line
= line
.replace("%*", ' '.join(args
[1:]))
179 # split into ';;' separated commands
180 # unless it's an alias command
181 if args
[0] != 'alias':
182 marker
= line
.find(';;')
184 # queue up everything after marker
185 next
= line
[marker
+2:].lstrip()
186 self
.cmdqueue
.append(next
)
187 line
= line
[:marker
].rstrip()
190 # Command definitions, called by cmdloop()
191 # The argument is the remaining string on the command line
192 # Return true to exit from the command loop
194 do_h
= cmd
.Cmd
.do_help
196 def do_EOF(self
, arg
):
197 return 0 # Don't die on EOF
199 def do_break(self
, arg
, temporary
= 0):
200 # break [ ([filename:]lineno | function) [, "condition"] ]
202 if self
.breaks
: # There's at least one
203 print "Num Type Disp Enb Where"
204 for bp
in bdb
.Breakpoint
.bpbynumber
:
208 # parse arguments; comma has lowest precedence
209 # and cannot occur in filename
213 comma
= arg
.find(',')
215 # parse stuff after comma: "condition"
216 cond
= arg
[comma
+1:].lstrip()
217 arg
= arg
[:comma
].rstrip()
218 # parse stuff before comma: [filename:]lineno | function
219 colon
= arg
.rfind(':')
221 filename
= arg
[:colon
].rstrip()
222 f
= self
.lookupmodule(filename
)
224 print '*** ', `filename`
,
225 print 'not found from sys.path'
229 arg
= arg
[colon
+1:].lstrip()
232 except ValueError, msg
:
233 print '*** Bad lineno:', arg
236 # no colon; can be lineno or function
242 self
.curframe
.f_globals
,
243 self
.curframe
.f_locals
)
247 if hasattr(func
, 'im_func'):
249 code
= func
.func_code
250 lineno
= code
.co_firstlineno
251 filename
= code
.co_filename
254 (ok
, filename
, ln
) = self
.lineinfo(arg
)
256 print '*** The specified object',
258 print 'is not a function'
259 print ('or was not found '
264 filename
= self
.defaultFile()
265 # Check for reasonable breakpoint
266 line
= self
.checkline(filename
, lineno
)
268 # now set the break point
269 err
= self
.set_break(filename
, line
, temporary
, cond
)
270 if err
: print '***', err
272 bp
= self
.get_breaks(filename
, line
)[-1]
273 print "Breakpoint %d at %s:%d" % (bp
.number
,
277 # To be overridden in derived debuggers
278 def defaultFile(self
):
279 """Produce a reasonable default."""
280 filename
= self
.curframe
.f_code
.co_filename
281 if filename
== '<string>' and mainpyfile
:
282 filename
= mainpyfile
287 def do_tbreak(self
, arg
):
288 self
.do_break(arg
, 1)
290 def lineinfo(self
, identifier
):
291 failed
= (None, None, None)
292 # Input is identifier, may be in single quotes
293 idstring
= identifier
.split("'")
294 if len(idstring
) == 1:
295 # not in single quotes
296 id = idstring
[0].strip()
297 elif len(idstring
) == 3:
299 id = idstring
[1].strip()
302 if id == '': return failed
303 parts
= id.split('.')
304 # Protection for derived debuggers
305 if parts
[0] == 'self':
309 # Best first guess at file to look at
310 fname
= self
.defaultFile()
314 # More than one part.
315 # First is module, second is method/class
316 f
= self
.lookupmodule(parts
[0])
320 answer
= find_function(item
, fname
)
321 return answer
or failed
323 def checkline(self
, filename
, lineno
):
324 """Return line number of first line at or after input
325 argument such that if the input points to a 'def', the
326 returned line number is the first
327 non-blank/non-comment line to follow. If the input
328 points to a blank or comment line, return 0. At end
329 of file, also return 0."""
331 line
= linecache
.getline(filename
, lineno
)
336 # Don't allow setting breakpoint at a blank line
337 if (not line
or (line
[0] == '#') or
338 (line
[:3] == '"""') or line
[:3] == "'''"):
339 print '*** Blank or comment'
341 # When a file is read in and a breakpoint is at
342 # the 'def' statement, the system stops there at
343 # code parse time. We don't want that, so all breakpoints
344 # set at 'def' statements are moved one line onward
345 if line
[:3] == 'def':
362 elif c
in ('(','{','['):
363 brackets
= brackets
+ 1
364 elif c
in (')','}',']'):
365 brackets
= brackets
- 1
367 line
= linecache
.getline(filename
, lineno
)
372 if not line
: continue # Blank line
373 if brackets
<= 0 and line
[0] not in ('#','"',"'"):
377 def do_enable(self
, arg
):
380 bp
= bdb
.Breakpoint
.bpbynumber
[int(i
)]
384 def do_disable(self
, arg
):
387 bp
= bdb
.Breakpoint
.bpbynumber
[int(i
)]
391 def do_condition(self
, arg
):
392 # arg is breakpoint number and condition
393 args
= arg
.split(' ', 1)
394 bpnum
= int(args
[0].strip())
399 bp
= bdb
.Breakpoint
.bpbynumber
[bpnum
]
403 print 'Breakpoint', bpnum
,
404 print 'is now unconditional.'
406 def do_ignore(self
,arg
):
407 """arg is bp number followed by ignore count."""
409 bpnum
= int(args
[0].strip())
411 count
= int(args
[1].strip())
414 bp
= bdb
.Breakpoint
.bpbynumber
[bpnum
]
418 reply
= 'Will ignore next '
420 reply
= reply
+ '%d crossings' % count
422 reply
= reply
+ '1 crossing'
423 print reply
+ ' of breakpoint %d.' % bpnum
425 print 'Will stop next time breakpoint',
426 print bpnum
, 'is reached.'
428 def do_clear(self
, arg
):
429 """Three possibilities, tried in this order:
430 clear -> clear all breaks, ask for confirmation
431 clear file:lineno -> clear all breaks at file:lineno
432 clear bpno bpno ... -> clear breakpoints by number"""
435 reply
= raw_input('Clear all breaks? ')
438 reply
= reply
.strip().lower()
439 if reply
in ('y', 'yes'):
440 self
.clear_all_breaks()
443 # Make sure it works for "clear C:\foo\bar.py:12"
450 err
= "Invalid line number (%s)" % arg
452 err
= self
.clear_break(filename
, lineno
)
453 if err
: print '***', err
455 numberlist
= arg
.split()
457 err
= self
.clear_bpbynumber(i
)
461 print 'Deleted breakpoint %s ' % (i
,)
462 do_cl
= do_clear
# 'c' is already an abbreviation for 'continue'
464 def do_where(self
, arg
):
465 self
.print_stack_trace()
469 def do_up(self
, arg
):
470 if self
.curindex
== 0:
471 print '*** Oldest frame'
473 self
.curindex
= self
.curindex
- 1
474 self
.curframe
= self
.stack
[self
.curindex
][0]
475 self
.print_stack_entry(self
.stack
[self
.curindex
])
479 def do_down(self
, arg
):
480 if self
.curindex
+ 1 == len(self
.stack
):
481 print '*** Newest frame'
483 self
.curindex
= self
.curindex
+ 1
484 self
.curframe
= self
.stack
[self
.curindex
][0]
485 self
.print_stack_entry(self
.stack
[self
.curindex
])
489 def do_step(self
, arg
):
494 def do_next(self
, arg
):
495 self
.set_next(self
.curframe
)
499 def do_return(self
, arg
):
500 self
.set_return(self
.curframe
)
504 def do_continue(self
, arg
):
507 do_c
= do_cont
= do_continue
509 def do_jump(self
, arg
):
510 if self
.curindex
+ 1 != len(self
.stack
):
511 print "*** You can only jump within the bottom frame"
516 print "*** The 'jump' command requires a line number."
519 # Do the jump, fix up our copy of the stack, and display the
521 self
.curframe
.f_lineno
= arg
522 self
.stack
[self
.curindex
] = self
.stack
[self
.curindex
][0], arg
523 self
.print_stack_entry(self
.stack
[self
.curindex
])
524 except ValueError, e
:
525 print '*** Jump failed:', e
528 def do_quit(self
, arg
):
534 def do_args(self
, arg
):
539 if co
.co_flags
& 4: n
= n
+1
540 if co
.co_flags
& 8: n
= n
+1
542 name
= co
.co_varnames
[i
]
544 if name
in dict: print dict[name
]
545 else: print "*** undefined ***"
548 def do_retval(self
, arg
):
549 if '__return__' in self
.curframe
.f_locals
:
550 print self
.curframe
.f_locals
['__return__']
552 print '*** Not yet returned!'
555 def _getval(self
, arg
):
557 return eval(arg
, self
.curframe
.f_globals
,
558 self
.curframe
.f_locals
)
560 t
, v
= sys
.exc_info()[:2]
561 if isinstance(t
, str):
563 else: exc_type_name
= t
.__name
__
564 print '***', exc_type_name
+ ':', `v`
569 print repr(self
._getval
(arg
))
573 def do_pp(self
, arg
):
575 pprint
.pprint(self
._getval
(arg
))
579 def do_list(self
, arg
):
580 self
.lastcmd
= 'list'
584 x
= eval(arg
, {}, {})
585 if type(x
) == type(()):
590 # Assume it's a count
593 first
= max(1, int(x
) - 5)
595 print '*** Error in argument:', `arg`
597 elif self
.lineno
is None:
598 first
= max(1, self
.curframe
.f_lineno
- 5)
600 first
= self
.lineno
+ 1
603 filename
= self
.curframe
.f_code
.co_filename
604 breaklist
= self
.get_file_breaks(filename
)
606 for lineno
in range(first
, last
+1):
607 line
= linecache
.getline(filename
, lineno
)
612 s
= `lineno`
.rjust(3)
613 if len(s
) < 4: s
= s
+ ' '
614 if lineno
in breaklist
: s
= s
+ 'B'
616 if lineno
== self
.curframe
.f_lineno
:
618 print s
+ '\t' + line
,
620 except KeyboardInterrupt:
624 def do_whatis(self
, arg
):
626 value
= eval(arg
, self
.curframe
.f_globals
,
627 self
.curframe
.f_locals
)
629 t
, v
= sys
.exc_info()[:2]
630 if type(t
) == type(''):
632 else: exc_type_name
= t
.__name
__
633 print '***', exc_type_name
+ ':', `v`
637 try: code
= value
.func_code
640 print 'Function', code
.co_name
642 # Is it an instance method?
643 try: code
= value
.im_func
.func_code
646 print 'Method', code
.co_name
648 # None of the above...
651 def do_alias(self
, arg
):
654 keys
= self
.aliases
.keys()
657 print "%s = %s" % (alias
, self
.aliases
[alias
])
659 if args
[0] in self
.aliases
and len(args
) == 1:
660 print "%s = %s" % (args
[0], self
.aliases
[args
[0]])
662 self
.aliases
[args
[0]] = ' '.join(args
[1:])
664 def do_unalias(self
, arg
):
666 if len(args
) == 0: return
667 if args
[0] in self
.aliases
:
668 del self
.aliases
[args
[0]]
670 # Print a traceback starting at the top stack frame.
671 # The most recently entered frame is printed last;
672 # this is different from dbx and gdb, but consistent with
673 # the Python interpreter's stack trace.
674 # It is also consistent with the up/down commands (which are
675 # compatible with dbx and gdb: up moves towards 'main()'
676 # and down moves towards the most recent stack frame).
678 def print_stack_trace(self
):
680 for frame_lineno
in self
.stack
:
681 self
.print_stack_entry(frame_lineno
)
682 except KeyboardInterrupt:
685 def print_stack_entry(self
, frame_lineno
, prompt_prefix
=line_prefix
):
686 frame
, lineno
= frame_lineno
687 if frame
is self
.curframe
:
691 print self
.format_stack_entry(frame_lineno
, prompt_prefix
)
694 # Help methods (derived from pdb.doc)
701 Without argument, print the list of available commands.
702 With a command name as argument, print help about that command
703 "help pdb" pipes the full documentation file to the $PAGER
704 "help exec" gives help on the ! command"""
706 def help_where(self
):
711 Print a stack trace, with the most recent frame at the bottom.
712 An arrow indicates the "current frame", which determines the
713 context of most commands. 'bt' is an alias for this command."""
722 Move the current frame one level down in the stack trace
723 (to an older frame)."""
730 Move the current frame one level up in the stack trace
731 (to a newer frame)."""
733 def help_break(self
):
737 print """b(reak) ([file:]lineno | function) [, condition]
738 With a line number argument, set a break there in the current
739 file. With a function name, set a break at first executable line
740 of that function. Without argument, list all breaks. If a second
741 argument is present, it is a string specifying an expression
742 which must evaluate to true before the breakpoint is honored.
744 The line number may be prefixed with a filename and a colon,
745 to specify a breakpoint in another file (probably one that
746 hasn't been loaded yet). The file is searched for on sys.path;
747 the .py suffix may be omitted."""
749 def help_clear(self
):
753 print "cl(ear) filename:lineno"
754 print """cl(ear) [bpnumber [bpnumber...]]
755 With a space separated list of breakpoint numbers, clear
756 those breakpoints. Without argument, clear all breaks (but
757 first ask confirmation). With a filename:lineno argument,
758 clear all breaks at that line in that file.
760 Note that the argument is different from previous versions of
761 the debugger (in python distributions 1.5.1 and before) where
762 a linenumber was used instead of either filename:lineno or
763 breakpoint numbers."""
765 def help_tbreak(self
):
766 print """tbreak same arguments as break, but breakpoint is
767 removed when first hit."""
769 def help_enable(self
):
770 print """enable bpnumber [bpnumber ...]
771 Enables the breakpoints given as a space separated list of
774 def help_disable(self
):
775 print """disable bpnumber [bpnumber ...]
776 Disables the breakpoints given as a space separated list of
779 def help_ignore(self
):
780 print """ignore bpnumber count
781 Sets the ignore count for the given breakpoint number. A breakpoint
782 becomes active when the ignore count is zero. When non-zero, the
783 count is decremented each time the breakpoint is reached and the
784 breakpoint is not disabled and any associated condition evaluates
787 def help_condition(self
):
788 print """condition bpnumber str_condition
789 str_condition is a string specifying an expression which
790 must evaluate to true before the breakpoint is honored.
791 If str_condition is absent, any existing condition is removed;
792 i.e., the breakpoint is made unconditional."""
799 Execute the current line, stop at the first possible occasion
800 (either in a function that is called or in the current function)."""
807 Continue execution until the next line in the current function
808 is reached or it returns."""
810 def help_return(self
):
815 Continue execution until the current function returns."""
817 def help_continue(self
):
824 print """c(ont(inue))
825 Continue execution, only stop when a breakpoint is encountered."""
831 print """j(ump) lineno
832 Set the next line that will be executed."""
838 print """l(ist) [first [,last]]
839 List source code for the current file.
840 Without arguments, list 11 lines around the current line
841 or continue the previous listing.
842 With one argument, list 11 lines starting at that line.
843 With two arguments, list the given range;
844 if the second argument is less than the first, it is a count."""
851 Print the arguments of the current function."""
854 print """p expression
855 Print the value of the expression."""
858 print """pp expression
859 Pretty-print the value of the expression."""
862 print """(!) statement
863 Execute the (one-line) statement in the context of
864 the current stack frame.
865 The exclamation point can be omitted unless the first word
866 of the statement resembles a debugger command.
867 To assign to a global variable you must always prefix the
868 command with a 'global' command, e.g.:
869 (Pdb) global list_options; list_options = ['-l']
876 print """q(uit) or exit - Quit from the debugger.
877 The program being executed is aborted."""
881 def help_whatis(self
):
883 Prints the type of the argument."""
887 Handles the receipt of EOF as a command."""
889 def help_alias(self
):
890 print """alias [name [command [parameter parameter ...] ]]
891 Creates an alias called 'name' the executes 'command'. The command
892 must *not* be enclosed in quotes. Replaceable parameters are
893 indicated by %1, %2, and so on, while %* is replaced by all the
894 parameters. If no command is given, the current alias for name
895 is shown. If no name is given, all aliases are listed.
897 Aliases may be nested and can contain anything that can be
898 legally typed at the pdb prompt. Note! You *can* override
899 internal pdb commands with aliases! Those internal commands
900 are then hidden until the alias is removed. Aliasing is recursively
901 applied to the first word of the command line; all other words
902 in the line are left alone.
904 Some useful aliases (especially when placed in the .pdbrc file) are:
906 #Print instance variables (usage "pi classInst")
907 alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
909 #Print instance variables in self
913 def help_unalias(self
):
914 print """unalias name
915 Deletes the specified alias."""
920 def lookupmodule(self
, filename
):
921 """Helper function for break/clear parsing -- may be overridden."""
922 root
, ext
= os
.path
.splitext(filename
)
924 filename
= filename
+ '.py'
925 if os
.path
.isabs(filename
):
927 for dirname
in sys
.path
:
928 while os
.path
.islink(dirname
):
929 dirname
= os
.readlink(dirname
)
930 fullname
= os
.path
.join(dirname
, filename
)
931 if os
.path
.exists(fullname
):
935 # Simplified interface
937 def run(statement
, globals=None, locals=None):
938 Pdb().run(statement
, globals, locals)
940 def runeval(expression
, globals=None, locals=None):
941 return Pdb().runeval(expression
, globals, locals)
943 def runctx(statement
, globals, locals):
945 run(statement
, globals, locals)
948 return apply(Pdb().runcall
, args
)
953 # Post-Mortem interface
958 while t
.tb_next
is not None:
960 p
.interaction(t
.tb_frame
, t
)
963 post_mortem(sys
.last_traceback
)
966 # Main program for testing
968 TESTCMD
= 'import x; x.main()'
975 for dirname
in sys
.path
:
976 fullname
= os
.path
.join(dirname
, 'pdb.doc')
977 if os
.path
.exists(fullname
):
978 sts
= os
.system('${PAGER-more} '+fullname
)
979 if sts
: print '*** Pager exit status:', sts
982 print 'Sorry, can\'t find the help file "pdb.doc"',
983 print 'along the Python search path'
988 # When invoked as main program, invoke the debugger on a script
989 if __name__
=='__main__':
991 print "usage: pdb.py scriptfile [arg] ..."
994 mainpyfile
= filename
= sys
.argv
[1] # Get script filename
995 if not os
.path
.exists(filename
):
996 print 'Error:', `filename`
, 'does not exist'
998 mainmodule
= os
.path
.basename(filename
)
999 del sys
.argv
[0] # Hide "pdb.py" from argument list
1001 # Insert script directory in front of module search path
1002 sys
.path
.insert(0, os
.path
.dirname(filename
))
1004 run('execfile(' + `filename`
+ ')')