3 """A Python debugger."""
5 # (See pdb.doc for documentation.)
11 from repr import repr as _saferepr
15 __all__
= ["run", "pm", "Pdb", "runeval", "runctx", "runcall", "set_trace",
16 "post_mortem", "help"]
18 def find_function(funcname
, filename
):
19 cre
= re
.compile(r
'def\s+%s\s*[(]' % funcname
)
24 # consumer of this info expects the first line to be 1
32 answer
= funcname
, filename
, lineno
39 # Interaction prompt line will separate file and call info from code
40 # text using value of line_prefix string. A newline and arrow may
41 # be to your liking. You can set it once pdb is imported using the
42 # command "pdb.line_prefix = '\n% '".
43 # line_prefix = ': ' # Use this to get the old situation back
44 line_prefix
= '\n-> ' # Probably a better default
46 class Pdb(bdb
.Bdb
, cmd
.Cmd
):
49 bdb
.Bdb
.__init
__(self
)
50 cmd
.Cmd
.__init
__(self
)
51 self
.prompt
= '(Pdb) '
53 # Try to load readline if it exists
59 # Read $HOME/.pdbrc and ./.pdbrc
61 if os
.environ
.has_key('HOME'):
62 envHome
= os
.environ
['HOME']
64 rcFile
= open(os
.path
.join(envHome
, ".pdbrc"))
68 for line
in rcFile
.readlines():
69 self
.rcLines
.append(line
)
72 rcFile
= open(".pdbrc")
76 for line
in rcFile
.readlines():
77 self
.rcLines
.append(line
)
90 def setup(self
, f
, t
):
92 self
.stack
, self
.curindex
= self
.get_stack(f
, t
)
93 self
.curframe
= self
.stack
[self
.curindex
][0]
96 # Can be executed earlier than 'setup' if desired
97 def execRcLines(self
):
99 # Make local copy because of recursion
100 rcLines
= self
.rcLines
105 if len (line
) > 0 and line
[0] != '#':
108 # Override Bdb methods (except user_call, for now)
110 def user_line(self
, frame
):
111 """This function is called when we stop or break at this line."""
112 self
.interaction(frame
, None)
114 def user_return(self
, frame
, return_value
):
115 """This function is called when a return trap is set here."""
116 frame
.f_locals
['__return__'] = return_value
118 self
.interaction(frame
, None)
120 def user_exception(self
, frame
, (exc_type
, exc_value
, exc_traceback
)):
121 """This function is called if an exception occurs,
122 but only if we are to stop at or just below this level."""
123 frame
.f_locals
['__exception__'] = exc_type
, exc_value
124 if type(exc_type
) == type(''):
125 exc_type_name
= exc_type
126 else: exc_type_name
= exc_type
.__name
__
127 print exc_type_name
+ ':', _saferepr(exc_value
)
128 self
.interaction(frame
, exc_traceback
)
130 # General interaction function
132 def interaction(self
, frame
, traceback
):
133 self
.setup(frame
, traceback
)
134 self
.print_stack_entry(self
.stack
[self
.curindex
])
138 def default(self
, line
):
139 if line
[:1] == '!': line
= line
[1:]
140 locals = self
.curframe
.f_locals
141 globals = self
.curframe
.f_globals
143 code
= compile(line
+ '\n', '<stdin>', 'single')
144 exec code
in globals, locals
146 t
, v
= sys
.exc_info()[:2]
147 if type(t
) == type(''):
149 else: exc_type_name
= t
.__name
__
150 print '***', exc_type_name
+ ':', v
152 def precmd(self
, line
):
153 """Handle alias expansion and ';;' separator."""
157 while self
.aliases
.has_key(args
[0]):
158 line
= self
.aliases
[args
[0]]
160 for tmpArg
in args
[1:]:
161 line
= line
.replace("%" + str(ii
),
164 line
= line
.replace("%*", ' '.join(args
[1:]))
166 # split into ';;' separated commands
167 # unless it's an alias command
168 if args
[0] != 'alias':
169 marker
= line
.find(';;')
171 # queue up everything after marker
172 next
= line
[marker
+2:].lstrip()
173 self
.cmdqueue
.append(next
)
174 line
= line
[:marker
].rstrip()
177 # Command definitions, called by cmdloop()
178 # The argument is the remaining string on the command line
179 # Return true to exit from the command loop
181 do_h
= cmd
.Cmd
.do_help
183 def do_EOF(self
, arg
):
184 return 0 # Don't die on EOF
186 def do_break(self
, arg
, temporary
= 0):
187 # break [ ([filename:]lineno | function) [, "condition"] ]
189 if self
.breaks
: # There's at least one
190 print "Num Type Disp Enb Where"
191 for bp
in bdb
.Breakpoint
.bpbynumber
:
195 # parse arguments; comma has lowest precedence
196 # and cannot occur in filename
200 comma
= arg
.find(',')
202 # parse stuff after comma: "condition"
203 cond
= arg
[comma
+1:].lstrip()
204 arg
= arg
[:comma
].rstrip()
205 # parse stuff before comma: [filename:]lineno | function
206 colon
= arg
.rfind(':')
208 filename
= arg
[:colon
].rstrip()
209 f
= self
.lookupmodule(filename
)
211 print '*** ', `filename`
,
212 print 'not found from sys.path'
216 arg
= arg
[colon
+1:].lstrip()
219 except ValueError, msg
:
220 print '*** Bad lineno:', arg
223 # no colon; can be lineno or function
229 self
.curframe
.f_globals
,
230 self
.curframe
.f_locals
)
234 if hasattr(func
, 'im_func'):
236 code
= func
.func_code
237 lineno
= code
.co_firstlineno
238 filename
= code
.co_filename
241 (ok
, filename
, ln
) = self
.lineinfo(arg
)
243 print '*** The specified object',
245 print 'is not a function'
246 print ('or was not found '
251 filename
= self
.defaultFile()
252 # Check for reasonable breakpoint
253 line
= self
.checkline(filename
, lineno
)
255 # now set the break point
256 err
= self
.set_break(filename
, line
, temporary
, cond
)
257 if err
: print '***', err
259 bp
= self
.get_breaks(filename
, line
)[-1]
260 print "Breakpoint %d at %s:%d" % (bp
.number
,
264 # To be overridden in derived debuggers
265 def defaultFile(self
):
266 """Produce a reasonable default."""
267 filename
= self
.curframe
.f_code
.co_filename
268 if filename
== '<string>' and mainpyfile
:
269 filename
= mainpyfile
274 def do_tbreak(self
, arg
):
275 self
.do_break(arg
, 1)
277 def lineinfo(self
, identifier
):
278 failed
= (None, None, None)
279 # Input is identifier, may be in single quotes
280 idstring
= identifier
.split("'")
281 if len(idstring
) == 1:
282 # not in single quotes
283 id = idstring
[0].strip()
284 elif len(idstring
) == 3:
286 id = idstring
[1].strip()
289 if id == '': return failed
290 parts
= id.split('.')
291 # Protection for derived debuggers
292 if parts
[0] == 'self':
296 # Best first guess at file to look at
297 fname
= self
.defaultFile()
301 # More than one part.
302 # First is module, second is method/class
303 f
= self
.lookupmodule(parts
[0])
307 answer
= find_function(item
, fname
)
308 return answer
or failed
310 def checkline(self
, filename
, lineno
):
311 """Return line number of first line at or after input
312 argument such that if the input points to a 'def', the
313 returned line number is the first
314 non-blank/non-comment line to follow. If the input
315 points to a blank or comment line, return 0. At end
316 of file, also return 0."""
318 line
= linecache
.getline(filename
, lineno
)
323 # Don't allow setting breakpoint at a blank line
324 if ( not line
or (line
[0] == '#') or
325 (line
[:3] == '"""') or line
[:3] == "'''" ):
326 print '*** Blank or comment'
328 # When a file is read in and a breakpoint is at
329 # the 'def' statement, the system stops there at
330 # code parse time. We don't want that, so all breakpoints
331 # set at 'def' statements are moved one line onward
332 if line
[:3] == 'def':
349 elif c
in ('(','{','['):
350 brackets
= brackets
+ 1
351 elif c
in (')','}',']'):
352 brackets
= brackets
- 1
354 line
= linecache
.getline(filename
, lineno
)
359 if not line
: continue # Blank line
360 if brackets
<= 0 and line
[0] not in ('#','"',"'"):
364 def do_enable(self
, arg
):
367 bp
= bdb
.Breakpoint
.bpbynumber
[int(i
)]
371 def do_disable(self
, arg
):
374 bp
= bdb
.Breakpoint
.bpbynumber
[int(i
)]
378 def do_condition(self
, arg
):
379 # arg is breakpoint number and condition
380 args
= arg
.split(' ', 1)
381 bpnum
= int(args
[0].strip())
386 bp
= bdb
.Breakpoint
.bpbynumber
[bpnum
]
390 print 'Breakpoint', bpnum
,
391 print 'is now unconditional.'
393 def do_ignore(self
,arg
):
394 """arg is bp number followed by ignore count."""
396 bpnum
= int(args
[0].strip())
398 count
= int(args
[1].strip())
401 bp
= bdb
.Breakpoint
.bpbynumber
[bpnum
]
405 reply
= 'Will ignore next '
407 reply
= reply
+ '%d crossings' % count
409 reply
= reply
+ '1 crossing'
410 print reply
+ ' of breakpoint %d.' % bpnum
412 print 'Will stop next time breakpoint',
413 print bpnum
, 'is reached.'
415 def do_clear(self
, arg
):
416 """Three possibilities, tried in this order:
417 clear -> clear all breaks, ask for confirmation
418 clear file:lineno -> clear all breaks at file:lineno
419 clear bpno bpno ... -> clear breakpoints by number"""
422 reply
= raw_input('Clear all breaks? ')
425 reply
= reply
.strip().lower()
426 if reply
in ('y', 'yes'):
427 self
.clear_all_breaks()
430 # Make sure it works for "clear C:\foo\bar.py:12"
437 err
= "Invalid line number (%s)" % arg
439 err
= self
.clear_break(filename
, lineno
)
440 if err
: print '***', err
442 numberlist
= arg
.split()
444 err
= self
.clear_bpbynumber(i
)
448 print 'Deleted breakpoint %s ' % (i
,)
449 do_cl
= do_clear
# 'c' is already an abbreviation for 'continue'
451 def do_where(self
, arg
):
452 self
.print_stack_trace()
456 def do_up(self
, arg
):
457 if self
.curindex
== 0:
458 print '*** Oldest frame'
460 self
.curindex
= self
.curindex
- 1
461 self
.curframe
= self
.stack
[self
.curindex
][0]
462 self
.print_stack_entry(self
.stack
[self
.curindex
])
466 def do_down(self
, arg
):
467 if self
.curindex
+ 1 == len(self
.stack
):
468 print '*** Newest frame'
470 self
.curindex
= self
.curindex
+ 1
471 self
.curframe
= self
.stack
[self
.curindex
][0]
472 self
.print_stack_entry(self
.stack
[self
.curindex
])
476 def do_step(self
, arg
):
481 def do_next(self
, arg
):
482 self
.set_next(self
.curframe
)
486 def do_return(self
, arg
):
487 self
.set_return(self
.curframe
)
491 def do_continue(self
, arg
):
494 do_c
= do_cont
= do_continue
496 def do_quit(self
, arg
):
501 def do_args(self
, arg
):
506 if co
.co_flags
& 4: n
= n
+1
507 if co
.co_flags
& 8: n
= n
+1
509 name
= co
.co_varnames
[i
]
511 if dict.has_key(name
): print dict[name
]
512 else: print "*** undefined ***"
515 def do_retval(self
, arg
):
516 if self
.curframe
.f_locals
.has_key('__return__'):
517 print self
.curframe
.f_locals
['__return__']
519 print '*** Not yet returned!'
524 value
= eval(arg
, self
.curframe
.f_globals
,
525 self
.curframe
.f_locals
)
527 t
, v
= sys
.exc_info()[:2]
528 if type(t
) == type(''):
530 else: exc_type_name
= t
.__name
__
531 print '***', exc_type_name
+ ':', `v`
536 def do_list(self
, arg
):
537 self
.lastcmd
= 'list'
541 x
= eval(arg
, {}, {})
542 if type(x
) == type(()):
547 # Assume it's a count
550 first
= max(1, int(x
) - 5)
552 print '*** Error in argument:', `arg`
554 elif self
.lineno
is None:
555 first
= max(1, self
.curframe
.f_lineno
- 5)
557 first
= self
.lineno
+ 1
560 filename
= self
.curframe
.f_code
.co_filename
561 breaklist
= self
.get_file_breaks(filename
)
563 for lineno
in range(first
, last
+1):
564 line
= linecache
.getline(filename
, lineno
)
569 s
= `lineno`
.rjust(3)
570 if len(s
) < 4: s
= s
+ ' '
571 if lineno
in breaklist
: s
= s
+ 'B'
573 if lineno
== self
.curframe
.f_lineno
:
575 print s
+ '\t' + line
,
577 except KeyboardInterrupt:
581 def do_whatis(self
, arg
):
583 value
= eval(arg
, self
.curframe
.f_globals
,
584 self
.curframe
.f_locals
)
586 t
, v
= sys
.exc_info()[:2]
587 if type(t
) == type(''):
589 else: exc_type_name
= t
.__name
__
590 print '***', exc_type_name
+ ':', `v`
594 try: code
= value
.func_code
597 print 'Function', code
.co_name
599 # Is it an instance method?
600 try: code
= value
.im_func
.func_code
603 print 'Method', code
.co_name
605 # None of the above...
608 def do_alias(self
, arg
):
611 keys
= self
.aliases
.keys()
614 print "%s = %s" % (alias
, self
.aliases
[alias
])
616 if self
.aliases
.has_key(args
[0]) and len (args
) == 1:
617 print "%s = %s" % (args
[0], self
.aliases
[args
[0]])
619 self
.aliases
[args
[0]] = ' '.join(args
[1:])
621 def do_unalias(self
, arg
):
623 if len(args
) == 0: return
624 if self
.aliases
.has_key(args
[0]):
625 del self
.aliases
[args
[0]]
627 # Print a traceback starting at the top stack frame.
628 # The most recently entered frame is printed last;
629 # this is different from dbx and gdb, but consistent with
630 # the Python interpreter's stack trace.
631 # It is also consistent with the up/down commands (which are
632 # compatible with dbx and gdb: up moves towards 'main()'
633 # and down moves towards the most recent stack frame).
635 def print_stack_trace(self
):
637 for frame_lineno
in self
.stack
:
638 self
.print_stack_entry(frame_lineno
)
639 except KeyboardInterrupt:
642 def print_stack_entry(self
, frame_lineno
, prompt_prefix
=line_prefix
):
643 frame
, lineno
= frame_lineno
644 if frame
is self
.curframe
:
648 print self
.format_stack_entry(frame_lineno
, prompt_prefix
)
651 # Help methods (derived from pdb.doc)
658 Without argument, print the list of available commands.
659 With a command name as argument, print help about that command
660 "help pdb" pipes the full documentation file to the $PAGER
661 "help exec" gives help on the ! command"""
663 def help_where(self
):
668 Print a stack trace, with the most recent frame at the bottom.
669 An arrow indicates the "current frame", which determines the
670 context of most commands. 'bt' is an alias for this command."""
679 Move the current frame one level down in the stack trace
680 (to an older frame)."""
687 Move the current frame one level up in the stack trace
688 (to a newer frame)."""
690 def help_break(self
):
694 print """b(reak) ([file:]lineno | function) [, condition]
695 With a line number argument, set a break there in the current
696 file. With a function name, set a break at first executable line
697 of that function. Without argument, list all breaks. If a second
698 argument is present, it is a string specifying an expression
699 which must evaluate to true before the breakpoint is honored.
701 The line number may be prefixed with a filename and a colon,
702 to specify a breakpoint in another file (probably one that
703 hasn't been loaded yet). The file is searched for on sys.path;
704 the .py suffix may be omitted."""
706 def help_clear(self
):
710 print "cl(ear) filename:lineno"
711 print """cl(ear) [bpnumber [bpnumber...]]
712 With a space separated list of breakpoint numbers, clear
713 those breakpoints. Without argument, clear all breaks (but
714 first ask confirmation). With a filename:lineno argument,
715 clear all breaks at that line in that file.
717 Note that the argument is different from previous versions of
718 the debugger (in python distributions 1.5.1 and before) where
719 a linenumber was used instead of either filename:lineno or
720 breakpoint numbers."""
722 def help_tbreak(self
):
723 print """tbreak same arguments as break, but breakpoint is
724 removed when first hit."""
726 def help_enable(self
):
727 print """enable bpnumber [bpnumber ...]
728 Enables the breakpoints given as a space separated list of
731 def help_disable(self
):
732 print """disable bpnumber [bpnumber ...]
733 Disables the breakpoints given as a space separated list of
736 def help_ignore(self
):
737 print """ignore bpnumber count
738 Sets the ignore count for the given breakpoint number. A breakpoint
739 becomes active when the ignore count is zero. When non-zero, the
740 count is decremented each time the breakpoint is reached and the
741 breakpoint is not disabled and any associated condition evaluates
744 def help_condition(self
):
745 print """condition bpnumber str_condition
746 str_condition is a string specifying an expression which
747 must evaluate to true before the breakpoint is honored.
748 If str_condition is absent, any existing condition is removed;
749 i.e., the breakpoint is made unconditional."""
756 Execute the current line, stop at the first possible occasion
757 (either in a function that is called or in the current function)."""
764 Continue execution until the next line in the current function
765 is reached or it returns."""
767 def help_return(self
):
772 Continue execution until the current function returns."""
774 def help_continue(self
):
781 print """c(ont(inue))
782 Continue execution, only stop when a breakpoint is encountered."""
788 print """l(ist) [first [,last]]
789 List source code for the current file.
790 Without arguments, list 11 lines around the current line
791 or continue the previous listing.
792 With one argument, list 11 lines starting at that line.
793 With two arguments, list the given range;
794 if the second argument is less than the first, it is a count."""
801 Print the arguments of the current function."""
804 print """p expression
805 Print the value of the expression."""
808 print """(!) statement
809 Execute the (one-line) statement in the context of
810 the current stack frame.
811 The exclamation point can be omitted unless the first word
812 of the statement resembles a debugger command.
813 To assign to a global variable you must always prefix the
814 command with a 'global' command, e.g.:
815 (Pdb) global list_options; list_options = ['-l']
822 print """q(uit) Quit from the debugger.
823 The program being executed is aborted."""
825 def help_whatis(self
):
827 Prints the type of the argument."""
831 Handles the receipt of EOF as a command."""
833 def help_alias(self
):
834 print """alias [name [command [parameter parameter ...] ]]
835 Creates an alias called 'name' the executes 'command'. The command
836 must *not* be enclosed in quotes. Replaceable parameters are
837 indicated by %1, %2, and so on, while %* is replaced by all the
838 parameters. If no command is given, the current alias for name
839 is shown. If no name is given, all aliases are listed.
841 Aliases may be nested and can contain anything that can be
842 legally typed at the pdb prompt. Note! You *can* override
843 internal pdb commands with aliases! Those internal commands
844 are then hidden until the alias is removed. Aliasing is recursively
845 applied to the first word of the command line; all other words
846 in the line are left alone.
848 Some useful aliases (especially when placed in the .pdbrc file) are:
850 #Print instance variables (usage "pi classInst")
851 alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
853 #Print instance variables in self
857 def help_unalias(self
):
858 print """unalias name
859 Deletes the specified alias."""
864 def lookupmodule(self
, filename
):
865 """Helper function for break/clear parsing -- may be overridden."""
866 root
, ext
= os
.path
.splitext(filename
)
868 filename
= filename
+ '.py'
869 if os
.path
.isabs(filename
):
871 for dirname
in sys
.path
:
872 while os
.path
.islink(dirname
):
873 dirname
= os
.readlink(dirname
)
874 fullname
= os
.path
.join(dirname
, filename
)
875 if os
.path
.exists(fullname
):
879 # Simplified interface
881 def run(statement
, globals=None, locals=None):
882 Pdb().run(statement
, globals, locals)
884 def runeval(expression
, globals=None, locals=None):
885 return Pdb().runeval(expression
, globals, locals)
887 def runctx(statement
, globals, locals):
889 run(statement
, globals, locals)
892 return apply(Pdb().runcall
, args
)
897 # Post-Mortem interface
902 while t
.tb_next
is not None:
904 p
.interaction(t
.tb_frame
, t
)
907 post_mortem(sys
.last_traceback
)
910 # Main program for testing
912 TESTCMD
= 'import x; x.main()'
919 for dirname
in sys
.path
:
920 fullname
= os
.path
.join(dirname
, 'pdb.doc')
921 if os
.path
.exists(fullname
):
922 sts
= os
.system('${PAGER-more} '+fullname
)
923 if sts
: print '*** Pager exit status:', sts
926 print 'Sorry, can\'t find the help file "pdb.doc"',
927 print 'along the Python search path'
932 # When invoked as main program, invoke the debugger on a script
933 if __name__
=='__main__':
935 print "usage: pdb.py scriptfile [arg] ..."
938 mainpyfile
= filename
= sys
.argv
[1] # Get script filename
939 if not os
.path
.exists(filename
):
940 print 'Error:', `filename`
, 'does not exist'
942 mainmodule
= os
.path
.basename(filename
)
943 del sys
.argv
[0] # Hide "pdb.py" from argument list
945 # Insert script directory in front of module search path
946 sys
.path
.insert(0, os
.path
.dirname(filename
))
948 run('execfile(' + `filename`
+ ')')