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.
215 def default(self
, line
):
216 if line
[:1] == '!': line
= line
[1:]
217 locals = self
.curframe_locals
218 globals = self
.curframe
.f_globals
220 code
= compile(line
+ '\n', '<stdin>', 'single')
221 save_stdout
= sys
.stdout
222 save_stdin
= sys
.stdin
223 save_displayhook
= sys
.displayhook
225 sys
.stdin
= self
.stdin
226 sys
.stdout
= self
.stdout
227 sys
.displayhook
= self
.displayhook
228 exec code
in globals, locals
230 sys
.stdout
= save_stdout
231 sys
.stdin
= save_stdin
232 sys
.displayhook
= save_displayhook
234 t
, v
= sys
.exc_info()[:2]
235 if type(t
) == type(''):
237 else: exc_type_name
= t
.__name
__
238 print >>self
.stdout
, '***', exc_type_name
+ ':', v
240 def precmd(self
, line
):
241 """Handle alias expansion and ';;' separator."""
245 while args
[0] in self
.aliases
:
246 line
= self
.aliases
[args
[0]]
248 for tmpArg
in args
[1:]:
249 line
= line
.replace("%" + str(ii
),
252 line
= line
.replace("%*", ' '.join(args
[1:]))
254 # split into ';;' separated commands
255 # unless it's an alias command
256 if args
[0] != 'alias':
257 marker
= line
.find(';;')
259 # queue up everything after marker
260 next
= line
[marker
+2:].lstrip()
261 self
.cmdqueue
.append(next
)
262 line
= line
[:marker
].rstrip()
265 def onecmd(self
, line
):
266 """Interpret the argument as though it had been typed in response
269 Checks whether this line is typed at the normal prompt or in
270 a breakpoint command list definition.
272 if not self
.commands_defining
:
273 return cmd
.Cmd
.onecmd(self
, line
)
275 return self
.handle_command_def(line
)
277 def handle_command_def(self
,line
):
278 """ Handles one command line during command list definition. """
279 cmd
, arg
, line
= self
.parseline(line
)
281 self
.commands_silent
[self
.commands_bnum
] = True
282 return # continue to handle other cmd def in the cmd list
285 return 1 # end of cmd list
286 cmdlist
= self
.commands
[self
.commands_bnum
]
288 cmdlist
.append(cmd
+' '+arg
)
291 # Determine if we must stop
293 func
= getattr(self
, 'do_' + cmd
)
294 except AttributeError:
296 # one of the resuming commands
297 if func
.func_name
in self
.commands_resuming
:
298 self
.commands_doprompt
[self
.commands_bnum
] = False
303 # Command definitions, called by cmdloop()
304 # The argument is the remaining string on the command line
305 # Return true to exit from the command loop
307 do_h
= cmd
.Cmd
.do_help
309 def do_commands(self
, arg
):
310 """Defines a list of commands associated to a breakpoint.
312 Those commands will be executed whenever the breakpoint causes
313 the program to stop execution."""
315 bnum
= len(bdb
.Breakpoint
.bpbynumber
)-1
320 print >>self
.stdout
, "Usage : commands [bnum]\n ..." \
323 self
.commands_bnum
= bnum
324 self
.commands
[bnum
] = []
325 self
.commands_doprompt
[bnum
] = True
326 self
.commands_silent
[bnum
] = False
327 prompt_back
= self
.prompt
328 self
.prompt
= '(com) '
329 self
.commands_defining
= True
331 self
.commands_defining
= False
332 self
.prompt
= prompt_back
334 def do_break(self
, arg
, temporary
= 0):
335 # break [ ([filename:]lineno | function) [, "condition"] ]
337 if self
.breaks
: # There's at least one
338 print >>self
.stdout
, "Num Type Disp Enb Where"
339 for bp
in bdb
.Breakpoint
.bpbynumber
:
341 bp
.bpprint(self
.stdout
)
343 # parse arguments; comma has lowest precedence
344 # and cannot occur in filename
348 comma
= arg
.find(',')
350 # parse stuff after comma: "condition"
351 cond
= arg
[comma
+1:].lstrip()
352 arg
= arg
[:comma
].rstrip()
353 # parse stuff before comma: [filename:]lineno | function
354 colon
= arg
.rfind(':')
357 filename
= arg
[:colon
].rstrip()
358 f
= self
.lookupmodule(filename
)
360 print >>self
.stdout
, '*** ', repr(filename
),
361 print >>self
.stdout
, 'not found from sys.path'
365 arg
= arg
[colon
+1:].lstrip()
368 except ValueError, msg
:
369 print >>self
.stdout
, '*** Bad lineno:', arg
372 # no colon; can be lineno or function
378 self
.curframe
.f_globals
,
379 self
.curframe_locals
)
383 if hasattr(func
, 'im_func'):
385 code
= func
.func_code
386 #use co_name to identify the bkpt (function names
387 #could be aliased, but co_name is invariant)
388 funcname
= code
.co_name
389 lineno
= code
.co_firstlineno
390 filename
= code
.co_filename
393 (ok
, filename
, ln
) = self
.lineinfo(arg
)
395 print >>self
.stdout
, '*** The specified object',
396 print >>self
.stdout
, repr(arg
),
397 print >>self
.stdout
, 'is not a function'
398 print >>self
.stdout
, 'or was not found along sys.path.'
400 funcname
= ok
# ok contains a function name
403 filename
= self
.defaultFile()
404 # Check for reasonable breakpoint
405 line
= self
.checkline(filename
, lineno
)
407 # now set the break point
408 err
= self
.set_break(filename
, line
, temporary
, cond
, funcname
)
409 if err
: print >>self
.stdout
, '***', err
411 bp
= self
.get_breaks(filename
, line
)[-1]
412 print >>self
.stdout
, "Breakpoint %d at %s:%d" % (bp
.number
,
416 # To be overridden in derived debuggers
417 def defaultFile(self
):
418 """Produce a reasonable default."""
419 filename
= self
.curframe
.f_code
.co_filename
420 if filename
== '<string>' and self
.mainpyfile
:
421 filename
= self
.mainpyfile
426 def do_tbreak(self
, arg
):
427 self
.do_break(arg
, 1)
429 def lineinfo(self
, identifier
):
430 failed
= (None, None, None)
431 # Input is identifier, may be in single quotes
432 idstring
= identifier
.split("'")
433 if len(idstring
) == 1:
434 # not in single quotes
435 id = idstring
[0].strip()
436 elif len(idstring
) == 3:
438 id = idstring
[1].strip()
441 if id == '': return failed
442 parts
= id.split('.')
443 # Protection for derived debuggers
444 if parts
[0] == 'self':
448 # Best first guess at file to look at
449 fname
= self
.defaultFile()
453 # More than one part.
454 # First is module, second is method/class
455 f
= self
.lookupmodule(parts
[0])
459 answer
= find_function(item
, fname
)
460 return answer
or failed
462 def checkline(self
, filename
, lineno
):
463 """Check whether specified line seems to be executable.
465 Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
466 line or EOF). Warning: testing is not comprehensive.
468 line
= linecache
.getline(filename
, lineno
, self
.curframe
.f_globals
)
470 print >>self
.stdout
, 'End of file'
473 # Don't allow setting breakpoint at a blank line
474 if (not line
or (line
[0] == '#') or
475 (line
[:3] == '"""') or line
[:3] == "'''"):
476 print >>self
.stdout
, '*** Blank or comment'
480 def do_enable(self
, arg
):
486 print >>self
.stdout
, 'Breakpoint index %r is not a number' % i
489 if not (0 <= i
< len(bdb
.Breakpoint
.bpbynumber
)):
490 print >>self
.stdout
, 'No breakpoint numbered', i
493 bp
= bdb
.Breakpoint
.bpbynumber
[i
]
497 def do_disable(self
, arg
):
503 print >>self
.stdout
, 'Breakpoint index %r is not a number' % i
506 if not (0 <= i
< len(bdb
.Breakpoint
.bpbynumber
)):
507 print >>self
.stdout
, 'No breakpoint numbered', i
510 bp
= bdb
.Breakpoint
.bpbynumber
[i
]
514 def do_condition(self
, arg
):
515 # arg is breakpoint number and condition
516 args
= arg
.split(' ', 1)
518 bpnum
= int(args
[0].strip())
520 # something went wrong
521 print >>self
.stdout
, \
522 'Breakpoint index %r is not a number' % args
[0]
529 bp
= bdb
.Breakpoint
.bpbynumber
[bpnum
]
531 print >>self
.stdout
, 'Breakpoint index %r is not valid' % args
[0]
536 print >>self
.stdout
, 'Breakpoint', bpnum
,
537 print >>self
.stdout
, 'is now unconditional.'
539 def do_ignore(self
,arg
):
540 """arg is bp number followed by ignore count."""
543 bpnum
= int(args
[0].strip())
545 # something went wrong
546 print >>self
.stdout
, \
547 'Breakpoint index %r is not a number' % args
[0]
550 count
= int(args
[1].strip())
554 bp
= bdb
.Breakpoint
.bpbynumber
[bpnum
]
556 print >>self
.stdout
, 'Breakpoint index %r is not valid' % args
[0]
561 reply
= 'Will ignore next '
563 reply
= reply
+ '%d crossings' % count
565 reply
= reply
+ '1 crossing'
566 print >>self
.stdout
, reply
+ ' of breakpoint %d.' % bpnum
568 print >>self
.stdout
, 'Will stop next time breakpoint',
569 print >>self
.stdout
, bpnum
, 'is reached.'
571 def do_clear(self
, arg
):
572 """Three possibilities, tried in this order:
573 clear -> clear all breaks, ask for confirmation
574 clear file:lineno -> clear all breaks at file:lineno
575 clear bpno bpno ... -> clear breakpoints by number"""
578 reply
= raw_input('Clear all breaks? ')
581 reply
= reply
.strip().lower()
582 if reply
in ('y', 'yes'):
583 self
.clear_all_breaks()
586 # Make sure it works for "clear C:\foo\bar.py:12"
593 err
= "Invalid line number (%s)" % arg
595 err
= self
.clear_break(filename
, lineno
)
596 if err
: print >>self
.stdout
, '***', err
598 numberlist
= arg
.split()
603 print >>self
.stdout
, 'Breakpoint index %r is not a number' % i
606 if not (0 <= i
< len(bdb
.Breakpoint
.bpbynumber
)):
607 print >>self
.stdout
, 'No breakpoint numbered', i
609 err
= self
.clear_bpbynumber(i
)
611 print >>self
.stdout
, '***', err
613 print >>self
.stdout
, 'Deleted breakpoint', i
614 do_cl
= do_clear
# 'c' is already an abbreviation for 'continue'
616 def do_where(self
, arg
):
617 self
.print_stack_trace()
621 def do_up(self
, arg
):
622 if self
.curindex
== 0:
623 print >>self
.stdout
, '*** Oldest frame'
625 self
.curindex
= self
.curindex
- 1
626 self
.curframe
= self
.stack
[self
.curindex
][0]
627 self
.curframe_locals
= self
.curframe
.f_locals
628 self
.print_stack_entry(self
.stack
[self
.curindex
])
632 def do_down(self
, arg
):
633 if self
.curindex
+ 1 == len(self
.stack
):
634 print >>self
.stdout
, '*** Newest frame'
636 self
.curindex
= self
.curindex
+ 1
637 self
.curframe
= self
.stack
[self
.curindex
][0]
638 self
.curframe_locals
= self
.curframe
.f_locals
639 self
.print_stack_entry(self
.stack
[self
.curindex
])
643 def do_until(self
, arg
):
644 self
.set_until(self
.curframe
)
648 def do_step(self
, arg
):
653 def do_next(self
, arg
):
654 self
.set_next(self
.curframe
)
658 def do_run(self
, arg
):
659 """Restart program by raising an exception to be caught in the main
660 debugger loop. If arguments were given, set them in sys.argv."""
663 argv0
= sys
.argv
[0:1]
664 sys
.argv
= shlex
.split(arg
)
670 def do_return(self
, arg
):
671 self
.set_return(self
.curframe
)
675 def do_continue(self
, arg
):
678 do_c
= do_cont
= do_continue
680 def do_jump(self
, arg
):
681 if self
.curindex
+ 1 != len(self
.stack
):
682 print >>self
.stdout
, "*** You can only jump within the bottom frame"
687 print >>self
.stdout
, "*** The 'jump' command requires a line number."
690 # Do the jump, fix up our copy of the stack, and display the
692 self
.curframe
.f_lineno
= arg
693 self
.stack
[self
.curindex
] = self
.stack
[self
.curindex
][0], arg
694 self
.print_stack_entry(self
.stack
[self
.curindex
])
695 except ValueError, e
:
696 print >>self
.stdout
, '*** Jump failed:', e
699 def do_debug(self
, arg
):
701 globals = self
.curframe
.f_globals
702 locals = self
.curframe_locals
703 p
= Pdb(self
.completekey
, self
.stdin
, self
.stdout
)
704 p
.prompt
= "(%s) " % self
.prompt
.strip()
705 print >>self
.stdout
, "ENTERING RECURSIVE DEBUGGER"
706 sys
.call_tracing(p
.run
, (arg
, globals, locals))
707 print >>self
.stdout
, "LEAVING RECURSIVE DEBUGGER"
708 sys
.settrace(self
.trace_dispatch
)
709 self
.lastcmd
= p
.lastcmd
711 def do_quit(self
, arg
):
712 self
._user
_requested
_quit
= 1
719 def do_EOF(self
, arg
):
721 self
._user
_requested
_quit
= 1
725 def do_args(self
, arg
):
726 co
= self
.curframe
.f_code
727 dict = self
.curframe_locals
729 if co
.co_flags
& 4: n
= n
+1
730 if co
.co_flags
& 8: n
= n
+1
732 name
= co
.co_varnames
[i
]
733 print >>self
.stdout
, name
, '=',
734 if name
in dict: print >>self
.stdout
, dict[name
]
735 else: print >>self
.stdout
, "*** undefined ***"
738 def do_retval(self
, arg
):
739 if '__return__' in self
.curframe_locals
:
740 print >>self
.stdout
, self
.curframe_locals
['__return__']
742 print >>self
.stdout
, '*** Not yet returned!'
745 def _getval(self
, arg
):
747 return eval(arg
, self
.curframe
.f_globals
,
748 self
.curframe_locals
)
750 t
, v
= sys
.exc_info()[:2]
751 if isinstance(t
, str):
753 else: exc_type_name
= t
.__name
__
754 print >>self
.stdout
, '***', exc_type_name
+ ':', repr(v
)
759 print >>self
.stdout
, repr(self
._getval
(arg
))
763 def do_pp(self
, arg
):
765 pprint
.pprint(self
._getval
(arg
), self
.stdout
)
769 def do_list(self
, arg
):
770 self
.lastcmd
= 'list'
774 x
= eval(arg
, {}, {})
775 if type(x
) == type(()):
780 # Assume it's a count
783 first
= max(1, int(x
) - 5)
785 print >>self
.stdout
, '*** Error in argument:', repr(arg
)
787 elif self
.lineno
is None:
788 first
= max(1, self
.curframe
.f_lineno
- 5)
790 first
= self
.lineno
+ 1
793 filename
= self
.curframe
.f_code
.co_filename
794 breaklist
= self
.get_file_breaks(filename
)
796 for lineno
in range(first
, last
+1):
797 line
= linecache
.getline(filename
, lineno
,
798 self
.curframe
.f_globals
)
800 print >>self
.stdout
, '[EOF]'
803 s
= repr(lineno
).rjust(3)
804 if len(s
) < 4: s
= s
+ ' '
805 if lineno
in breaklist
: s
= s
+ 'B'
807 if lineno
== self
.curframe
.f_lineno
:
809 print >>self
.stdout
, s
+ '\t' + line
,
811 except KeyboardInterrupt:
815 def do_whatis(self
, arg
):
817 value
= eval(arg
, self
.curframe
.f_globals
,
818 self
.curframe_locals
)
820 t
, v
= sys
.exc_info()[:2]
821 if type(t
) == type(''):
823 else: exc_type_name
= t
.__name
__
824 print >>self
.stdout
, '***', exc_type_name
+ ':', repr(v
)
828 try: code
= value
.func_code
831 print >>self
.stdout
, 'Function', code
.co_name
833 # Is it an instance method?
834 try: code
= value
.im_func
.func_code
837 print >>self
.stdout
, 'Method', code
.co_name
839 # None of the above...
840 print >>self
.stdout
, type(value
)
842 def do_alias(self
, arg
):
845 keys
= self
.aliases
.keys()
848 print >>self
.stdout
, "%s = %s" % (alias
, self
.aliases
[alias
])
850 if args
[0] in self
.aliases
and len(args
) == 1:
851 print >>self
.stdout
, "%s = %s" % (args
[0], self
.aliases
[args
[0]])
853 self
.aliases
[args
[0]] = ' '.join(args
[1:])
855 def do_unalias(self
, arg
):
857 if len(args
) == 0: return
858 if args
[0] in self
.aliases
:
859 del self
.aliases
[args
[0]]
861 #list of all the commands making the program resume execution.
862 commands_resuming
= ['do_continue', 'do_step', 'do_next', 'do_return',
863 'do_quit', 'do_jump']
865 # Print a traceback starting at the top stack frame.
866 # The most recently entered frame is printed last;
867 # this is different from dbx and gdb, but consistent with
868 # the Python interpreter's stack trace.
869 # It is also consistent with the up/down commands (which are
870 # compatible with dbx and gdb: up moves towards 'main()'
871 # and down moves towards the most recent stack frame).
873 def print_stack_trace(self
):
875 for frame_lineno
in self
.stack
:
876 self
.print_stack_entry(frame_lineno
)
877 except KeyboardInterrupt:
880 def print_stack_entry(self
, frame_lineno
, prompt_prefix
=line_prefix
):
881 frame
, lineno
= frame_lineno
882 if frame
is self
.curframe
:
883 print >>self
.stdout
, '>',
885 print >>self
.stdout
, ' ',
886 print >>self
.stdout
, self
.format_stack_entry(frame_lineno
,
890 # Help methods (derived from pdb.doc)
896 print >>self
.stdout
, """h(elp)
897 Without argument, print the list of available commands.
898 With a command name as argument, print help about that command
899 "help pdb" pipes the full documentation file to the $PAGER
900 "help exec" gives help on the ! command"""
902 def help_where(self
):
906 print >>self
.stdout
, """w(here)
907 Print a stack trace, with the most recent frame at the bottom.
908 An arrow indicates the "current frame", which determines the
909 context of most commands. 'bt' is an alias for this command."""
917 print >>self
.stdout
, """d(own)
918 Move the current frame one level down in the stack trace
919 (to a newer frame)."""
925 print >>self
.stdout
, """u(p)
926 Move the current frame one level up in the stack trace
927 (to an older frame)."""
929 def help_break(self
):
933 print >>self
.stdout
, """b(reak) ([file:]lineno | function) [, condition]
934 With a line number argument, set a break there in the current
935 file. With a function name, set a break at first executable line
936 of that function. Without argument, list all breaks. If a second
937 argument is present, it is a string specifying an expression
938 which must evaluate to true before the breakpoint is honored.
940 The line number may be prefixed with a filename and a colon,
941 to specify a breakpoint in another file (probably one that
942 hasn't been loaded yet). The file is searched for on sys.path;
943 the .py suffix may be omitted."""
945 def help_clear(self
):
949 print >>self
.stdout
, "cl(ear) filename:lineno"
950 print >>self
.stdout
, """cl(ear) [bpnumber [bpnumber...]]
951 With a space separated list of breakpoint numbers, clear
952 those breakpoints. Without argument, clear all breaks (but
953 first ask confirmation). With a filename:lineno argument,
954 clear all breaks at that line in that file.
956 Note that the argument is different from previous versions of
957 the debugger (in python distributions 1.5.1 and before) where
958 a linenumber was used instead of either filename:lineno or
959 breakpoint numbers."""
961 def help_tbreak(self
):
962 print >>self
.stdout
, """tbreak same arguments as break, but breakpoint
963 is removed when first hit."""
965 def help_enable(self
):
966 print >>self
.stdout
, """enable bpnumber [bpnumber ...]
967 Enables the breakpoints given as a space separated list of
970 def help_disable(self
):
971 print >>self
.stdout
, """disable bpnumber [bpnumber ...]
972 Disables the breakpoints given as a space separated list of
975 def help_ignore(self
):
976 print >>self
.stdout
, """ignore bpnumber count
977 Sets the ignore count for the given breakpoint number. A breakpoint
978 becomes active when the ignore count is zero. When non-zero, the
979 count is decremented each time the breakpoint is reached and the
980 breakpoint is not disabled and any associated condition evaluates
983 def help_condition(self
):
984 print >>self
.stdout
, """condition bpnumber str_condition
985 str_condition is a string specifying an expression which
986 must evaluate to true before the breakpoint is honored.
987 If str_condition is absent, any existing condition is removed;
988 i.e., the breakpoint is made unconditional."""
994 print >>self
.stdout
, """s(tep)
995 Execute the current line, stop at the first possible occasion
996 (either in a function that is called or in the current function)."""
998 def help_until(self
):
1003 Continue execution until the line with a number greater than the current
1004 one is reached or until the current frame returns"""
1006 def help_next(self
):
1010 print >>self
.stdout
, """n(ext)
1011 Continue execution until the next line in the current function
1012 is reached or it returns."""
1014 def help_return(self
):
1018 print >>self
.stdout
, """r(eturn)
1019 Continue execution until the current function returns."""
1021 def help_continue(self
):
1024 def help_cont(self
):
1028 print >>self
.stdout
, """c(ont(inue))
1029 Continue execution, only stop when a breakpoint is encountered."""
1031 def help_jump(self
):
1035 print >>self
.stdout
, """j(ump) lineno
1036 Set the next line that will be executed."""
1038 def help_debug(self
):
1039 print >>self
.stdout
, """debug code
1040 Enter a recursive debugger that steps through the code argument
1041 (which is an arbitrary expression or statement to be executed
1042 in the current environment)."""
1044 def help_list(self
):
1048 print >>self
.stdout
, """l(ist) [first [,last]]
1049 List source code for the current file.
1050 Without arguments, list 11 lines around the current line
1051 or continue the previous listing.
1052 With one argument, list 11 lines starting at that line.
1053 With two arguments, list the given range;
1054 if the second argument is less than the first, it is a count."""
1056 def help_args(self
):
1060 print >>self
.stdout
, """a(rgs)
1061 Print the arguments of the current function."""
1064 print >>self
.stdout
, """p expression
1065 Print the value of the expression."""
1068 print >>self
.stdout
, """pp expression
1069 Pretty-print the value of the expression."""
1071 def help_exec(self
):
1072 print >>self
.stdout
, """(!) statement
1073 Execute the (one-line) statement in the context of
1074 the current stack frame.
1075 The exclamation point can be omitted unless the first word
1076 of the statement resembles a debugger command.
1077 To assign to a global variable you must always prefix the
1078 command with a 'global' command, e.g.:
1079 (Pdb) global list_options; list_options = ['-l']
1083 print """run [args...]
1084 Restart the debugged python program. If a string is supplied, it is
1085 splitted with "shlex" and the result is used as the new sys.argv.
1086 History, breakpoints, actions and debugger options are preserved.
1087 "restart" is an alias for "run"."""
1089 help_restart
= help_run
1091 def help_quit(self
):
1095 print >>self
.stdout
, """q(uit) or exit - Quit from the debugger.
1096 The program being executed is aborted."""
1100 def help_whatis(self
):
1101 print >>self
.stdout
, """whatis arg
1102 Prints the type of the argument."""
1105 print >>self
.stdout
, """EOF
1106 Handles the receipt of EOF as a command."""
1108 def help_alias(self
):
1109 print >>self
.stdout
, """alias [name [command [parameter parameter ...]]]
1110 Creates an alias called 'name' the executes 'command'. The command
1111 must *not* be enclosed in quotes. Replaceable parameters are
1112 indicated by %1, %2, and so on, while %* is replaced by all the
1113 parameters. If no command is given, the current alias for name
1114 is shown. If no name is given, all aliases are listed.
1116 Aliases may be nested and can contain anything that can be
1117 legally typed at the pdb prompt. Note! You *can* override
1118 internal pdb commands with aliases! Those internal commands
1119 are then hidden until the alias is removed. Aliasing is recursively
1120 applied to the first word of the command line; all other words
1121 in the line are left alone.
1123 Some useful aliases (especially when placed in the .pdbrc file) are:
1125 #Print instance variables (usage "pi classInst")
1126 alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
1128 #Print instance variables in self
1132 def help_unalias(self
):
1133 print >>self
.stdout
, """unalias name
1134 Deletes the specified alias."""
1136 def help_commands(self
):
1137 print >>self
.stdout
, """commands [bpnumber]
1142 Specify a list of commands for breakpoint number bpnumber. The
1143 commands themselves appear on the following lines. Type a line
1144 containing just 'end' to terminate the commands.
1146 To remove all commands from a breakpoint, type commands and
1147 follow it immediately with end; that is, give no commands.
1149 With no bpnumber argument, commands refers to the last
1152 You can use breakpoint commands to start your program up again.
1153 Simply use the continue command, or step, or any other
1154 command that resumes execution.
1156 Specifying any command resuming execution (currently continue,
1157 step, next, return, jump, quit and their abbreviations) terminates
1158 the command list (as if that command was immediately followed by end).
1159 This is because any time you resume execution
1160 (even with a simple next or step), you may encounter
1161 another breakpoint--which could have its own command list, leading to
1162 ambiguities about which list to execute.
1164 If you use the 'silent' command in the command list, the
1165 usual message about stopping at a breakpoint is not printed. This may
1166 be desirable for breakpoints that are to print a specific message and
1167 then continue. If none of the other commands print anything, you
1168 see no sign that the breakpoint was reached.
1174 def lookupmodule(self
, filename
):
1175 """Helper function for break/clear parsing -- may be overridden.
1177 lookupmodule() translates (possibly incomplete) file or module name
1178 into an absolute file name.
1180 if os
.path
.isabs(filename
) and os
.path
.exists(filename
):
1182 f
= os
.path
.join(sys
.path
[0], filename
)
1183 if os
.path
.exists(f
) and self
.canonic(f
) == self
.mainpyfile
:
1185 root
, ext
= os
.path
.splitext(filename
)
1187 filename
= filename
+ '.py'
1188 if os
.path
.isabs(filename
):
1190 for dirname
in sys
.path
:
1191 while os
.path
.islink(dirname
):
1192 dirname
= os
.readlink(dirname
)
1193 fullname
= os
.path
.join(dirname
, filename
)
1194 if os
.path
.exists(fullname
):
1198 def _runscript(self
, filename
):
1199 # The script has to run in __main__ namespace (or imports from
1200 # __main__ will break).
1202 # So we clear up the __main__ and set several special variables
1203 # (this gets rid of pdb's globals and cleans old variables on restarts).
1205 __main__
.__dict
__.clear()
1206 __main__
.__dict
__.update({"__name__" : "__main__",
1207 "__file__" : filename
,
1208 "__builtins__": __builtins__
,
1211 # When bdb sets tracing, a number of call and line events happens
1212 # BEFORE debugger even reaches user's code (and the exact sequence of
1213 # events depends on python version). So we take special measures to
1214 # avoid stopping before we reach the main script (see user_line and
1215 # user_call for details).
1216 self
._wait
_for
_mainpyfile
= 1
1217 self
.mainpyfile
= self
.canonic(filename
)
1218 self
._user
_requested
_quit
= 0
1219 statement
= 'execfile( "%s")' % filename
1222 # Simplified interface
1224 def run(statement
, globals=None, locals=None):
1225 Pdb().run(statement
, globals, locals)
1227 def runeval(expression
, globals=None, locals=None):
1228 return Pdb().runeval(expression
, globals, locals)
1230 def runctx(statement
, globals, locals):
1232 run(statement
, globals, locals)
1234 def runcall(*args
, **kwds
):
1235 return Pdb().runcall(*args
, **kwds
)
1238 Pdb().set_trace(sys
._getframe
().f_back
)
1240 # Post-Mortem interface
1242 def post_mortem(t
=None):
1243 # handling the default
1245 # sys.exc_info() returns (type, value, traceback) if an exception is
1246 # being handled, otherwise it returns None
1247 t
= sys
.exc_info()[2]
1249 raise ValueError("A valid traceback must be passed if no "
1250 "exception is being handled")
1254 p
.interaction(None, t
)
1257 post_mortem(sys
.last_traceback
)
1260 # Main program for testing
1262 TESTCMD
= 'import x; x.main()'
1269 for dirname
in sys
.path
:
1270 fullname
= os
.path
.join(dirname
, 'pdb.doc')
1271 if os
.path
.exists(fullname
):
1272 sts
= os
.system('${PAGER-more} '+fullname
)
1273 if sts
: print '*** Pager exit status:', sts
1276 print 'Sorry, can\'t find the help file "pdb.doc"',
1277 print 'along the Python search path'
1280 if not sys
.argv
[1:] or sys
.argv
[1] in ("--help", "-h"):
1281 print "usage: pdb.py scriptfile [arg] ..."
1284 mainpyfile
= sys
.argv
[1] # Get script filename
1285 if not os
.path
.exists(mainpyfile
):
1286 print 'Error:', mainpyfile
, 'does not exist'
1289 del sys
.argv
[0] # Hide "pdb.py" from argument list
1291 # Replace pdb's dir with script's dir in front of module search path.
1292 sys
.path
[0] = os
.path
.dirname(mainpyfile
)
1294 # Note on saving/restoring sys.argv: it's a good idea when sys.argv was
1295 # modified by the script being debugged. It's a bad idea when it was
1296 # changed by the user from the command line. There is a "restart" command
1297 # which allows explicit specification of command line arguments.
1301 pdb
._runscript
(mainpyfile
)
1302 if pdb
._user
_requested
_quit
:
1304 print "The program finished and will be restarted"
1306 print "Restarting", mainpyfile
, "with arguments:"
1307 print "\t" + " ".join(sys
.argv
[1:])
1309 # In most cases SystemExit does not warrant a post-mortem session.
1310 print "The program exited via sys.exit(). Exit status: ",
1311 print sys
.exc_info()[1]
1313 traceback
.print_exc()
1314 print "Uncaught exception. Entering post mortem debugging"
1315 print "Running 'cont' or 'step' will restart the program"
1316 t
= sys
.exc_info()[2]
1317 pdb
.interaction(None, t
)
1318 print "Post mortem debugger finished. The " + mainpyfile
+ \
1319 " will be restarted"
1322 # When invoked as main program, invoke the debugger on a script
1323 if __name__
== '__main__':