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."""
120 if self
.stop_here(frame
):
122 self
.interaction(frame
, None)
124 def user_line(self
, frame
):
125 """This function is called when we stop or break at this line."""
126 self
.interaction(frame
, None)
128 def user_return(self
, frame
, return_value
):
129 """This function is called when a return trap is set here."""
130 frame
.f_locals
['__return__'] = return_value
132 self
.interaction(frame
, None)
134 def user_exception(self
, frame
, (exc_type
, exc_value
, exc_traceback
)):
135 """This function is called if an exception occurs,
136 but only if we are to stop at or just below this level."""
137 frame
.f_locals
['__exception__'] = exc_type
, exc_value
138 if type(exc_type
) == type(''):
139 exc_type_name
= exc_type
140 else: exc_type_name
= exc_type
.__name
__
141 print exc_type_name
+ ':', _saferepr(exc_value
)
142 self
.interaction(frame
, exc_traceback
)
144 # General interaction function
146 def interaction(self
, frame
, traceback
):
147 self
.setup(frame
, traceback
)
148 self
.print_stack_entry(self
.stack
[self
.curindex
])
152 def default(self
, line
):
153 if line
[:1] == '!': line
= line
[1:]
154 locals = self
.curframe
.f_locals
155 globals = self
.curframe
.f_globals
157 code
= compile(line
+ '\n', '<stdin>', 'single')
158 exec code
in globals, locals
160 t
, v
= sys
.exc_info()[:2]
161 if type(t
) == type(''):
163 else: exc_type_name
= t
.__name
__
164 print '***', exc_type_name
+ ':', v
166 def precmd(self
, line
):
167 """Handle alias expansion and ';;' separator."""
171 while args
[0] in self
.aliases
:
172 line
= self
.aliases
[args
[0]]
174 for tmpArg
in args
[1:]:
175 line
= line
.replace("%" + str(ii
),
178 line
= line
.replace("%*", ' '.join(args
[1:]))
180 # split into ';;' separated commands
181 # unless it's an alias command
182 if args
[0] != 'alias':
183 marker
= line
.find(';;')
185 # queue up everything after marker
186 next
= line
[marker
+2:].lstrip()
187 self
.cmdqueue
.append(next
)
188 line
= line
[:marker
].rstrip()
191 # Command definitions, called by cmdloop()
192 # The argument is the remaining string on the command line
193 # Return true to exit from the command loop
195 do_h
= cmd
.Cmd
.do_help
197 def do_break(self
, arg
, temporary
= 0):
198 # break [ ([filename:]lineno | function) [, "condition"] ]
200 if self
.breaks
: # There's at least one
201 print "Num Type Disp Enb Where"
202 for bp
in bdb
.Breakpoint
.bpbynumber
:
206 # parse arguments; comma has lowest precedence
207 # and cannot occur in filename
211 comma
= arg
.find(',')
213 # parse stuff after comma: "condition"
214 cond
= arg
[comma
+1:].lstrip()
215 arg
= arg
[:comma
].rstrip()
216 # parse stuff before comma: [filename:]lineno | function
217 colon
= arg
.rfind(':')
219 filename
= arg
[:colon
].rstrip()
220 f
= self
.lookupmodule(filename
)
222 print '*** ', `filename`
,
223 print 'not found from sys.path'
227 arg
= arg
[colon
+1:].lstrip()
230 except ValueError, msg
:
231 print '*** Bad lineno:', arg
234 # no colon; can be lineno or function
240 self
.curframe
.f_globals
,
241 self
.curframe
.f_locals
)
245 if hasattr(func
, 'im_func'):
247 code
= func
.func_code
248 lineno
= code
.co_firstlineno
249 filename
= code
.co_filename
252 (ok
, filename
, ln
) = self
.lineinfo(arg
)
254 print '*** The specified object',
256 print 'is not a function'
257 print ('or was not found '
262 filename
= self
.defaultFile()
263 # Check for reasonable breakpoint
264 line
= self
.checkline(filename
, lineno
)
266 # now set the break point
267 err
= self
.set_break(filename
, line
, temporary
, cond
)
268 if err
: print '***', err
270 bp
= self
.get_breaks(filename
, line
)[-1]
271 print "Breakpoint %d at %s:%d" % (bp
.number
,
275 # To be overridden in derived debuggers
276 def defaultFile(self
):
277 """Produce a reasonable default."""
278 filename
= self
.curframe
.f_code
.co_filename
279 if filename
== '<string>' and mainpyfile
:
280 filename
= mainpyfile
285 def do_tbreak(self
, arg
):
286 self
.do_break(arg
, 1)
288 def lineinfo(self
, identifier
):
289 failed
= (None, None, None)
290 # Input is identifier, may be in single quotes
291 idstring
= identifier
.split("'")
292 if len(idstring
) == 1:
293 # not in single quotes
294 id = idstring
[0].strip()
295 elif len(idstring
) == 3:
297 id = idstring
[1].strip()
300 if id == '': return failed
301 parts
= id.split('.')
302 # Protection for derived debuggers
303 if parts
[0] == 'self':
307 # Best first guess at file to look at
308 fname
= self
.defaultFile()
312 # More than one part.
313 # First is module, second is method/class
314 f
= self
.lookupmodule(parts
[0])
318 answer
= find_function(item
, fname
)
319 return answer
or failed
321 def checkline(self
, filename
, lineno
):
322 """Return line number of first line at or after input
323 argument such that if the input points to a 'def', the
324 returned line number is the first
325 non-blank/non-comment line to follow. If the input
326 points to a blank or comment line, return 0. At end
327 of file, also return 0."""
329 line
= linecache
.getline(filename
, lineno
)
334 # Don't allow setting breakpoint at a blank line
335 if (not line
or (line
[0] == '#') or
336 (line
[:3] == '"""') or line
[:3] == "'''"):
337 print '*** Blank or comment'
339 # When a file is read in and a breakpoint is at
340 # the 'def' statement, the system stops there at
341 # code parse time. We don't want that, so all breakpoints
342 # set at 'def' statements are moved one line onward
343 if line
[:3] == 'def':
360 elif c
in ('(','{','['):
361 brackets
= brackets
+ 1
362 elif c
in (')','}',']'):
363 brackets
= brackets
- 1
365 line
= linecache
.getline(filename
, lineno
)
370 if not line
: continue # Blank line
371 if brackets
<= 0 and line
[0] not in ('#','"',"'"):
375 def do_enable(self
, arg
):
381 print 'Breakpoint index %r is not a number' % i
384 if not (0 <= i
< len(bdb
.Breakpoint
.bpbynumber
)):
385 print 'No breakpoint numbered', i
388 bp
= bdb
.Breakpoint
.bpbynumber
[i
]
392 def do_disable(self
, arg
):
398 print 'Breakpoint index %r is not a number' % i
401 if not (0 <= i
< len(bdb
.Breakpoint
.bpbynumber
)):
402 print 'No breakpoint numbered', i
405 bp
= bdb
.Breakpoint
.bpbynumber
[i
]
409 def do_condition(self
, arg
):
410 # arg is breakpoint number and condition
411 args
= arg
.split(' ', 1)
412 bpnum
= int(args
[0].strip())
417 bp
= bdb
.Breakpoint
.bpbynumber
[bpnum
]
421 print 'Breakpoint', bpnum
,
422 print 'is now unconditional.'
424 def do_ignore(self
,arg
):
425 """arg is bp number followed by ignore count."""
427 bpnum
= int(args
[0].strip())
429 count
= int(args
[1].strip())
432 bp
= bdb
.Breakpoint
.bpbynumber
[bpnum
]
436 reply
= 'Will ignore next '
438 reply
= reply
+ '%d crossings' % count
440 reply
= reply
+ '1 crossing'
441 print reply
+ ' of breakpoint %d.' % bpnum
443 print 'Will stop next time breakpoint',
444 print bpnum
, 'is reached.'
446 def do_clear(self
, arg
):
447 """Three possibilities, tried in this order:
448 clear -> clear all breaks, ask for confirmation
449 clear file:lineno -> clear all breaks at file:lineno
450 clear bpno bpno ... -> clear breakpoints by number"""
453 reply
= raw_input('Clear all breaks? ')
456 reply
= reply
.strip().lower()
457 if reply
in ('y', 'yes'):
458 self
.clear_all_breaks()
461 # Make sure it works for "clear C:\foo\bar.py:12"
468 err
= "Invalid line number (%s)" % arg
470 err
= self
.clear_break(filename
, lineno
)
471 if err
: print '***', err
473 numberlist
= arg
.split()
475 err
= self
.clear_bpbynumber(i
)
479 print 'Deleted breakpoint %s ' % (i
,)
480 do_cl
= do_clear
# 'c' is already an abbreviation for 'continue'
482 def do_where(self
, arg
):
483 self
.print_stack_trace()
487 def do_up(self
, arg
):
488 if self
.curindex
== 0:
489 print '*** Oldest frame'
491 self
.curindex
= self
.curindex
- 1
492 self
.curframe
= self
.stack
[self
.curindex
][0]
493 self
.print_stack_entry(self
.stack
[self
.curindex
])
497 def do_down(self
, arg
):
498 if self
.curindex
+ 1 == len(self
.stack
):
499 print '*** Newest frame'
501 self
.curindex
= self
.curindex
+ 1
502 self
.curframe
= self
.stack
[self
.curindex
][0]
503 self
.print_stack_entry(self
.stack
[self
.curindex
])
507 def do_step(self
, arg
):
512 def do_next(self
, arg
):
513 self
.set_next(self
.curframe
)
517 def do_return(self
, arg
):
518 self
.set_return(self
.curframe
)
522 def do_continue(self
, arg
):
525 do_c
= do_cont
= do_continue
527 def do_jump(self
, arg
):
528 if self
.curindex
+ 1 != len(self
.stack
):
529 print "*** You can only jump within the bottom frame"
534 print "*** The 'jump' command requires a line number."
537 # Do the jump, fix up our copy of the stack, and display the
539 self
.curframe
.f_lineno
= arg
540 self
.stack
[self
.curindex
] = self
.stack
[self
.curindex
][0], arg
541 self
.print_stack_entry(self
.stack
[self
.curindex
])
542 except ValueError, e
:
543 print '*** Jump failed:', e
546 def do_debug(self
, arg
):
548 globals = self
.curframe
.f_globals
549 locals = self
.curframe
.f_locals
551 p
.prompt
= "(%s) " % self
.prompt
.strip()
552 print "ENTERING RECURSIVE DEBUGGER"
553 sys
.call_tracing(p
.run
, (arg
, globals, locals))
554 print "LEAVING RECURSIVE DEBUGGER"
555 sys
.settrace(self
.trace_dispatch
)
556 self
.lastcmd
= p
.lastcmd
558 def do_quit(self
, arg
):
564 def do_EOF(self
, arg
):
569 def do_args(self
, arg
):
574 if co
.co_flags
& 4: n
= n
+1
575 if co
.co_flags
& 8: n
= n
+1
577 name
= co
.co_varnames
[i
]
579 if name
in dict: print dict[name
]
580 else: print "*** undefined ***"
583 def do_retval(self
, arg
):
584 if '__return__' in self
.curframe
.f_locals
:
585 print self
.curframe
.f_locals
['__return__']
587 print '*** Not yet returned!'
590 def _getval(self
, arg
):
592 return eval(arg
, self
.curframe
.f_globals
,
593 self
.curframe
.f_locals
)
595 t
, v
= sys
.exc_info()[:2]
596 if isinstance(t
, str):
598 else: exc_type_name
= t
.__name
__
599 print '***', exc_type_name
+ ':', `v`
604 print repr(self
._getval
(arg
))
608 def do_pp(self
, arg
):
610 pprint
.pprint(self
._getval
(arg
))
614 def do_list(self
, arg
):
615 self
.lastcmd
= 'list'
619 x
= eval(arg
, {}, {})
620 if type(x
) == type(()):
625 # Assume it's a count
628 first
= max(1, int(x
) - 5)
630 print '*** Error in argument:', `arg`
632 elif self
.lineno
is None:
633 first
= max(1, self
.curframe
.f_lineno
- 5)
635 first
= self
.lineno
+ 1
638 filename
= self
.curframe
.f_code
.co_filename
639 breaklist
= self
.get_file_breaks(filename
)
641 for lineno
in range(first
, last
+1):
642 line
= linecache
.getline(filename
, lineno
)
647 s
= `lineno`
.rjust(3)
648 if len(s
) < 4: s
= s
+ ' '
649 if lineno
in breaklist
: s
= s
+ 'B'
651 if lineno
== self
.curframe
.f_lineno
:
653 print s
+ '\t' + line
,
655 except KeyboardInterrupt:
659 def do_whatis(self
, arg
):
661 value
= eval(arg
, self
.curframe
.f_globals
,
662 self
.curframe
.f_locals
)
664 t
, v
= sys
.exc_info()[:2]
665 if type(t
) == type(''):
667 else: exc_type_name
= t
.__name
__
668 print '***', exc_type_name
+ ':', `v`
672 try: code
= value
.func_code
675 print 'Function', code
.co_name
677 # Is it an instance method?
678 try: code
= value
.im_func
.func_code
681 print 'Method', code
.co_name
683 # None of the above...
686 def do_alias(self
, arg
):
689 keys
= self
.aliases
.keys()
692 print "%s = %s" % (alias
, self
.aliases
[alias
])
694 if args
[0] in self
.aliases
and len(args
) == 1:
695 print "%s = %s" % (args
[0], self
.aliases
[args
[0]])
697 self
.aliases
[args
[0]] = ' '.join(args
[1:])
699 def do_unalias(self
, arg
):
701 if len(args
) == 0: return
702 if args
[0] in self
.aliases
:
703 del self
.aliases
[args
[0]]
705 # Print a traceback starting at the top stack frame.
706 # The most recently entered frame is printed last;
707 # this is different from dbx and gdb, but consistent with
708 # the Python interpreter's stack trace.
709 # It is also consistent with the up/down commands (which are
710 # compatible with dbx and gdb: up moves towards 'main()'
711 # and down moves towards the most recent stack frame).
713 def print_stack_trace(self
):
715 for frame_lineno
in self
.stack
:
716 self
.print_stack_entry(frame_lineno
)
717 except KeyboardInterrupt:
720 def print_stack_entry(self
, frame_lineno
, prompt_prefix
=line_prefix
):
721 frame
, lineno
= frame_lineno
722 if frame
is self
.curframe
:
726 print self
.format_stack_entry(frame_lineno
, prompt_prefix
)
729 # Help methods (derived from pdb.doc)
736 Without argument, print the list of available commands.
737 With a command name as argument, print help about that command
738 "help pdb" pipes the full documentation file to the $PAGER
739 "help exec" gives help on the ! command"""
741 def help_where(self
):
746 Print a stack trace, with the most recent frame at the bottom.
747 An arrow indicates the "current frame", which determines the
748 context of most commands. 'bt' is an alias for this command."""
757 Move the current frame one level down in the stack trace
758 (to an older frame)."""
765 Move the current frame one level up in the stack trace
766 (to a newer frame)."""
768 def help_break(self
):
772 print """b(reak) ([file:]lineno | function) [, condition]
773 With a line number argument, set a break there in the current
774 file. With a function name, set a break at first executable line
775 of that function. Without argument, list all breaks. If a second
776 argument is present, it is a string specifying an expression
777 which must evaluate to true before the breakpoint is honored.
779 The line number may be prefixed with a filename and a colon,
780 to specify a breakpoint in another file (probably one that
781 hasn't been loaded yet). The file is searched for on sys.path;
782 the .py suffix may be omitted."""
784 def help_clear(self
):
788 print "cl(ear) filename:lineno"
789 print """cl(ear) [bpnumber [bpnumber...]]
790 With a space separated list of breakpoint numbers, clear
791 those breakpoints. Without argument, clear all breaks (but
792 first ask confirmation). With a filename:lineno argument,
793 clear all breaks at that line in that file.
795 Note that the argument is different from previous versions of
796 the debugger (in python distributions 1.5.1 and before) where
797 a linenumber was used instead of either filename:lineno or
798 breakpoint numbers."""
800 def help_tbreak(self
):
801 print """tbreak same arguments as break, but breakpoint is
802 removed when first hit."""
804 def help_enable(self
):
805 print """enable bpnumber [bpnumber ...]
806 Enables the breakpoints given as a space separated list of
809 def help_disable(self
):
810 print """disable bpnumber [bpnumber ...]
811 Disables the breakpoints given as a space separated list of
814 def help_ignore(self
):
815 print """ignore bpnumber count
816 Sets the ignore count for the given breakpoint number. A breakpoint
817 becomes active when the ignore count is zero. When non-zero, the
818 count is decremented each time the breakpoint is reached and the
819 breakpoint is not disabled and any associated condition evaluates
822 def help_condition(self
):
823 print """condition bpnumber str_condition
824 str_condition is a string specifying an expression which
825 must evaluate to true before the breakpoint is honored.
826 If str_condition is absent, any existing condition is removed;
827 i.e., the breakpoint is made unconditional."""
834 Execute the current line, stop at the first possible occasion
835 (either in a function that is called or in the current function)."""
842 Continue execution until the next line in the current function
843 is reached or it returns."""
845 def help_return(self
):
850 Continue execution until the current function returns."""
852 def help_continue(self
):
859 print """c(ont(inue))
860 Continue execution, only stop when a breakpoint is encountered."""
866 print """j(ump) lineno
867 Set the next line that will be executed."""
869 def help_debug(self
):
871 Enter a recursive debugger that steps through the code argument
872 (which is an arbitrary expression or statement to be executed
873 in the current environment)."""
879 print """l(ist) [first [,last]]
880 List source code for the current file.
881 Without arguments, list 11 lines around the current line
882 or continue the previous listing.
883 With one argument, list 11 lines starting at that line.
884 With two arguments, list the given range;
885 if the second argument is less than the first, it is a count."""
892 Print the arguments of the current function."""
895 print """p expression
896 Print the value of the expression."""
899 print """pp expression
900 Pretty-print the value of the expression."""
903 print """(!) statement
904 Execute the (one-line) statement in the context of
905 the current stack frame.
906 The exclamation point can be omitted unless the first word
907 of the statement resembles a debugger command.
908 To assign to a global variable you must always prefix the
909 command with a 'global' command, e.g.:
910 (Pdb) global list_options; list_options = ['-l']
917 print """q(uit) or exit - Quit from the debugger.
918 The program being executed is aborted."""
922 def help_whatis(self
):
924 Prints the type of the argument."""
928 Handles the receipt of EOF as a command."""
930 def help_alias(self
):
931 print """alias [name [command [parameter parameter ...] ]]
932 Creates an alias called 'name' the executes 'command'. The command
933 must *not* be enclosed in quotes. Replaceable parameters are
934 indicated by %1, %2, and so on, while %* is replaced by all the
935 parameters. If no command is given, the current alias for name
936 is shown. If no name is given, all aliases are listed.
938 Aliases may be nested and can contain anything that can be
939 legally typed at the pdb prompt. Note! You *can* override
940 internal pdb commands with aliases! Those internal commands
941 are then hidden until the alias is removed. Aliasing is recursively
942 applied to the first word of the command line; all other words
943 in the line are left alone.
945 Some useful aliases (especially when placed in the .pdbrc file) are:
947 #Print instance variables (usage "pi classInst")
948 alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
950 #Print instance variables in self
954 def help_unalias(self
):
955 print """unalias name
956 Deletes the specified alias."""
961 def lookupmodule(self
, filename
):
962 """Helper function for break/clear parsing -- may be overridden."""
963 root
, ext
= os
.path
.splitext(filename
)
965 filename
= filename
+ '.py'
966 if os
.path
.isabs(filename
):
968 for dirname
in sys
.path
:
969 while os
.path
.islink(dirname
):
970 dirname
= os
.readlink(dirname
)
971 fullname
= os
.path
.join(dirname
, filename
)
972 if os
.path
.exists(fullname
):
976 # Simplified interface
978 def run(statement
, globals=None, locals=None):
979 Pdb().run(statement
, globals, locals)
981 def runeval(expression
, globals=None, locals=None):
982 return Pdb().runeval(expression
, globals, locals)
984 def runctx(statement
, globals, locals):
986 run(statement
, globals, locals)
989 return Pdb().runcall(*args
)
994 # Post-Mortem interface
999 while t
.tb_next
is not None:
1001 p
.interaction(t
.tb_frame
, t
)
1004 post_mortem(sys
.last_traceback
)
1007 # Main program for testing
1009 TESTCMD
= 'import x; x.main()'
1016 for dirname
in sys
.path
:
1017 fullname
= os
.path
.join(dirname
, 'pdb.doc')
1018 if os
.path
.exists(fullname
):
1019 sts
= os
.system('${PAGER-more} '+fullname
)
1020 if sts
: print '*** Pager exit status:', sts
1023 print 'Sorry, can\'t find the help file "pdb.doc"',
1024 print 'along the Python search path'
1029 # When invoked as main program, invoke the debugger on a script
1030 if __name__
=='__main__':
1031 if not sys
.argv
[1:]:
1032 print "usage: pdb.py scriptfile [arg] ..."
1035 mainpyfile
= filename
= sys
.argv
[1] # Get script filename
1036 if not os
.path
.exists(filename
):
1037 print 'Error:', `filename`
, 'does not exist'
1039 mainmodule
= os
.path
.basename(filename
)
1040 del sys
.argv
[0] # Hide "pdb.py" from argument list
1042 # Insert script directory in front of module search path
1043 sys
.path
.insert(0, os
.path
.dirname(filename
))
1045 run('execfile(' + `filename`
+ ')')