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, skip
=None):
62 bdb
.Bdb
.__init
__(self
, skip
=skip
)
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
99 # must be disp. after execing the cmd list
100 self
.commands_silent
= {} # for each bp num, tells if the stack trace
101 # must be disp. after execing the cmd list
102 self
.commands_defining
= False # True while in the process of defining
104 self
.commands_bnum
= None # The breakpoint number for which we are
117 def setup(self
, f
, t
):
119 self
.stack
, self
.curindex
= self
.get_stack(f
, t
)
120 self
.curframe
= self
.stack
[self
.curindex
][0]
121 # The f_locals dictionary is updated from the actual frame
122 # locals whenever the .f_locals accessor is called, so we
123 # cache it here to ensure that modifications are not overwritten.
124 self
.curframe_locals
= self
.curframe
.f_locals
127 # Can be executed earlier than 'setup' if desired
128 def execRcLines(self
):
130 # Make local copy because of recursion
131 rcLines
= self
.rcLines
136 if len(line
) > 0 and line
[0] != '#':
139 # Override Bdb methods
141 def user_call(self
, frame
, argument_list
):
142 """This method is called when there is the remote possibility
143 that we ever need to stop in this function."""
144 if self
._wait
_for
_mainpyfile
:
146 if self
.stop_here(frame
):
147 print >>self
.stdout
, '--Call--'
148 self
.interaction(frame
, None)
150 def user_line(self
, frame
):
151 """This function is called when we stop or break at this line."""
152 if self
._wait
_for
_mainpyfile
:
153 if (self
.mainpyfile
!= self
.canonic(frame
.f_code
.co_filename
)
154 or frame
.f_lineno
<= 0):
156 self
._wait
_for
_mainpyfile
= 0
157 if self
.bp_commands(frame
):
158 self
.interaction(frame
, None)
160 def bp_commands(self
,frame
):
161 """Call every command that was set for the current active breakpoint
164 Returns True if the normal interaction function must be called,
166 # self.currentbp is set in bdb in Bdb.break_here if a breakpoint was hit
167 if getattr(self
, "currentbp", False) and \
168 self
.currentbp
in self
.commands
:
169 currentbp
= self
.currentbp
171 lastcmd_back
= self
.lastcmd
172 self
.setup(frame
, None)
173 for line
in self
.commands
[currentbp
]:
175 self
.lastcmd
= lastcmd_back
176 if not self
.commands_silent
[currentbp
]:
177 self
.print_stack_entry(self
.stack
[self
.curindex
])
178 if self
.commands_doprompt
[currentbp
]:
184 def user_return(self
, frame
, return_value
):
185 """This function is called when a return trap is set here."""
186 frame
.f_locals
['__return__'] = return_value
187 print >>self
.stdout
, '--Return--'
188 self
.interaction(frame
, None)
190 def user_exception(self
, frame
, exc_info
):
191 exc_type
, exc_value
, exc_traceback
= exc_info
192 """This function is called if an exception occurs,
193 but only if we are to stop at or just below this level."""
194 frame
.f_locals
['__exception__'] = exc_type
, exc_value
195 if type(exc_type
) == type(''):
196 exc_type_name
= exc_type
197 else: exc_type_name
= exc_type
.__name
__
198 print >>self
.stdout
, exc_type_name
+ ':', _saferepr(exc_value
)
199 self
.interaction(frame
, exc_traceback
)
201 # General interaction function
203 def interaction(self
, frame
, traceback
):
204 self
.setup(frame
, traceback
)
205 self
.print_stack_entry(self
.stack
[self
.curindex
])
209 def displayhook(self
, obj
):
210 """Custom displayhook for the exec in default(), which prevents
211 assignment of the _ variable in the builtins.
213 # reproduce the behavior of the standard displayhook, not printing None
217 def default(self
, line
):
218 if line
[:1] == '!': line
= line
[1:]
219 locals = self
.curframe_locals
220 globals = self
.curframe
.f_globals
222 code
= compile(line
+ '\n', '<stdin>', 'single')
223 save_stdout
= sys
.stdout
224 save_stdin
= sys
.stdin
225 save_displayhook
= sys
.displayhook
227 sys
.stdin
= self
.stdin
228 sys
.stdout
= self
.stdout
229 sys
.displayhook
= self
.displayhook
230 exec code
in globals, locals
232 sys
.stdout
= save_stdout
233 sys
.stdin
= save_stdin
234 sys
.displayhook
= save_displayhook
236 t
, v
= sys
.exc_info()[:2]
237 if type(t
) == type(''):
239 else: exc_type_name
= t
.__name
__
240 print >>self
.stdout
, '***', exc_type_name
+ ':', v
242 def precmd(self
, line
):
243 """Handle alias expansion and ';;' separator."""
247 while args
[0] in self
.aliases
:
248 line
= self
.aliases
[args
[0]]
250 for tmpArg
in args
[1:]:
251 line
= line
.replace("%" + str(ii
),
254 line
= line
.replace("%*", ' '.join(args
[1:]))
256 # split into ';;' separated commands
257 # unless it's an alias command
258 if args
[0] != 'alias':
259 marker
= line
.find(';;')
261 # queue up everything after marker
262 next
= line
[marker
+2:].lstrip()
263 self
.cmdqueue
.append(next
)
264 line
= line
[:marker
].rstrip()
267 def onecmd(self
, line
):
268 """Interpret the argument as though it had been typed in response
271 Checks whether this line is typed at the normal prompt or in
272 a breakpoint command list definition.
274 if not self
.commands_defining
:
275 return cmd
.Cmd
.onecmd(self
, line
)
277 return self
.handle_command_def(line
)
279 def handle_command_def(self
,line
):
280 """ Handles one command line during command list definition. """
281 cmd
, arg
, line
= self
.parseline(line
)
283 self
.commands_silent
[self
.commands_bnum
] = True
284 return # continue to handle other cmd def in the cmd list
287 return 1 # end of cmd list
288 cmdlist
= self
.commands
[self
.commands_bnum
]
290 cmdlist
.append(cmd
+' '+arg
)
293 # Determine if we must stop
295 func
= getattr(self
, 'do_' + cmd
)
296 except AttributeError:
298 # one of the resuming commands
299 if func
.func_name
in self
.commands_resuming
:
300 self
.commands_doprompt
[self
.commands_bnum
] = False
305 # Command definitions, called by cmdloop()
306 # The argument is the remaining string on the command line
307 # Return true to exit from the command loop
309 do_h
= cmd
.Cmd
.do_help
311 def do_commands(self
, arg
):
312 """Defines a list of commands associated to a breakpoint.
314 Those commands will be executed whenever the breakpoint causes
315 the program to stop execution."""
317 bnum
= len(bdb
.Breakpoint
.bpbynumber
)-1
322 print >>self
.stdout
, "Usage : commands [bnum]\n ..." \
325 self
.commands_bnum
= bnum
326 self
.commands
[bnum
] = []
327 self
.commands_doprompt
[bnum
] = True
328 self
.commands_silent
[bnum
] = False
329 prompt_back
= self
.prompt
330 self
.prompt
= '(com) '
331 self
.commands_defining
= True
333 self
.commands_defining
= False
334 self
.prompt
= prompt_back
336 def do_break(self
, arg
, temporary
= 0):
337 # break [ ([filename:]lineno | function) [, "condition"] ]
339 if self
.breaks
: # There's at least one
340 print >>self
.stdout
, "Num Type Disp Enb Where"
341 for bp
in bdb
.Breakpoint
.bpbynumber
:
343 bp
.bpprint(self
.stdout
)
345 # parse arguments; comma has lowest precedence
346 # and cannot occur in filename
350 comma
= arg
.find(',')
352 # parse stuff after comma: "condition"
353 cond
= arg
[comma
+1:].lstrip()
354 arg
= arg
[:comma
].rstrip()
355 # parse stuff before comma: [filename:]lineno | function
356 colon
= arg
.rfind(':')
359 filename
= arg
[:colon
].rstrip()
360 f
= self
.lookupmodule(filename
)
362 print >>self
.stdout
, '*** ', repr(filename
),
363 print >>self
.stdout
, 'not found from sys.path'
367 arg
= arg
[colon
+1:].lstrip()
370 except ValueError, msg
:
371 print >>self
.stdout
, '*** Bad lineno:', arg
374 # no colon; can be lineno or function
380 self
.curframe
.f_globals
,
381 self
.curframe_locals
)
385 if hasattr(func
, 'im_func'):
387 code
= func
.func_code
388 #use co_name to identify the bkpt (function names
389 #could be aliased, but co_name is invariant)
390 funcname
= code
.co_name
391 lineno
= code
.co_firstlineno
392 filename
= code
.co_filename
395 (ok
, filename
, ln
) = self
.lineinfo(arg
)
397 print >>self
.stdout
, '*** The specified object',
398 print >>self
.stdout
, repr(arg
),
399 print >>self
.stdout
, 'is not a function'
400 print >>self
.stdout
, 'or was not found along sys.path.'
402 funcname
= ok
# ok contains a function name
405 filename
= self
.defaultFile()
406 # Check for reasonable breakpoint
407 line
= self
.checkline(filename
, lineno
)
409 # now set the break point
410 err
= self
.set_break(filename
, line
, temporary
, cond
, funcname
)
411 if err
: print >>self
.stdout
, '***', err
413 bp
= self
.get_breaks(filename
, line
)[-1]
414 print >>self
.stdout
, "Breakpoint %d at %s:%d" % (bp
.number
,
418 # To be overridden in derived debuggers
419 def defaultFile(self
):
420 """Produce a reasonable default."""
421 filename
= self
.curframe
.f_code
.co_filename
422 if filename
== '<string>' and self
.mainpyfile
:
423 filename
= self
.mainpyfile
428 def do_tbreak(self
, arg
):
429 self
.do_break(arg
, 1)
431 def lineinfo(self
, identifier
):
432 failed
= (None, None, None)
433 # Input is identifier, may be in single quotes
434 idstring
= identifier
.split("'")
435 if len(idstring
) == 1:
436 # not in single quotes
437 id = idstring
[0].strip()
438 elif len(idstring
) == 3:
440 id = idstring
[1].strip()
443 if id == '': return failed
444 parts
= id.split('.')
445 # Protection for derived debuggers
446 if parts
[0] == 'self':
450 # Best first guess at file to look at
451 fname
= self
.defaultFile()
455 # More than one part.
456 # First is module, second is method/class
457 f
= self
.lookupmodule(parts
[0])
461 answer
= find_function(item
, fname
)
462 return answer
or failed
464 def checkline(self
, filename
, lineno
):
465 """Check whether specified line seems to be executable.
467 Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
468 line or EOF). Warning: testing is not comprehensive.
470 line
= linecache
.getline(filename
, lineno
, self
.curframe
.f_globals
)
472 print >>self
.stdout
, 'End of file'
475 # Don't allow setting breakpoint at a blank line
476 if (not line
or (line
[0] == '#') or
477 (line
[:3] == '"""') or line
[:3] == "'''"):
478 print >>self
.stdout
, '*** Blank or comment'
482 def do_enable(self
, arg
):
488 print >>self
.stdout
, 'Breakpoint index %r is not a number' % i
491 if not (0 <= i
< len(bdb
.Breakpoint
.bpbynumber
)):
492 print >>self
.stdout
, 'No breakpoint numbered', i
495 bp
= bdb
.Breakpoint
.bpbynumber
[i
]
499 def do_disable(self
, arg
):
505 print >>self
.stdout
, 'Breakpoint index %r is not a number' % i
508 if not (0 <= i
< len(bdb
.Breakpoint
.bpbynumber
)):
509 print >>self
.stdout
, 'No breakpoint numbered', i
512 bp
= bdb
.Breakpoint
.bpbynumber
[i
]
516 def do_condition(self
, arg
):
517 # arg is breakpoint number and condition
518 args
= arg
.split(' ', 1)
520 bpnum
= int(args
[0].strip())
522 # something went wrong
523 print >>self
.stdout
, \
524 'Breakpoint index %r is not a number' % args
[0]
531 bp
= bdb
.Breakpoint
.bpbynumber
[bpnum
]
533 print >>self
.stdout
, 'Breakpoint index %r is not valid' % args
[0]
538 print >>self
.stdout
, 'Breakpoint', bpnum
,
539 print >>self
.stdout
, 'is now unconditional.'
541 def do_ignore(self
,arg
):
542 """arg is bp number followed by ignore count."""
545 bpnum
= int(args
[0].strip())
547 # something went wrong
548 print >>self
.stdout
, \
549 'Breakpoint index %r is not a number' % args
[0]
552 count
= int(args
[1].strip())
556 bp
= bdb
.Breakpoint
.bpbynumber
[bpnum
]
558 print >>self
.stdout
, 'Breakpoint index %r is not valid' % args
[0]
563 reply
= 'Will ignore next '
565 reply
= reply
+ '%d crossings' % count
567 reply
= reply
+ '1 crossing'
568 print >>self
.stdout
, reply
+ ' of breakpoint %d.' % bpnum
570 print >>self
.stdout
, 'Will stop next time breakpoint',
571 print >>self
.stdout
, bpnum
, 'is reached.'
573 def do_clear(self
, arg
):
574 """Three possibilities, tried in this order:
575 clear -> clear all breaks, ask for confirmation
576 clear file:lineno -> clear all breaks at file:lineno
577 clear bpno bpno ... -> clear breakpoints by number"""
580 reply
= raw_input('Clear all breaks? ')
583 reply
= reply
.strip().lower()
584 if reply
in ('y', 'yes'):
585 self
.clear_all_breaks()
588 # Make sure it works for "clear C:\foo\bar.py:12"
595 err
= "Invalid line number (%s)" % arg
597 err
= self
.clear_break(filename
, lineno
)
598 if err
: print >>self
.stdout
, '***', err
600 numberlist
= arg
.split()
605 print >>self
.stdout
, 'Breakpoint index %r is not a number' % i
608 if not (0 <= i
< len(bdb
.Breakpoint
.bpbynumber
)):
609 print >>self
.stdout
, 'No breakpoint numbered', i
611 err
= self
.clear_bpbynumber(i
)
613 print >>self
.stdout
, '***', err
615 print >>self
.stdout
, 'Deleted breakpoint', i
616 do_cl
= do_clear
# 'c' is already an abbreviation for 'continue'
618 def do_where(self
, arg
):
619 self
.print_stack_trace()
623 def do_up(self
, arg
):
624 if self
.curindex
== 0:
625 print >>self
.stdout
, '*** Oldest frame'
627 self
.curindex
= self
.curindex
- 1
628 self
.curframe
= self
.stack
[self
.curindex
][0]
629 self
.curframe_locals
= self
.curframe
.f_locals
630 self
.print_stack_entry(self
.stack
[self
.curindex
])
634 def do_down(self
, arg
):
635 if self
.curindex
+ 1 == len(self
.stack
):
636 print >>self
.stdout
, '*** Newest frame'
638 self
.curindex
= self
.curindex
+ 1
639 self
.curframe
= self
.stack
[self
.curindex
][0]
640 self
.curframe_locals
= self
.curframe
.f_locals
641 self
.print_stack_entry(self
.stack
[self
.curindex
])
645 def do_until(self
, arg
):
646 self
.set_until(self
.curframe
)
650 def do_step(self
, arg
):
655 def do_next(self
, arg
):
656 self
.set_next(self
.curframe
)
660 def do_run(self
, arg
):
661 """Restart program by raising an exception to be caught in the main
662 debugger loop. If arguments were given, set them in sys.argv."""
665 argv0
= sys
.argv
[0:1]
666 sys
.argv
= shlex
.split(arg
)
672 def do_return(self
, arg
):
673 self
.set_return(self
.curframe
)
677 def do_continue(self
, arg
):
680 do_c
= do_cont
= do_continue
682 def do_jump(self
, arg
):
683 if self
.curindex
+ 1 != len(self
.stack
):
684 print >>self
.stdout
, "*** You can only jump within the bottom frame"
689 print >>self
.stdout
, "*** The 'jump' command requires a line number."
692 # Do the jump, fix up our copy of the stack, and display the
694 self
.curframe
.f_lineno
= arg
695 self
.stack
[self
.curindex
] = self
.stack
[self
.curindex
][0], arg
696 self
.print_stack_entry(self
.stack
[self
.curindex
])
697 except ValueError, e
:
698 print >>self
.stdout
, '*** Jump failed:', e
701 def do_debug(self
, arg
):
703 globals = self
.curframe
.f_globals
704 locals = self
.curframe_locals
705 p
= Pdb(self
.completekey
, self
.stdin
, self
.stdout
)
706 p
.prompt
= "(%s) " % self
.prompt
.strip()
707 print >>self
.stdout
, "ENTERING RECURSIVE DEBUGGER"
708 sys
.call_tracing(p
.run
, (arg
, globals, locals))
709 print >>self
.stdout
, "LEAVING RECURSIVE DEBUGGER"
710 sys
.settrace(self
.trace_dispatch
)
711 self
.lastcmd
= p
.lastcmd
713 def do_quit(self
, arg
):
714 self
._user
_requested
_quit
= 1
721 def do_EOF(self
, arg
):
723 self
._user
_requested
_quit
= 1
727 def do_args(self
, arg
):
728 co
= self
.curframe
.f_code
729 dict = self
.curframe_locals
731 if co
.co_flags
& 4: n
= n
+1
732 if co
.co_flags
& 8: n
= n
+1
734 name
= co
.co_varnames
[i
]
735 print >>self
.stdout
, name
, '=',
736 if name
in dict: print >>self
.stdout
, dict[name
]
737 else: print >>self
.stdout
, "*** undefined ***"
740 def do_retval(self
, arg
):
741 if '__return__' in self
.curframe_locals
:
742 print >>self
.stdout
, self
.curframe_locals
['__return__']
744 print >>self
.stdout
, '*** Not yet returned!'
747 def _getval(self
, arg
):
749 return eval(arg
, self
.curframe
.f_globals
,
750 self
.curframe_locals
)
752 t
, v
= sys
.exc_info()[:2]
753 if isinstance(t
, str):
755 else: exc_type_name
= t
.__name
__
756 print >>self
.stdout
, '***', exc_type_name
+ ':', repr(v
)
761 print >>self
.stdout
, repr(self
._getval
(arg
))
765 def do_pp(self
, arg
):
767 pprint
.pprint(self
._getval
(arg
), self
.stdout
)
771 def do_list(self
, arg
):
772 self
.lastcmd
= 'list'
776 x
= eval(arg
, {}, {})
777 if type(x
) == type(()):
782 # Assume it's a count
785 first
= max(1, int(x
) - 5)
787 print >>self
.stdout
, '*** Error in argument:', repr(arg
)
789 elif self
.lineno
is None:
790 first
= max(1, self
.curframe
.f_lineno
- 5)
792 first
= self
.lineno
+ 1
795 filename
= self
.curframe
.f_code
.co_filename
796 breaklist
= self
.get_file_breaks(filename
)
798 for lineno
in range(first
, last
+1):
799 line
= linecache
.getline(filename
, lineno
,
800 self
.curframe
.f_globals
)
802 print >>self
.stdout
, '[EOF]'
805 s
= repr(lineno
).rjust(3)
806 if len(s
) < 4: s
= s
+ ' '
807 if lineno
in breaklist
: s
= s
+ 'B'
809 if lineno
== self
.curframe
.f_lineno
:
811 print >>self
.stdout
, s
+ '\t' + line
,
813 except KeyboardInterrupt:
817 def do_whatis(self
, arg
):
819 value
= eval(arg
, self
.curframe
.f_globals
,
820 self
.curframe_locals
)
822 t
, v
= sys
.exc_info()[:2]
823 if type(t
) == type(''):
825 else: exc_type_name
= t
.__name
__
826 print >>self
.stdout
, '***', exc_type_name
+ ':', repr(v
)
830 try: code
= value
.func_code
833 print >>self
.stdout
, 'Function', code
.co_name
835 # Is it an instance method?
836 try: code
= value
.im_func
.func_code
839 print >>self
.stdout
, 'Method', code
.co_name
841 # None of the above...
842 print >>self
.stdout
, type(value
)
844 def do_alias(self
, arg
):
847 keys
= self
.aliases
.keys()
850 print >>self
.stdout
, "%s = %s" % (alias
, self
.aliases
[alias
])
852 if args
[0] in self
.aliases
and len(args
) == 1:
853 print >>self
.stdout
, "%s = %s" % (args
[0], self
.aliases
[args
[0]])
855 self
.aliases
[args
[0]] = ' '.join(args
[1:])
857 def do_unalias(self
, arg
):
859 if len(args
) == 0: return
860 if args
[0] in self
.aliases
:
861 del self
.aliases
[args
[0]]
863 #list of all the commands making the program resume execution.
864 commands_resuming
= ['do_continue', 'do_step', 'do_next', 'do_return',
865 'do_quit', 'do_jump']
867 # Print a traceback starting at the top stack frame.
868 # The most recently entered frame is printed last;
869 # this is different from dbx and gdb, but consistent with
870 # the Python interpreter's stack trace.
871 # It is also consistent with the up/down commands (which are
872 # compatible with dbx and gdb: up moves towards 'main()'
873 # and down moves towards the most recent stack frame).
875 def print_stack_trace(self
):
877 for frame_lineno
in self
.stack
:
878 self
.print_stack_entry(frame_lineno
)
879 except KeyboardInterrupt:
882 def print_stack_entry(self
, frame_lineno
, prompt_prefix
=line_prefix
):
883 frame
, lineno
= frame_lineno
884 if frame
is self
.curframe
:
885 print >>self
.stdout
, '>',
887 print >>self
.stdout
, ' ',
888 print >>self
.stdout
, self
.format_stack_entry(frame_lineno
,
892 # Help methods (derived from pdb.doc)
898 print >>self
.stdout
, """h(elp)
899 Without argument, print the list of available commands.
900 With a command name as argument, print help about that command
901 "help pdb" pipes the full documentation file to the $PAGER
902 "help exec" gives help on the ! command"""
904 def help_where(self
):
908 print >>self
.stdout
, """w(here)
909 Print a stack trace, with the most recent frame at the bottom.
910 An arrow indicates the "current frame", which determines the
911 context of most commands. 'bt' is an alias for this command."""
919 print >>self
.stdout
, """d(own)
920 Move the current frame one level down in the stack trace
921 (to a newer frame)."""
927 print >>self
.stdout
, """u(p)
928 Move the current frame one level up in the stack trace
929 (to an older frame)."""
931 def help_break(self
):
935 print >>self
.stdout
, """b(reak) ([file:]lineno | function) [, condition]
936 With a line number argument, set a break there in the current
937 file. With a function name, set a break at first executable line
938 of that function. Without argument, list all breaks. If a second
939 argument is present, it is a string specifying an expression
940 which must evaluate to true before the breakpoint is honored.
942 The line number may be prefixed with a filename and a colon,
943 to specify a breakpoint in another file (probably one that
944 hasn't been loaded yet). The file is searched for on sys.path;
945 the .py suffix may be omitted."""
947 def help_clear(self
):
951 print >>self
.stdout
, "cl(ear) filename:lineno"
952 print >>self
.stdout
, """cl(ear) [bpnumber [bpnumber...]]
953 With a space separated list of breakpoint numbers, clear
954 those breakpoints. Without argument, clear all breaks (but
955 first ask confirmation). With a filename:lineno argument,
956 clear all breaks at that line in that file.
958 Note that the argument is different from previous versions of
959 the debugger (in python distributions 1.5.1 and before) where
960 a linenumber was used instead of either filename:lineno or
961 breakpoint numbers."""
963 def help_tbreak(self
):
964 print >>self
.stdout
, """tbreak same arguments as break, but breakpoint
965 is removed when first hit."""
967 def help_enable(self
):
968 print >>self
.stdout
, """enable bpnumber [bpnumber ...]
969 Enables the breakpoints given as a space separated list of
972 def help_disable(self
):
973 print >>self
.stdout
, """disable bpnumber [bpnumber ...]
974 Disables the breakpoints given as a space separated list of
977 def help_ignore(self
):
978 print >>self
.stdout
, """ignore bpnumber count
979 Sets the ignore count for the given breakpoint number. A breakpoint
980 becomes active when the ignore count is zero. When non-zero, the
981 count is decremented each time the breakpoint is reached and the
982 breakpoint is not disabled and any associated condition evaluates
985 def help_condition(self
):
986 print >>self
.stdout
, """condition bpnumber str_condition
987 str_condition is a string specifying an expression which
988 must evaluate to true before the breakpoint is honored.
989 If str_condition is absent, any existing condition is removed;
990 i.e., the breakpoint is made unconditional."""
996 print >>self
.stdout
, """s(tep)
997 Execute the current line, stop at the first possible occasion
998 (either in a function that is called or in the current function)."""
1000 def help_until(self
):
1005 Continue execution until the line with a number greater than the current
1006 one is reached or until the current frame returns"""
1008 def help_next(self
):
1012 print >>self
.stdout
, """n(ext)
1013 Continue execution until the next line in the current function
1014 is reached or it returns."""
1016 def help_return(self
):
1020 print >>self
.stdout
, """r(eturn)
1021 Continue execution until the current function returns."""
1023 def help_continue(self
):
1026 def help_cont(self
):
1030 print >>self
.stdout
, """c(ont(inue))
1031 Continue execution, only stop when a breakpoint is encountered."""
1033 def help_jump(self
):
1037 print >>self
.stdout
, """j(ump) lineno
1038 Set the next line that will be executed."""
1040 def help_debug(self
):
1041 print >>self
.stdout
, """debug code
1042 Enter a recursive debugger that steps through the code argument
1043 (which is an arbitrary expression or statement to be executed
1044 in the current environment)."""
1046 def help_list(self
):
1050 print >>self
.stdout
, """l(ist) [first [,last]]
1051 List source code for the current file.
1052 Without arguments, list 11 lines around the current line
1053 or continue the previous listing.
1054 With one argument, list 11 lines starting at that line.
1055 With two arguments, list the given range;
1056 if the second argument is less than the first, it is a count."""
1058 def help_args(self
):
1062 print >>self
.stdout
, """a(rgs)
1063 Print the arguments of the current function."""
1066 print >>self
.stdout
, """p expression
1067 Print the value of the expression."""
1070 print >>self
.stdout
, """pp expression
1071 Pretty-print the value of the expression."""
1073 def help_exec(self
):
1074 print >>self
.stdout
, """(!) statement
1075 Execute the (one-line) statement in the context of
1076 the current stack frame.
1077 The exclamation point can be omitted unless the first word
1078 of the statement resembles a debugger command.
1079 To assign to a global variable you must always prefix the
1080 command with a 'global' command, e.g.:
1081 (Pdb) global list_options; list_options = ['-l']
1085 print """run [args...]
1086 Restart the debugged python program. If a string is supplied, it is
1087 splitted with "shlex" and the result is used as the new sys.argv.
1088 History, breakpoints, actions and debugger options are preserved.
1089 "restart" is an alias for "run"."""
1091 help_restart
= help_run
1093 def help_quit(self
):
1097 print >>self
.stdout
, """q(uit) or exit - Quit from the debugger.
1098 The program being executed is aborted."""
1102 def help_whatis(self
):
1103 print >>self
.stdout
, """whatis arg
1104 Prints the type of the argument."""
1107 print >>self
.stdout
, """EOF
1108 Handles the receipt of EOF as a command."""
1110 def help_alias(self
):
1111 print >>self
.stdout
, """alias [name [command [parameter parameter ...]]]
1112 Creates an alias called 'name' the executes 'command'. The command
1113 must *not* be enclosed in quotes. Replaceable parameters are
1114 indicated by %1, %2, and so on, while %* is replaced by all the
1115 parameters. If no command is given, the current alias for name
1116 is shown. If no name is given, all aliases are listed.
1118 Aliases may be nested and can contain anything that can be
1119 legally typed at the pdb prompt. Note! You *can* override
1120 internal pdb commands with aliases! Those internal commands
1121 are then hidden until the alias is removed. Aliasing is recursively
1122 applied to the first word of the command line; all other words
1123 in the line are left alone.
1125 Some useful aliases (especially when placed in the .pdbrc file) are:
1127 #Print instance variables (usage "pi classInst")
1128 alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
1130 #Print instance variables in self
1134 def help_unalias(self
):
1135 print >>self
.stdout
, """unalias name
1136 Deletes the specified alias."""
1138 def help_commands(self
):
1139 print >>self
.stdout
, """commands [bpnumber]
1144 Specify a list of commands for breakpoint number bpnumber. The
1145 commands themselves appear on the following lines. Type a line
1146 containing just 'end' to terminate the commands.
1148 To remove all commands from a breakpoint, type commands and
1149 follow it immediately with end; that is, give no commands.
1151 With no bpnumber argument, commands refers to the last
1154 You can use breakpoint commands to start your program up again.
1155 Simply use the continue command, or step, or any other
1156 command that resumes execution.
1158 Specifying any command resuming execution (currently continue,
1159 step, next, return, jump, quit and their abbreviations) terminates
1160 the command list (as if that command was immediately followed by end).
1161 This is because any time you resume execution
1162 (even with a simple next or step), you may encounter
1163 another breakpoint--which could have its own command list, leading to
1164 ambiguities about which list to execute.
1166 If you use the 'silent' command in the command list, the
1167 usual message about stopping at a breakpoint is not printed. This may
1168 be desirable for breakpoints that are to print a specific message and
1169 then continue. If none of the other commands print anything, you
1170 see no sign that the breakpoint was reached.
1176 def lookupmodule(self
, filename
):
1177 """Helper function for break/clear parsing -- may be overridden.
1179 lookupmodule() translates (possibly incomplete) file or module name
1180 into an absolute file name.
1182 if os
.path
.isabs(filename
) and os
.path
.exists(filename
):
1184 f
= os
.path
.join(sys
.path
[0], filename
)
1185 if os
.path
.exists(f
) and self
.canonic(f
) == self
.mainpyfile
:
1187 root
, ext
= os
.path
.splitext(filename
)
1189 filename
= filename
+ '.py'
1190 if os
.path
.isabs(filename
):
1192 for dirname
in sys
.path
:
1193 while os
.path
.islink(dirname
):
1194 dirname
= os
.readlink(dirname
)
1195 fullname
= os
.path
.join(dirname
, filename
)
1196 if os
.path
.exists(fullname
):
1200 def _runscript(self
, filename
):
1201 # The script has to run in __main__ namespace (or imports from
1202 # __main__ will break).
1204 # So we clear up the __main__ and set several special variables
1205 # (this gets rid of pdb's globals and cleans old variables on restarts).
1207 __main__
.__dict
__.clear()
1208 __main__
.__dict
__.update({"__name__" : "__main__",
1209 "__file__" : filename
,
1210 "__builtins__": __builtins__
,
1213 # When bdb sets tracing, a number of call and line events happens
1214 # BEFORE debugger even reaches user's code (and the exact sequence of
1215 # events depends on python version). So we take special measures to
1216 # avoid stopping before we reach the main script (see user_line and
1217 # user_call for details).
1218 self
._wait
_for
_mainpyfile
= 1
1219 self
.mainpyfile
= self
.canonic(filename
)
1220 self
._user
_requested
_quit
= 0
1221 statement
= 'execfile( "%s")' % filename
1224 # Simplified interface
1226 def run(statement
, globals=None, locals=None):
1227 Pdb().run(statement
, globals, locals)
1229 def runeval(expression
, globals=None, locals=None):
1230 return Pdb().runeval(expression
, globals, locals)
1232 def runctx(statement
, globals, locals):
1234 run(statement
, globals, locals)
1236 def runcall(*args
, **kwds
):
1237 return Pdb().runcall(*args
, **kwds
)
1240 Pdb().set_trace(sys
._getframe
().f_back
)
1242 # Post-Mortem interface
1244 def post_mortem(t
=None):
1245 # handling the default
1247 # sys.exc_info() returns (type, value, traceback) if an exception is
1248 # being handled, otherwise it returns None
1249 t
= sys
.exc_info()[2]
1251 raise ValueError("A valid traceback must be passed if no "
1252 "exception is being handled")
1256 p
.interaction(None, t
)
1259 post_mortem(sys
.last_traceback
)
1262 # Main program for testing
1264 TESTCMD
= 'import x; x.main()'
1271 for dirname
in sys
.path
:
1272 fullname
= os
.path
.join(dirname
, 'pdb.doc')
1273 if os
.path
.exists(fullname
):
1274 sts
= os
.system('${PAGER-more} '+fullname
)
1275 if sts
: print '*** Pager exit status:', sts
1278 print 'Sorry, can\'t find the help file "pdb.doc"',
1279 print 'along the Python search path'
1282 if not sys
.argv
[1:] or sys
.argv
[1] in ("--help", "-h"):
1283 print "usage: pdb.py scriptfile [arg] ..."
1286 mainpyfile
= sys
.argv
[1] # Get script filename
1287 if not os
.path
.exists(mainpyfile
):
1288 print 'Error:', mainpyfile
, 'does not exist'
1291 del sys
.argv
[0] # Hide "pdb.py" from argument list
1293 # Replace pdb's dir with script's dir in front of module search path.
1294 sys
.path
[0] = os
.path
.dirname(mainpyfile
)
1296 # Note on saving/restoring sys.argv: it's a good idea when sys.argv was
1297 # modified by the script being debugged. It's a bad idea when it was
1298 # changed by the user from the command line. There is a "restart" command
1299 # which allows explicit specification of command line arguments.
1303 pdb
._runscript
(mainpyfile
)
1304 if pdb
._user
_requested
_quit
:
1306 print "The program finished and will be restarted"
1308 print "Restarting", mainpyfile
, "with arguments:"
1309 print "\t" + " ".join(sys
.argv
[1:])
1311 # In most cases SystemExit does not warrant a post-mortem session.
1312 print "The program exited via sys.exit(). Exit status: ",
1313 print sys
.exc_info()[1]
1315 traceback
.print_exc()
1316 print "Uncaught exception. Entering post mortem debugging"
1317 print "Running 'cont' or 'step' will restart the program"
1318 t
= sys
.exc_info()[2]
1319 pdb
.interaction(None, t
)
1320 print "Post mortem debugger finished. The " + mainpyfile
+ \
1321 " will be restarted"
1324 # When invoked as main program, invoke the debugger on a script
1325 if __name__
== '__main__':