3 """A Python debugger."""
5 # (See pdb.doc for documentation.)
18 class Restart(Exception):
19 """Causes a debugger to be restarted for the debugged python program."""
22 # Create a custom safe Repr instance and increase its maxstring.
23 # The default of 30 truncates error messages too easily.
26 _saferepr
= _repr
.repr
28 __all__
= ["run", "pm", "Pdb", "runeval", "runctx", "runcall", "set_trace",
29 "post_mortem", "help"]
31 def find_function(funcname
, filename
):
32 cre
= re
.compile(r
'def\s+%s\s*[(]' % re
.escape(funcname
))
37 # consumer of this info expects the first line to be 1
45 answer
= funcname
, filename
, lineno
52 # Interaction prompt line will separate file and call info from code
53 # text using value of line_prefix string. A newline and arrow may
54 # be to your liking. You can set it once pdb is imported using the
55 # command "pdb.line_prefix = '\n% '".
56 # line_prefix = ': ' # Use this to get the old situation back
57 line_prefix
= '\n-> ' # Probably a better default
59 class Pdb(bdb
.Bdb
, cmd
.Cmd
):
61 def __init__(self
, completekey
='tab', stdin
=None, stdout
=None):
62 bdb
.Bdb
.__init
__(self
)
63 cmd
.Cmd
.__init
__(self
, completekey
, stdin
, stdout
)
66 self
.prompt
= '(Pdb) '
69 self
._wait
_for
_mainpyfile
= 0
70 # Try to load readline if it exists
76 # Read $HOME/.pdbrc and ./.pdbrc
78 if 'HOME' in os
.environ
:
79 envHome
= os
.environ
['HOME']
81 rcFile
= open(os
.path
.join(envHome
, ".pdbrc"))
85 for line
in rcFile
.readlines():
86 self
.rcLines
.append(line
)
89 rcFile
= open(".pdbrc")
93 for line
in rcFile
.readlines():
94 self
.rcLines
.append(line
)
97 self
.commands
= {} # associates a command list to breakpoint numbers
98 self
.commands_doprompt
= {} # for each bp num, tells if the prompt must be disp. after execing the cmd list
99 self
.commands_silent
= {} # for each bp num, tells if the stack trace must be disp. after execing the cmd list
100 self
.commands_defining
= False # True while in the process of defining a command list
101 self
.commands_bnum
= None # The breakpoint number for which we are defining a list
113 def setup(self
, f
, t
):
115 self
.stack
, self
.curindex
= self
.get_stack(f
, t
)
116 self
.curframe
= self
.stack
[self
.curindex
][0]
119 # Can be executed earlier than 'setup' if desired
120 def execRcLines(self
):
122 # Make local copy because of recursion
123 rcLines
= self
.rcLines
128 if len(line
) > 0 and line
[0] != '#':
131 # Override Bdb methods
133 def user_call(self
, frame
, argument_list
):
134 """This method is called when there is the remote possibility
135 that we ever need to stop in this function."""
136 if self
._wait
_for
_mainpyfile
:
138 if self
.stop_here(frame
):
139 print >>self
.stdout
, '--Call--'
140 self
.interaction(frame
, None)
142 def user_line(self
, frame
):
143 """This function is called when we stop or break at this line."""
144 if self
._wait
_for
_mainpyfile
:
145 if (self
.mainpyfile
!= self
.canonic(frame
.f_code
.co_filename
)
146 or frame
.f_lineno
<= 0):
148 self
._wait
_for
_mainpyfile
= 0
149 if self
.bp_commands(frame
):
150 self
.interaction(frame
, None)
152 def bp_commands(self
,frame
):
153 """ Call every command that was set for the current active breakpoint (if there is one)
154 Returns True if the normal interaction function must be called, False otherwise """
155 #self.currentbp is set in bdb.py in bdb.break_here if a breakpoint was hit
156 if getattr(self
,"currentbp",False) and self
.currentbp
in self
.commands
:
157 currentbp
= self
.currentbp
159 lastcmd_back
= self
.lastcmd
160 self
.setup(frame
, None)
161 for line
in self
.commands
[currentbp
]:
163 self
.lastcmd
= lastcmd_back
164 if not self
.commands_silent
[currentbp
]:
165 self
.print_stack_entry(self
.stack
[self
.curindex
])
166 if self
.commands_doprompt
[currentbp
]:
172 def user_return(self
, frame
, return_value
):
173 """This function is called when a return trap is set here."""
174 frame
.f_locals
['__return__'] = return_value
175 print >>self
.stdout
, '--Return--'
176 self
.interaction(frame
, None)
178 def user_exception(self
, frame
, (exc_type
, exc_value
, exc_traceback
)):
179 """This function is called if an exception occurs,
180 but only if we are to stop at or just below this level."""
181 frame
.f_locals
['__exception__'] = exc_type
, exc_value
182 if type(exc_type
) == type(''):
183 exc_type_name
= exc_type
184 else: exc_type_name
= exc_type
.__name
__
185 print >>self
.stdout
, exc_type_name
+ ':', _saferepr(exc_value
)
186 self
.interaction(frame
, exc_traceback
)
188 # General interaction function
190 def interaction(self
, frame
, traceback
):
191 self
.setup(frame
, traceback
)
192 self
.print_stack_entry(self
.stack
[self
.curindex
])
196 def default(self
, line
):
197 if line
[:1] == '!': line
= line
[1:]
198 locals = self
.curframe
.f_locals
199 globals = self
.curframe
.f_globals
201 code
= compile(line
+ '\n', '<stdin>', 'single')
202 exec code
in globals, locals
204 t
, v
= sys
.exc_info()[:2]
205 if type(t
) == type(''):
207 else: exc_type_name
= t
.__name
__
208 print >>self
.stdout
, '***', exc_type_name
+ ':', v
210 def precmd(self
, line
):
211 """Handle alias expansion and ';;' separator."""
215 while args
[0] in self
.aliases
:
216 line
= self
.aliases
[args
[0]]
218 for tmpArg
in args
[1:]:
219 line
= line
.replace("%" + str(ii
),
222 line
= line
.replace("%*", ' '.join(args
[1:]))
224 # split into ';;' separated commands
225 # unless it's an alias command
226 if args
[0] != 'alias':
227 marker
= line
.find(';;')
229 # queue up everything after marker
230 next
= line
[marker
+2:].lstrip()
231 self
.cmdqueue
.append(next
)
232 line
= line
[:marker
].rstrip()
235 def onecmd(self
, line
):
236 """Interpret the argument as though it had been typed in response
239 Checks whether this line is typed at the normal prompt or in
240 a breakpoint command list definition.
242 if not self
.commands_defining
:
243 return cmd
.Cmd
.onecmd(self
, line
)
245 return self
.handle_command_def(line
)
247 def handle_command_def(self
,line
):
248 """ Handles one command line during command list definition. """
249 cmd
, arg
, line
= self
.parseline(line
)
251 self
.commands_silent
[self
.commands_bnum
] = True
252 return # continue to handle other cmd def in the cmd list
255 return 1 # end of cmd list
256 cmdlist
= self
.commands
[self
.commands_bnum
]
258 cmdlist
.append(cmd
+' '+arg
)
261 # Determine if we must stop
263 func
= getattr(self
, 'do_' + cmd
)
264 except AttributeError:
266 if func
.func_name
in self
.commands_resuming
: # one of the resuming commands.
267 self
.commands_doprompt
[self
.commands_bnum
] = False
272 # Command definitions, called by cmdloop()
273 # The argument is the remaining string on the command line
274 # Return true to exit from the command loop
276 do_h
= cmd
.Cmd
.do_help
278 def do_commands(self
, arg
):
279 """Defines a list of commands associated to a breakpoint
280 Those commands will be executed whenever the breakpoint causes the program to stop execution."""
282 bnum
= len(bdb
.Breakpoint
.bpbynumber
)-1
287 print >>self
.stdout
, "Usage : commands [bnum]\n ...\n end"
289 self
.commands_bnum
= bnum
290 self
.commands
[bnum
] = []
291 self
.commands_doprompt
[bnum
] = True
292 self
.commands_silent
[bnum
] = False
293 prompt_back
= self
.prompt
294 self
.prompt
= '(com) '
295 self
.commands_defining
= True
297 self
.commands_defining
= False
298 self
.prompt
= prompt_back
300 def do_break(self
, arg
, temporary
= 0):
301 # break [ ([filename:]lineno | function) [, "condition"] ]
303 if self
.breaks
: # There's at least one
304 print >>self
.stdout
, "Num Type Disp Enb Where"
305 for bp
in bdb
.Breakpoint
.bpbynumber
:
307 bp
.bpprint(self
.stdout
)
309 # parse arguments; comma has lowest precedence
310 # and cannot occur in filename
314 comma
= arg
.find(',')
316 # parse stuff after comma: "condition"
317 cond
= arg
[comma
+1:].lstrip()
318 arg
= arg
[:comma
].rstrip()
319 # parse stuff before comma: [filename:]lineno | function
320 colon
= arg
.rfind(':')
323 filename
= arg
[:colon
].rstrip()
324 f
= self
.lookupmodule(filename
)
326 print >>self
.stdout
, '*** ', repr(filename
),
327 print >>self
.stdout
, 'not found from sys.path'
331 arg
= arg
[colon
+1:].lstrip()
334 except ValueError, msg
:
335 print >>self
.stdout
, '*** Bad lineno:', arg
338 # no colon; can be lineno or function
344 self
.curframe
.f_globals
,
345 self
.curframe
.f_locals
)
349 if hasattr(func
, 'im_func'):
351 code
= func
.func_code
352 #use co_name to identify the bkpt (function names
353 #could be aliased, but co_name is invariant)
354 funcname
= code
.co_name
355 lineno
= code
.co_firstlineno
356 filename
= code
.co_filename
359 (ok
, filename
, ln
) = self
.lineinfo(arg
)
361 print >>self
.stdout
, '*** The specified object',
362 print >>self
.stdout
, repr(arg
),
363 print >>self
.stdout
, 'is not a function'
364 print >>self
.stdout
, 'or was not found along sys.path.'
366 funcname
= ok
# ok contains a function name
369 filename
= self
.defaultFile()
370 # Check for reasonable breakpoint
371 line
= self
.checkline(filename
, lineno
)
373 # now set the break point
374 err
= self
.set_break(filename
, line
, temporary
, cond
, funcname
)
375 if err
: print >>self
.stdout
, '***', err
377 bp
= self
.get_breaks(filename
, line
)[-1]
378 print >>self
.stdout
, "Breakpoint %d at %s:%d" % (bp
.number
,
382 # To be overridden in derived debuggers
383 def defaultFile(self
):
384 """Produce a reasonable default."""
385 filename
= self
.curframe
.f_code
.co_filename
386 if filename
== '<string>' and self
.mainpyfile
:
387 filename
= self
.mainpyfile
392 def do_tbreak(self
, arg
):
393 self
.do_break(arg
, 1)
395 def lineinfo(self
, identifier
):
396 failed
= (None, None, None)
397 # Input is identifier, may be in single quotes
398 idstring
= identifier
.split("'")
399 if len(idstring
) == 1:
400 # not in single quotes
401 id = idstring
[0].strip()
402 elif len(idstring
) == 3:
404 id = idstring
[1].strip()
407 if id == '': return failed
408 parts
= id.split('.')
409 # Protection for derived debuggers
410 if parts
[0] == 'self':
414 # Best first guess at file to look at
415 fname
= self
.defaultFile()
419 # More than one part.
420 # First is module, second is method/class
421 f
= self
.lookupmodule(parts
[0])
425 answer
= find_function(item
, fname
)
426 return answer
or failed
428 def checkline(self
, filename
, lineno
):
429 """Check whether specified line seems to be executable.
431 Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
432 line or EOF). Warning: testing is not comprehensive.
434 line
= linecache
.getline(filename
, lineno
)
436 print >>self
.stdout
, 'End of file'
439 # Don't allow setting breakpoint at a blank line
440 if (not line
or (line
[0] == '#') or
441 (line
[:3] == '"""') or line
[:3] == "'''"):
442 print >>self
.stdout
, '*** Blank or comment'
446 def do_enable(self
, arg
):
452 print >>self
.stdout
, 'Breakpoint index %r is not a number' % i
455 if not (0 <= i
< len(bdb
.Breakpoint
.bpbynumber
)):
456 print >>self
.stdout
, 'No breakpoint numbered', i
459 bp
= bdb
.Breakpoint
.bpbynumber
[i
]
463 def do_disable(self
, arg
):
469 print >>self
.stdout
, 'Breakpoint index %r is not a number' % i
472 if not (0 <= i
< len(bdb
.Breakpoint
.bpbynumber
)):
473 print >>self
.stdout
, 'No breakpoint numbered', i
476 bp
= bdb
.Breakpoint
.bpbynumber
[i
]
480 def do_condition(self
, arg
):
481 # arg is breakpoint number and condition
482 args
= arg
.split(' ', 1)
484 bpnum
= int(args
[0].strip())
486 # something went wrong
487 print >>self
.stdout
, \
488 'Breakpoint index %r is not a number' % args
[0]
495 bp
= bdb
.Breakpoint
.bpbynumber
[bpnum
]
497 print >>self
.stdout
, 'Breakpoint index %r is not valid' % args
[0]
502 print >>self
.stdout
, 'Breakpoint', bpnum
,
503 print >>self
.stdout
, 'is now unconditional.'
505 def do_ignore(self
,arg
):
506 """arg is bp number followed by ignore count."""
509 bpnum
= int(args
[0].strip())
511 # something went wrong
512 print >>self
.stdout
, \
513 'Breakpoint index %r is not a number' % args
[0]
516 count
= int(args
[1].strip())
520 bp
= bdb
.Breakpoint
.bpbynumber
[bpnum
]
522 print >>self
.stdout
, 'Breakpoint index %r is not valid' % args
[0]
527 reply
= 'Will ignore next '
529 reply
= reply
+ '%d crossings' % count
531 reply
= reply
+ '1 crossing'
532 print >>self
.stdout
, reply
+ ' of breakpoint %d.' % bpnum
534 print >>self
.stdout
, 'Will stop next time breakpoint',
535 print >>self
.stdout
, bpnum
, 'is reached.'
537 def do_clear(self
, arg
):
538 """Three possibilities, tried in this order:
539 clear -> clear all breaks, ask for confirmation
540 clear file:lineno -> clear all breaks at file:lineno
541 clear bpno bpno ... -> clear breakpoints by number"""
544 reply
= raw_input('Clear all breaks? ')
547 reply
= reply
.strip().lower()
548 if reply
in ('y', 'yes'):
549 self
.clear_all_breaks()
552 # Make sure it works for "clear C:\foo\bar.py:12"
559 err
= "Invalid line number (%s)" % arg
561 err
= self
.clear_break(filename
, lineno
)
562 if err
: print >>self
.stdout
, '***', err
564 numberlist
= arg
.split()
569 print >>self
.stdout
, 'Breakpoint index %r is not a number' % i
572 if not (0 <= i
< len(bdb
.Breakpoint
.bpbynumber
)):
573 print >>self
.stdout
, 'No breakpoint numbered', i
575 err
= self
.clear_bpbynumber(i
)
577 print >>self
.stdout
, '***', err
579 print >>self
.stdout
, 'Deleted breakpoint', i
580 do_cl
= do_clear
# 'c' is already an abbreviation for 'continue'
582 def do_where(self
, arg
):
583 self
.print_stack_trace()
587 def do_up(self
, arg
):
588 if self
.curindex
== 0:
589 print >>self
.stdout
, '*** Oldest frame'
591 self
.curindex
= self
.curindex
- 1
592 self
.curframe
= self
.stack
[self
.curindex
][0]
593 self
.print_stack_entry(self
.stack
[self
.curindex
])
597 def do_down(self
, arg
):
598 if self
.curindex
+ 1 == len(self
.stack
):
599 print >>self
.stdout
, '*** Newest frame'
601 self
.curindex
= self
.curindex
+ 1
602 self
.curframe
= self
.stack
[self
.curindex
][0]
603 self
.print_stack_entry(self
.stack
[self
.curindex
])
607 def do_step(self
, arg
):
612 def do_next(self
, arg
):
613 self
.set_next(self
.curframe
)
617 def do_run(self
, arg
):
618 """Restart program by raising an exception to be caught in the main debugger
619 loop. If arguments were given, set them in sys.argv."""
622 argv0
= sys
.argv
[0:1]
623 sys
.argv
= shlex
.split(arg
)
629 def do_return(self
, arg
):
630 self
.set_return(self
.curframe
)
634 def do_continue(self
, arg
):
637 do_c
= do_cont
= do_continue
639 def do_jump(self
, arg
):
640 if self
.curindex
+ 1 != len(self
.stack
):
641 print >>self
.stdout
, "*** You can only jump within the bottom frame"
646 print >>self
.stdout
, "*** The 'jump' command requires a line number."
649 # Do the jump, fix up our copy of the stack, and display the
651 self
.curframe
.f_lineno
= arg
652 self
.stack
[self
.curindex
] = self
.stack
[self
.curindex
][0], arg
653 self
.print_stack_entry(self
.stack
[self
.curindex
])
654 except ValueError, e
:
655 print >>self
.stdout
, '*** Jump failed:', e
658 def do_debug(self
, arg
):
660 globals = self
.curframe
.f_globals
661 locals = self
.curframe
.f_locals
663 p
.prompt
= "(%s) " % self
.prompt
.strip()
664 print >>self
.stdout
, "ENTERING RECURSIVE DEBUGGER"
665 sys
.call_tracing(p
.run
, (arg
, globals, locals))
666 print >>self
.stdout
, "LEAVING RECURSIVE DEBUGGER"
667 sys
.settrace(self
.trace_dispatch
)
668 self
.lastcmd
= p
.lastcmd
670 def do_quit(self
, arg
):
671 self
._user
_requested
_quit
= 1
678 def do_EOF(self
, arg
):
680 self
._user
_requested
_quit
= 1
684 def do_args(self
, arg
):
689 if co
.co_flags
& 4: n
= n
+1
690 if co
.co_flags
& 8: n
= n
+1
692 name
= co
.co_varnames
[i
]
693 print >>self
.stdout
, name
, '=',
694 if name
in dict: print >>self
.stdout
, dict[name
]
695 else: print >>self
.stdout
, "*** undefined ***"
698 def do_retval(self
, arg
):
699 if '__return__' in self
.curframe
.f_locals
:
700 print >>self
.stdout
, self
.curframe
.f_locals
['__return__']
702 print >>self
.stdout
, '*** Not yet returned!'
705 def _getval(self
, arg
):
707 return eval(arg
, self
.curframe
.f_globals
,
708 self
.curframe
.f_locals
)
710 t
, v
= sys
.exc_info()[:2]
711 if isinstance(t
, str):
713 else: exc_type_name
= t
.__name
__
714 print >>self
.stdout
, '***', exc_type_name
+ ':', repr(v
)
719 print >>self
.stdout
, repr(self
._getval
(arg
))
723 def do_pp(self
, arg
):
725 pprint
.pprint(self
._getval
(arg
), self
.stdout
)
729 def do_list(self
, arg
):
730 self
.lastcmd
= 'list'
734 x
= eval(arg
, {}, {})
735 if type(x
) == type(()):
740 # Assume it's a count
743 first
= max(1, int(x
) - 5)
745 print >>self
.stdout
, '*** Error in argument:', repr(arg
)
747 elif self
.lineno
is None:
748 first
= max(1, self
.curframe
.f_lineno
- 5)
750 first
= self
.lineno
+ 1
753 filename
= self
.curframe
.f_code
.co_filename
754 breaklist
= self
.get_file_breaks(filename
)
756 for lineno
in range(first
, last
+1):
757 line
= linecache
.getline(filename
, lineno
)
759 print >>self
.stdout
, '[EOF]'
762 s
= repr(lineno
).rjust(3)
763 if len(s
) < 4: s
= s
+ ' '
764 if lineno
in breaklist
: s
= s
+ 'B'
766 if lineno
== self
.curframe
.f_lineno
:
768 print >>self
.stdout
, s
+ '\t' + line
,
770 except KeyboardInterrupt:
774 def do_whatis(self
, arg
):
776 value
= eval(arg
, self
.curframe
.f_globals
,
777 self
.curframe
.f_locals
)
779 t
, v
= sys
.exc_info()[:2]
780 if type(t
) == type(''):
782 else: exc_type_name
= t
.__name
__
783 print >>self
.stdout
, '***', exc_type_name
+ ':', repr(v
)
787 try: code
= value
.func_code
790 print >>self
.stdout
, 'Function', code
.co_name
792 # Is it an instance method?
793 try: code
= value
.im_func
.func_code
796 print >>self
.stdout
, 'Method', code
.co_name
798 # None of the above...
799 print >>self
.stdout
, type(value
)
801 def do_alias(self
, arg
):
804 keys
= self
.aliases
.keys()
807 print >>self
.stdout
, "%s = %s" % (alias
, self
.aliases
[alias
])
809 if args
[0] in self
.aliases
and len(args
) == 1:
810 print >>self
.stdout
, "%s = %s" % (args
[0], self
.aliases
[args
[0]])
812 self
.aliases
[args
[0]] = ' '.join(args
[1:])
814 def do_unalias(self
, arg
):
816 if len(args
) == 0: return
817 if args
[0] in self
.aliases
:
818 del self
.aliases
[args
[0]]
820 #list of all the commands making the program resume execution.
821 commands_resuming
= ['do_continue', 'do_step', 'do_next', 'do_return',
822 'do_quit', 'do_jump']
824 # Print a traceback starting at the top stack frame.
825 # The most recently entered frame is printed last;
826 # this is different from dbx and gdb, but consistent with
827 # the Python interpreter's stack trace.
828 # It is also consistent with the up/down commands (which are
829 # compatible with dbx and gdb: up moves towards 'main()'
830 # and down moves towards the most recent stack frame).
832 def print_stack_trace(self
):
834 for frame_lineno
in self
.stack
:
835 self
.print_stack_entry(frame_lineno
)
836 except KeyboardInterrupt:
839 def print_stack_entry(self
, frame_lineno
, prompt_prefix
=line_prefix
):
840 frame
, lineno
= frame_lineno
841 if frame
is self
.curframe
:
842 print >>self
.stdout
, '>',
844 print >>self
.stdout
, ' ',
845 print >>self
.stdout
, self
.format_stack_entry(frame_lineno
,
849 # Help methods (derived from pdb.doc)
855 print >>self
.stdout
, """h(elp)
856 Without argument, print the list of available commands.
857 With a command name as argument, print help about that command
858 "help pdb" pipes the full documentation file to the $PAGER
859 "help exec" gives help on the ! command"""
861 def help_where(self
):
865 print >>self
.stdout
, """w(here)
866 Print a stack trace, with the most recent frame at the bottom.
867 An arrow indicates the "current frame", which determines the
868 context of most commands. 'bt' is an alias for this command."""
876 print >>self
.stdout
, """d(own)
877 Move the current frame one level down in the stack trace
878 (to a newer frame)."""
884 print >>self
.stdout
, """u(p)
885 Move the current frame one level up in the stack trace
886 (to an older frame)."""
888 def help_break(self
):
892 print >>self
.stdout
, """b(reak) ([file:]lineno | function) [, condition]
893 With a line number argument, set a break there in the current
894 file. With a function name, set a break at first executable line
895 of that function. Without argument, list all breaks. If a second
896 argument is present, it is a string specifying an expression
897 which must evaluate to true before the breakpoint is honored.
899 The line number may be prefixed with a filename and a colon,
900 to specify a breakpoint in another file (probably one that
901 hasn't been loaded yet). The file is searched for on sys.path;
902 the .py suffix may be omitted."""
904 def help_clear(self
):
908 print >>self
.stdout
, "cl(ear) filename:lineno"
909 print >>self
.stdout
, """cl(ear) [bpnumber [bpnumber...]]
910 With a space separated list of breakpoint numbers, clear
911 those breakpoints. Without argument, clear all breaks (but
912 first ask confirmation). With a filename:lineno argument,
913 clear all breaks at that line in that file.
915 Note that the argument is different from previous versions of
916 the debugger (in python distributions 1.5.1 and before) where
917 a linenumber was used instead of either filename:lineno or
918 breakpoint numbers."""
920 def help_tbreak(self
):
921 print >>self
.stdout
, """tbreak same arguments as break, but breakpoint is
922 removed when first hit."""
924 def help_enable(self
):
925 print >>self
.stdout
, """enable bpnumber [bpnumber ...]
926 Enables the breakpoints given as a space separated list of
929 def help_disable(self
):
930 print >>self
.stdout
, """disable bpnumber [bpnumber ...]
931 Disables the breakpoints given as a space separated list of
934 def help_ignore(self
):
935 print >>self
.stdout
, """ignore bpnumber count
936 Sets the ignore count for the given breakpoint number. A breakpoint
937 becomes active when the ignore count is zero. When non-zero, the
938 count is decremented each time the breakpoint is reached and the
939 breakpoint is not disabled and any associated condition evaluates
942 def help_condition(self
):
943 print >>self
.stdout
, """condition bpnumber str_condition
944 str_condition is a string specifying an expression which
945 must evaluate to true before the breakpoint is honored.
946 If str_condition is absent, any existing condition is removed;
947 i.e., the breakpoint is made unconditional."""
953 print >>self
.stdout
, """s(tep)
954 Execute the current line, stop at the first possible occasion
955 (either in a function that is called or in the current function)."""
961 print >>self
.stdout
, """n(ext)
962 Continue execution until the next line in the current function
963 is reached or it returns."""
965 def help_return(self
):
969 print >>self
.stdout
, """r(eturn)
970 Continue execution until the current function returns."""
972 def help_continue(self
):
979 print >>self
.stdout
, """c(ont(inue))
980 Continue execution, only stop when a breakpoint is encountered."""
986 print >>self
.stdout
, """j(ump) lineno
987 Set the next line that will be executed."""
989 def help_debug(self
):
990 print >>self
.stdout
, """debug code
991 Enter a recursive debugger that steps through the code argument
992 (which is an arbitrary expression or statement to be executed
993 in the current environment)."""
999 print >>self
.stdout
, """l(ist) [first [,last]]
1000 List source code for the current file.
1001 Without arguments, list 11 lines around the current line
1002 or continue the previous listing.
1003 With one argument, list 11 lines starting at that line.
1004 With two arguments, list the given range;
1005 if the second argument is less than the first, it is a count."""
1007 def help_args(self
):
1011 print >>self
.stdout
, """a(rgs)
1012 Print the arguments of the current function."""
1015 print >>self
.stdout
, """p expression
1016 Print the value of the expression."""
1019 print >>self
.stdout
, """pp expression
1020 Pretty-print the value of the expression."""
1022 def help_exec(self
):
1023 print >>self
.stdout
, """(!) statement
1024 Execute the (one-line) statement in the context of
1025 the current stack frame.
1026 The exclamation point can be omitted unless the first word
1027 of the statement resembles a debugger command.
1028 To assign to a global variable you must always prefix the
1029 command with a 'global' command, e.g.:
1030 (Pdb) global list_options; list_options = ['-l']
1034 print """run [args...]
1035 Restart the debugged python program. If a string is supplied, it is
1036 splitted with "shlex" and the result is used as the new sys.argv.
1037 History, breakpoints, actions and debugger options are preserved.
1038 "restart" is an alias for "run"."""
1040 help_restart
= help_run
1042 def help_quit(self
):
1046 print >>self
.stdout
, """q(uit) or exit - Quit from the debugger.
1047 The program being executed is aborted."""
1051 def help_whatis(self
):
1052 print >>self
.stdout
, """whatis arg
1053 Prints the type of the argument."""
1056 print >>self
.stdout
, """EOF
1057 Handles the receipt of EOF as a command."""
1059 def help_alias(self
):
1060 print >>self
.stdout
, """alias [name [command [parameter parameter ...] ]]
1061 Creates an alias called 'name' the executes 'command'. The command
1062 must *not* be enclosed in quotes. Replaceable parameters are
1063 indicated by %1, %2, and so on, while %* is replaced by all the
1064 parameters. If no command is given, the current alias for name
1065 is shown. If no name is given, all aliases are listed.
1067 Aliases may be nested and can contain anything that can be
1068 legally typed at the pdb prompt. Note! You *can* override
1069 internal pdb commands with aliases! Those internal commands
1070 are then hidden until the alias is removed. Aliasing is recursively
1071 applied to the first word of the command line; all other words
1072 in the line are left alone.
1074 Some useful aliases (especially when placed in the .pdbrc file) are:
1076 #Print instance variables (usage "pi classInst")
1077 alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
1079 #Print instance variables in self
1083 def help_unalias(self
):
1084 print >>self
.stdout
, """unalias name
1085 Deletes the specified alias."""
1087 def help_commands(self
):
1088 print >>self
.stdout
, """commands [bpnumber]
1093 Specify a list of commands for breakpoint number bpnumber. The
1094 commands themselves appear on the following lines. Type a line
1095 containing just 'end' to terminate the commands.
1097 To remove all commands from a breakpoint, type commands and
1098 follow it immediately with end; that is, give no commands.
1100 With no bpnumber argument, commands refers to the last
1103 You can use breakpoint commands to start your program up again.
1104 Simply use the continue command, or step, or any other
1105 command that resumes execution.
1107 Specifying any command resuming execution (currently continue,
1108 step, next, return, jump, quit and their abbreviations) terminates
1109 the command list (as if that command was immediately followed by end).
1110 This is because any time you resume execution
1111 (even with a simple next or step), you may encounter
1112 another breakpoint--which could have its own command list, leading to
1113 ambiguities about which list to execute.
1115 If you use the 'silent' command in the command list, the
1116 usual message about stopping at a breakpoint is not printed. This may
1117 be desirable for breakpoints that are to print a specific message and
1118 then continue. If none of the other commands print anything, you
1119 see no sign that the breakpoint was reached.
1125 def lookupmodule(self
, filename
):
1126 """Helper function for break/clear parsing -- may be overridden.
1128 lookupmodule() translates (possibly incomplete) file or module name
1129 into an absolute file name.
1131 if os
.path
.isabs(filename
) and os
.path
.exists(filename
):
1133 f
= os
.path
.join(sys
.path
[0], filename
)
1134 if os
.path
.exists(f
) and self
.canonic(f
) == self
.mainpyfile
:
1136 root
, ext
= os
.path
.splitext(filename
)
1138 filename
= filename
+ '.py'
1139 if os
.path
.isabs(filename
):
1141 for dirname
in sys
.path
:
1142 while os
.path
.islink(dirname
):
1143 dirname
= os
.readlink(dirname
)
1144 fullname
= os
.path
.join(dirname
, filename
)
1145 if os
.path
.exists(fullname
):
1149 def _runscript(self
, filename
):
1150 # The script has to run in __main__ namespace (or imports from
1151 # __main__ will break).
1153 # So we clear up the __main__ and set several special variables
1154 # (this gets rid of pdb's globals and cleans old variables on restarts).
1156 __main__
.__dict
__.clear()
1157 __main__
.__dict
__.update({"__name__" : "__main__",
1158 "__file__" : filename
,
1159 "__builtins__": __builtins__
,
1162 # When bdb sets tracing, a number of call and line events happens
1163 # BEFORE debugger even reaches user's code (and the exact sequence of
1164 # events depends on python version). So we take special measures to
1165 # avoid stopping before we reach the main script (see user_line and
1166 # user_call for details).
1167 self
._wait
_for
_mainpyfile
= 1
1168 self
.mainpyfile
= self
.canonic(filename
)
1169 self
._user
_requested
_quit
= 0
1170 statement
= 'execfile( "%s")' % filename
1173 # Simplified interface
1175 def run(statement
, globals=None, locals=None):
1176 Pdb().run(statement
, globals, locals)
1178 def runeval(expression
, globals=None, locals=None):
1179 return Pdb().runeval(expression
, globals, locals)
1181 def runctx(statement
, globals, locals):
1183 run(statement
, globals, locals)
1185 def runcall(*args
, **kwds
):
1186 return Pdb().runcall(*args
, **kwds
)
1189 Pdb().set_trace(sys
._getframe
().f_back
)
1191 # Post-Mortem interface
1196 while t
.tb_next
is not None:
1198 p
.interaction(t
.tb_frame
, t
)
1201 post_mortem(sys
.last_traceback
)
1204 # Main program for testing
1206 TESTCMD
= 'import x; x.main()'
1213 for dirname
in sys
.path
:
1214 fullname
= os
.path
.join(dirname
, 'pdb.doc')
1215 if os
.path
.exists(fullname
):
1216 sts
= os
.system('${PAGER-more} '+fullname
)
1217 if sts
: print '*** Pager exit status:', sts
1220 print 'Sorry, can\'t find the help file "pdb.doc"',
1221 print 'along the Python search path'
1224 if not sys
.argv
[1:]:
1225 print "usage: pdb.py scriptfile [arg] ..."
1228 mainpyfile
= sys
.argv
[1] # Get script filename
1229 if not os
.path
.exists(mainpyfile
):
1230 print 'Error:', mainpyfile
, 'does not exist'
1233 del sys
.argv
[0] # Hide "pdb.py" from argument list
1235 # Replace pdb's dir with script's dir in front of module search path.
1236 sys
.path
[0] = os
.path
.dirname(mainpyfile
)
1238 # Note on saving/restoring sys.argv: it's a good idea when sys.argv was
1239 # modified by the script being debugged. It's a bad idea when it was
1240 # changed by the user from the command line. There is a "restart" command which
1241 # allows explicit specification of command line arguments.
1245 pdb
._runscript
(mainpyfile
)
1246 if pdb
._user
_requested
_quit
:
1248 print "The program finished and will be restarted"
1250 print "Restarting", mainpyfile
, "with arguments:"
1251 print "\t" + " ".join(sys
.argv
[1:])
1253 # In most cases SystemExit does not warrant a post-mortem session.
1254 print "The program exited via sys.exit(). Exit status: ",
1255 print sys
.exc_info()[1]
1257 traceback
.print_exc()
1258 print "Uncaught exception. Entering post mortem debugging"
1259 print "Running 'cont' or 'step' will restart the program"
1260 t
= sys
.exc_info()[2]
1261 while t
.tb_next
is not None:
1263 pdb
.interaction(t
.tb_frame
,t
)
1264 print "Post mortem debugger finished. The "+mainpyfile
+" will be restarted"
1267 # When invoked as main program, invoke the debugger on a script
1268 if __name__
== '__main__':