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('--Call--', file=self
.stdout
)
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('--Return--', file=self
.stdout
)
176 self
.interaction(frame
, None)
178 def user_exception(self
, frame
, exc_info
):
179 """This function is called if an exception occurs,
180 but only if we are to stop at or just below this level."""
181 exc_type
, exc_value
, exc_traceback
= exc_info
182 frame
.f_locals
['__exception__'] = exc_type
, exc_value
183 exc_type_name
= exc_type
.__name
__
184 print(exc_type_name
+ ':', _saferepr(exc_value
), file=self
.stdout
)
185 self
.interaction(frame
, exc_traceback
)
187 # General interaction function
189 def interaction(self
, frame
, traceback
):
190 self
.setup(frame
, traceback
)
191 self
.print_stack_entry(self
.stack
[self
.curindex
])
195 def default(self
, line
):
196 if line
[:1] == '!': line
= line
[1:]
197 locals = self
.curframe
.f_locals
198 globals = self
.curframe
.f_globals
200 code
= compile(line
+ '\n', '<stdin>', 'single')
201 save_stdout
= sys
.stdout
202 save_stdin
= sys
.stdin
204 sys
.stdin
= self
.stdin
205 sys
.stdout
= self
.stdout
206 exec(code
, globals, locals)
208 sys
.stdout
= save_stdout
209 sys
.stdin
= save_stdin
211 t
, v
= sys
.exc_info()[:2]
212 if type(t
) == type(''):
214 else: exc_type_name
= t
.__name
__
215 print('***', exc_type_name
+ ':', v
, file=self
.stdout
)
217 def precmd(self
, line
):
218 """Handle alias expansion and ';;' separator."""
222 while args
[0] in self
.aliases
:
223 line
= self
.aliases
[args
[0]]
225 for tmpArg
in args
[1:]:
226 line
= line
.replace("%" + str(ii
),
229 line
= line
.replace("%*", ' '.join(args
[1:]))
231 # split into ';;' separated commands
232 # unless it's an alias command
233 if args
[0] != 'alias':
234 marker
= line
.find(';;')
236 # queue up everything after marker
237 next
= line
[marker
+2:].lstrip()
238 self
.cmdqueue
.append(next
)
239 line
= line
[:marker
].rstrip()
242 def onecmd(self
, line
):
243 """Interpret the argument as though it had been typed in response
246 Checks whether this line is typed at the normal prompt or in
247 a breakpoint command list definition.
249 if not self
.commands_defining
:
250 return cmd
.Cmd
.onecmd(self
, line
)
252 return self
.handle_command_def(line
)
254 def handle_command_def(self
,line
):
255 """ Handles one command line during command list definition. """
256 cmd
, arg
, line
= self
.parseline(line
)
258 self
.commands_silent
[self
.commands_bnum
] = True
259 return # continue to handle other cmd def in the cmd list
262 return 1 # end of cmd list
263 cmdlist
= self
.commands
[self
.commands_bnum
]
265 cmdlist
.append(cmd
+' '+arg
)
268 # Determine if we must stop
270 func
= getattr(self
, 'do_' + cmd
)
271 except AttributeError:
273 if func
.__name
__ in self
.commands_resuming
: # one of the resuming commands.
274 self
.commands_doprompt
[self
.commands_bnum
] = False
279 # Command definitions, called by cmdloop()
280 # The argument is the remaining string on the command line
281 # Return true to exit from the command loop
283 do_h
= cmd
.Cmd
.do_help
285 def do_commands(self
, arg
):
286 """Defines a list of commands associated to a breakpoint
287 Those commands will be executed whenever the breakpoint causes the program to stop execution."""
289 bnum
= len(bdb
.Breakpoint
.bpbynumber
)-1
294 print("Usage : commands [bnum]\n ...\n end", file=self
.stdout
)
296 self
.commands_bnum
= bnum
297 self
.commands
[bnum
] = []
298 self
.commands_doprompt
[bnum
] = True
299 self
.commands_silent
[bnum
] = False
300 prompt_back
= self
.prompt
301 self
.prompt
= '(com) '
302 self
.commands_defining
= True
304 self
.commands_defining
= False
305 self
.prompt
= prompt_back
307 def do_break(self
, arg
, temporary
= 0):
308 # break [ ([filename:]lineno | function) [, "condition"] ]
310 if self
.breaks
: # There's at least one
311 print("Num Type Disp Enb Where", file=self
.stdout
)
312 for bp
in bdb
.Breakpoint
.bpbynumber
:
314 bp
.bpprint(self
.stdout
)
316 # parse arguments; comma has lowest precedence
317 # and cannot occur in filename
321 comma
= arg
.find(',')
323 # parse stuff after comma: "condition"
324 cond
= arg
[comma
+1:].lstrip()
325 arg
= arg
[:comma
].rstrip()
326 # parse stuff before comma: [filename:]lineno | function
327 colon
= arg
.rfind(':')
330 filename
= arg
[:colon
].rstrip()
331 f
= self
.lookupmodule(filename
)
333 print('*** ', repr(filename
), end
=' ', file=self
.stdout
)
334 print('not found from sys.path', file=self
.stdout
)
338 arg
= arg
[colon
+1:].lstrip()
341 except ValueError as msg
:
342 print('*** Bad lineno:', arg
, file=self
.stdout
)
345 # no colon; can be lineno or function
351 self
.curframe
.f_globals
,
352 self
.curframe
.f_locals
)
356 if hasattr(func
, '__func__'):
359 #use co_name to identify the bkpt (function names
360 #could be aliased, but co_name is invariant)
361 funcname
= code
.co_name
362 lineno
= code
.co_firstlineno
363 filename
= code
.co_filename
366 (ok
, filename
, ln
) = self
.lineinfo(arg
)
368 print('*** The specified object', end
=' ', file=self
.stdout
)
369 print(repr(arg
), end
=' ', file=self
.stdout
)
370 print('is not a function', file=self
.stdout
)
371 print('or was not found along sys.path.', file=self
.stdout
)
373 funcname
= ok
# ok contains a function name
376 filename
= self
.defaultFile()
377 # Check for reasonable breakpoint
378 line
= self
.checkline(filename
, lineno
)
380 # now set the break point
381 err
= self
.set_break(filename
, line
, temporary
, cond
, funcname
)
382 if err
: print('***', err
, file=self
.stdout
)
384 bp
= self
.get_breaks(filename
, line
)[-1]
385 print("Breakpoint %d at %s:%d" % (bp
.number
,
387 bp
.line
), file=self
.stdout
)
389 # To be overridden in derived debuggers
390 def defaultFile(self
):
391 """Produce a reasonable default."""
392 filename
= self
.curframe
.f_code
.co_filename
393 if filename
== '<string>' and self
.mainpyfile
:
394 filename
= self
.mainpyfile
399 def do_tbreak(self
, arg
):
400 self
.do_break(arg
, 1)
402 def lineinfo(self
, identifier
):
403 failed
= (None, None, None)
404 # Input is identifier, may be in single quotes
405 idstring
= identifier
.split("'")
406 if len(idstring
) == 1:
407 # not in single quotes
408 id = idstring
[0].strip()
409 elif len(idstring
) == 3:
411 id = idstring
[1].strip()
414 if id == '': return failed
415 parts
= id.split('.')
416 # Protection for derived debuggers
417 if parts
[0] == 'self':
421 # Best first guess at file to look at
422 fname
= self
.defaultFile()
426 # More than one part.
427 # First is module, second is method/class
428 f
= self
.lookupmodule(parts
[0])
432 answer
= find_function(item
, fname
)
433 return answer
or failed
435 def checkline(self
, filename
, lineno
):
436 """Check whether specified line seems to be executable.
438 Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
439 line or EOF). Warning: testing is not comprehensive.
441 line
= linecache
.getline(filename
, lineno
)
443 print('End of file', file=self
.stdout
)
446 # Don't allow setting breakpoint at a blank line
447 if (not line
or (line
[0] == '#') or
448 (line
[:3] == '"""') or line
[:3] == "'''"):
449 print('*** Blank or comment', file=self
.stdout
)
453 def do_enable(self
, arg
):
459 print('Breakpoint index %r is not a number' % i
, file=self
.stdout
)
462 if not (0 <= i
< len(bdb
.Breakpoint
.bpbynumber
)):
463 print('No breakpoint numbered', i
, file=self
.stdout
)
466 bp
= bdb
.Breakpoint
.bpbynumber
[i
]
470 def do_disable(self
, arg
):
476 print('Breakpoint index %r is not a number' % i
, file=self
.stdout
)
479 if not (0 <= i
< len(bdb
.Breakpoint
.bpbynumber
)):
480 print('No breakpoint numbered', i
, file=self
.stdout
)
483 bp
= bdb
.Breakpoint
.bpbynumber
[i
]
487 def do_condition(self
, arg
):
488 # arg is breakpoint number and condition
489 args
= arg
.split(' ', 1)
491 bpnum
= int(args
[0].strip())
493 # something went wrong
494 print('Breakpoint index %r is not a number' % args
[0], file=self
.stdout
)
501 bp
= bdb
.Breakpoint
.bpbynumber
[bpnum
]
503 print >>self
.stdout
, 'Breakpoint index %r is not valid' % args
[0]
508 print('Breakpoint', bpnum
, end
=' ', file=self
.stdout
)
509 print('is now unconditional.', file=self
.stdout
)
511 def do_ignore(self
,arg
):
512 """arg is bp number followed by ignore count."""
515 bpnum
= int(args
[0].strip())
517 # something went wrong
518 print('Breakpoint index %r is not a number' % args
[0], file=self
.stdout
)
521 count
= int(args
[1].strip())
525 bp
= bdb
.Breakpoint
.bpbynumber
[bpnum
]
527 print >>self
.stdout
, 'Breakpoint index %r is not valid' % args
[0]
532 reply
= 'Will ignore next '
534 reply
= reply
+ '%d crossings' % count
536 reply
= reply
+ '1 crossing'
537 print(reply
+ ' of breakpoint %d.' % bpnum
, file=self
.stdout
)
539 print('Will stop next time breakpoint', end
=' ', file=self
.stdout
)
540 print(bpnum
, 'is reached.', file=self
.stdout
)
542 def do_clear(self
, arg
):
543 """Three possibilities, tried in this order:
544 clear -> clear all breaks, ask for confirmation
545 clear file:lineno -> clear all breaks at file:lineno
546 clear bpno bpno ... -> clear breakpoints by number"""
549 reply
= input('Clear all breaks? ')
552 reply
= reply
.strip().lower()
553 if reply
in ('y', 'yes'):
554 self
.clear_all_breaks()
557 # Make sure it works for "clear C:\foo\bar.py:12"
564 err
= "Invalid line number (%s)" % arg
566 err
= self
.clear_break(filename
, lineno
)
567 if err
: print('***', err
, file=self
.stdout
)
569 numberlist
= arg
.split()
574 print('Breakpoint index %r is not a number' % i
, file=self
.stdout
)
577 if not (0 <= i
< len(bdb
.Breakpoint
.bpbynumber
)):
578 print('No breakpoint numbered', i
, file=self
.stdout
)
580 err
= self
.clear_bpbynumber(i
)
582 print('***', err
, file=self
.stdout
)
584 print('Deleted breakpoint', i
, file=self
.stdout
)
585 do_cl
= do_clear
# 'c' is already an abbreviation for 'continue'
587 def do_where(self
, arg
):
588 self
.print_stack_trace()
592 def do_up(self
, arg
):
593 if self
.curindex
== 0:
594 print('*** Oldest frame', file=self
.stdout
)
596 self
.curindex
= self
.curindex
- 1
597 self
.curframe
= self
.stack
[self
.curindex
][0]
598 self
.print_stack_entry(self
.stack
[self
.curindex
])
602 def do_down(self
, arg
):
603 if self
.curindex
+ 1 == len(self
.stack
):
604 print('*** Newest frame', file=self
.stdout
)
606 self
.curindex
= self
.curindex
+ 1
607 self
.curframe
= self
.stack
[self
.curindex
][0]
608 self
.print_stack_entry(self
.stack
[self
.curindex
])
612 def do_step(self
, arg
):
617 def do_next(self
, arg
):
618 self
.set_next(self
.curframe
)
622 def do_run(self
, arg
):
623 """Restart program by raising an exception to be caught in the main debugger
624 loop. If arguments were given, set them in sys.argv."""
627 argv0
= sys
.argv
[0:1]
628 sys
.argv
= shlex
.split(arg
)
634 def do_return(self
, arg
):
635 self
.set_return(self
.curframe
)
639 def do_continue(self
, arg
):
642 do_c
= do_cont
= do_continue
644 def do_jump(self
, arg
):
645 if self
.curindex
+ 1 != len(self
.stack
):
646 print("*** You can only jump within the bottom frame", file=self
.stdout
)
651 print("*** The 'jump' command requires a line number.", file=self
.stdout
)
654 # Do the jump, fix up our copy of the stack, and display the
656 self
.curframe
.f_lineno
= arg
657 self
.stack
[self
.curindex
] = self
.stack
[self
.curindex
][0], arg
658 self
.print_stack_entry(self
.stack
[self
.curindex
])
659 except ValueError as e
:
660 print('*** Jump failed:', e
, file=self
.stdout
)
663 def do_debug(self
, arg
):
665 globals = self
.curframe
.f_globals
666 locals = self
.curframe
.f_locals
667 p
= Pdb(self
.completekey
, self
.stdin
, self
.stdout
)
668 p
.prompt
= "(%s) " % self
.prompt
.strip()
669 print("ENTERING RECURSIVE DEBUGGER", file=self
.stdout
)
670 sys
.call_tracing(p
.run
, (arg
, globals, locals))
671 print("LEAVING RECURSIVE DEBUGGER", file=self
.stdout
)
672 sys
.settrace(self
.trace_dispatch
)
673 self
.lastcmd
= p
.lastcmd
675 def do_quit(self
, arg
):
676 self
._user
_requested
_quit
= 1
683 def do_EOF(self
, arg
):
684 print(file=self
.stdout
)
685 self
._user
_requested
_quit
= 1
689 def do_args(self
, arg
):
694 if co
.co_flags
& 4: n
= n
+1
695 if co
.co_flags
& 8: n
= n
+1
697 name
= co
.co_varnames
[i
]
698 print(name
, '=', end
=' ', file=self
.stdout
)
699 if name
in dict: print(dict[name
], file=self
.stdout
)
700 else: print("*** undefined ***", file=self
.stdout
)
703 def do_retval(self
, arg
):
704 if '__return__' in self
.curframe
.f_locals
:
705 print(self
.curframe
.f_locals
['__return__'], file=self
.stdout
)
707 print('*** Not yet returned!', file=self
.stdout
)
710 def _getval(self
, arg
):
712 return eval(arg
, self
.curframe
.f_globals
,
713 self
.curframe
.f_locals
)
715 t
, v
= sys
.exc_info()[:2]
716 if isinstance(t
, str):
718 else: exc_type_name
= t
.__name
__
719 print('***', exc_type_name
+ ':', repr(v
), file=self
.stdout
)
724 print(repr(self
._getval
(arg
)), file=self
.stdout
)
727 # make "print" an alias of "p" since print isn't a Python statement anymore
730 def do_pp(self
, arg
):
732 pprint
.pprint(self
._getval
(arg
), self
.stdout
)
736 def do_list(self
, arg
):
737 self
.lastcmd
= 'list'
741 x
= eval(arg
, {}, {})
742 if type(x
) == type(()):
747 # Assume it's a count
750 first
= max(1, int(x
) - 5)
752 print('*** Error in argument:', repr(arg
), file=self
.stdout
)
754 elif self
.lineno
is None:
755 first
= max(1, self
.curframe
.f_lineno
- 5)
757 first
= self
.lineno
+ 1
760 filename
= self
.curframe
.f_code
.co_filename
761 breaklist
= self
.get_file_breaks(filename
)
763 for lineno
in range(first
, last
+1):
764 line
= linecache
.getline(filename
, lineno
)
766 print('[EOF]', file=self
.stdout
)
769 s
= repr(lineno
).rjust(3)
770 if len(s
) < 4: s
= s
+ ' '
771 if lineno
in breaklist
: s
= s
+ 'B'
773 if lineno
== self
.curframe
.f_lineno
:
775 print(s
+ '\t' + line
, end
='', file=self
.stdout
)
777 except KeyboardInterrupt:
781 def do_whatis(self
, arg
):
783 value
= eval(arg
, self
.curframe
.f_globals
,
784 self
.curframe
.f_locals
)
786 t
, v
= sys
.exc_info()[:2]
787 if type(t
) == type(''):
789 else: exc_type_name
= t
.__name
__
790 print('***', exc_type_name
+ ':', repr(v
), file=self
.stdout
)
794 try: code
= value
.__code
__
797 print('Function', code
.co_name
, file=self
.stdout
)
799 # Is it an instance method?
800 try: code
= value
.__func
__.__code
__
803 print('Method', code
.co_name
, file=self
.stdout
)
805 # None of the above...
806 print(type(value
), file=self
.stdout
)
808 def do_alias(self
, arg
):
811 keys
= self
.aliases
.keys()
814 print("%s = %s" % (alias
, self
.aliases
[alias
]), file=self
.stdout
)
816 if args
[0] in self
.aliases
and len(args
) == 1:
817 print("%s = %s" % (args
[0], self
.aliases
[args
[0]]), file=self
.stdout
)
819 self
.aliases
[args
[0]] = ' '.join(args
[1:])
821 def do_unalias(self
, arg
):
823 if len(args
) == 0: return
824 if args
[0] in self
.aliases
:
825 del self
.aliases
[args
[0]]
827 #list of all the commands making the program resume execution.
828 commands_resuming
= ['do_continue', 'do_step', 'do_next', 'do_return',
829 'do_quit', 'do_jump']
831 # Print a traceback starting at the top stack frame.
832 # The most recently entered frame is printed last;
833 # this is different from dbx and gdb, but consistent with
834 # the Python interpreter's stack trace.
835 # It is also consistent with the up/down commands (which are
836 # compatible with dbx and gdb: up moves towards 'main()'
837 # and down moves towards the most recent stack frame).
839 def print_stack_trace(self
):
841 for frame_lineno
in self
.stack
:
842 self
.print_stack_entry(frame_lineno
)
843 except KeyboardInterrupt:
846 def print_stack_entry(self
, frame_lineno
, prompt_prefix
=line_prefix
):
847 frame
, lineno
= frame_lineno
848 if frame
is self
.curframe
:
849 print('>', end
=' ', file=self
.stdout
)
851 print(' ', end
=' ', file=self
.stdout
)
852 print(self
.format_stack_entry(frame_lineno
,
853 prompt_prefix
), file=self
.stdout
)
856 # Help methods (derived from pdb.doc)
863 Without argument, print the list of available commands.
864 With a command name as argument, print help about that command
865 "help pdb" pipes the full documentation file to the $PAGER
866 "help exec" gives help on the ! command""", file=self
.stdout
)
868 def help_where(self
):
873 Print a stack trace, with the most recent frame at the bottom.
874 An arrow indicates the "current frame", which determines the
875 context of most commands. 'bt' is an alias for this command.""", file=self
.stdout
)
884 Move the current frame one level down in the stack trace
885 (to a newer frame).""", file=self
.stdout
)
892 Move the current frame one level up in the stack trace
893 (to an older frame).""", file=self
.stdout
)
895 def help_break(self
):
899 print("""b(reak) ([file:]lineno | function) [, condition]
900 With a line number argument, set a break there in the current
901 file. With a function name, set a break at first executable line
902 of that function. Without argument, list all breaks. If a second
903 argument is present, it is a string specifying an expression
904 which must evaluate to true before the breakpoint is honored.
906 The line number may be prefixed with a filename and a colon,
907 to specify a breakpoint in another file (probably one that
908 hasn't been loaded yet). The file is searched for on sys.path;
909 the .py suffix may be omitted.""", file=self
.stdout
)
911 def help_clear(self
):
915 print("cl(ear) filename:lineno", file=self
.stdout
)
916 print("""cl(ear) [bpnumber [bpnumber...]]
917 With a space separated list of breakpoint numbers, clear
918 those breakpoints. Without argument, clear all breaks (but
919 first ask confirmation). With a filename:lineno argument,
920 clear all breaks at that line in that file.""", file=self
.stdout
)
922 def help_tbreak(self
):
923 print("""tbreak same arguments as break, but breakpoint is
924 removed when first hit.""", file=self
.stdout
)
926 def help_enable(self
):
927 print("""enable bpnumber [bpnumber ...]
928 Enables the breakpoints given as a space separated list of
929 bp numbers.""", file=self
.stdout
)
931 def help_disable(self
):
932 print("""disable bpnumber [bpnumber ...]
933 Disables the breakpoints given as a space separated list of
934 bp numbers.""", file=self
.stdout
)
936 def help_ignore(self
):
937 print("""ignore bpnumber count
938 Sets the ignore count for the given breakpoint number. A breakpoint
939 becomes active when the ignore count is zero. When non-zero, the
940 count is decremented each time the breakpoint is reached and the
941 breakpoint is not disabled and any associated condition evaluates
942 to true.""", file=self
.stdout
)
944 def help_condition(self
):
945 print("""condition bpnumber str_condition
946 str_condition is a string specifying an expression which
947 must evaluate to true before the breakpoint is honored.
948 If str_condition is absent, any existing condition is removed;
949 i.e., the breakpoint is made unconditional.""", file=self
.stdout
)
956 Execute the current line, stop at the first possible occasion
957 (either in a function that is called or in the current function).""", file=self
.stdout
)
964 Continue execution until the next line in the current function
965 is reached or it returns.""", file=self
.stdout
)
967 def help_return(self
):
972 Continue execution until the current function returns.""", file=self
.stdout
)
974 def help_continue(self
):
981 print("""c(ont(inue))
982 Continue execution, only stop when a breakpoint is encountered.""", file=self
.stdout
)
988 print("""j(ump) lineno
989 Set the next line that will be executed.""", file=self
.stdout
)
991 def help_debug(self
):
993 Enter a recursive debugger that steps through the code argument
994 (which is an arbitrary expression or statement to be executed
995 in the current environment).""", file=self
.stdout
)
1001 print("""l(ist) [first [,last]]
1002 List source code for the current file.
1003 Without arguments, list 11 lines around the current line
1004 or continue the previous listing.
1005 With one argument, list 11 lines starting at that line.
1006 With two arguments, list the given range;
1007 if the second argument is less than the first, it is a count.""", file=self
.stdout
)
1009 def help_args(self
):
1014 Print the arguments of the current function.""", file=self
.stdout
)
1017 print("""p(rint) expression
1018 Print the value of the expression.""", file=self
.stdout
)
1021 print("""pp expression
1022 Pretty-print the value of the expression.""", file=self
.stdout
)
1024 def help_exec(self
):
1025 print("""(!) statement
1026 Execute the (one-line) statement in the context of
1027 the current stack frame.
1028 The exclamation point can be omitted unless the first word
1029 of the statement resembles a debugger command.
1030 To assign to a global variable you must always prefix the
1031 command with a 'global' command, e.g.:
1032 (Pdb) global list_options; list_options = ['-l']
1033 (Pdb)""", file=self
.stdout
)
1036 print("""run [args...]
1037 Restart the debugged python program. If a string is supplied, it is
1038 splitted with "shlex" and the result is used as the new sys.argv.
1039 History, breakpoints, actions and debugger options are preserved.
1040 "restart" is an alias for "run".""")
1042 help_restart
= help_run
1044 def help_quit(self
):
1048 print("""q(uit) or exit - Quit from the debugger.
1049 The program being executed is aborted.""", file=self
.stdout
)
1053 def help_whatis(self
):
1055 Prints the type of the argument.""", file=self
.stdout
)
1059 Handles the receipt of EOF as a command.""", file=self
.stdout
)
1061 def help_alias(self
):
1062 print("""alias [name [command [parameter parameter ...] ]]
1063 Creates an alias called 'name' the executes 'command'. The command
1064 must *not* be enclosed in quotes. Replaceable parameters are
1065 indicated by %1, %2, and so on, while %* is replaced by all the
1066 parameters. If no command is given, the current alias for name
1067 is shown. If no name is given, all aliases are listed.
1069 Aliases may be nested and can contain anything that can be
1070 legally typed at the pdb prompt. Note! You *can* override
1071 internal pdb commands with aliases! Those internal commands
1072 are then hidden until the alias is removed. Aliasing is recursively
1073 applied to the first word of the command line; all other words
1074 in the line are left alone.
1076 Some useful aliases (especially when placed in the .pdbrc file) are:
1078 #Print instance variables (usage "pi classInst")
1079 alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
1081 #Print instance variables in self
1083 """, file=self
.stdout
)
1085 def help_unalias(self
):
1086 print("""unalias name
1087 Deletes the specified alias.""", file=self
.stdout
)
1089 def help_commands(self
):
1090 print("""commands [bpnumber]
1095 Specify a list of commands for breakpoint number bpnumber. The
1096 commands themselves appear on the following lines. Type a line
1097 containing just 'end' to terminate the commands.
1099 To remove all commands from a breakpoint, type commands and
1100 follow it immediately with end; that is, give no commands.
1102 With no bpnumber argument, commands refers to the last
1105 You can use breakpoint commands to start your program up again.
1106 Simply use the continue command, or step, or any other
1107 command that resumes execution.
1109 Specifying any command resuming execution (currently continue,
1110 step, next, return, jump, quit and their abbreviations) terminates
1111 the command list (as if that command was immediately followed by end).
1112 This is because any time you resume execution
1113 (even with a simple next or step), you may encounter
1114 another breakpoint--which could have its own command list, leading to
1115 ambiguities about which list to execute.
1117 If you use the 'silent' command in the command list, the
1118 usual message about stopping at a breakpoint is not printed. This may
1119 be desirable for breakpoints that are to print a specific message and
1120 then continue. If none of the other commands print anything, you
1121 see no sign that the breakpoint was reached.
1122 """, file=self
.stdout
)
1127 def lookupmodule(self
, filename
):
1128 """Helper function for break/clear parsing -- may be overridden.
1130 lookupmodule() translates (possibly incomplete) file or module name
1131 into an absolute file name.
1133 if os
.path
.isabs(filename
) and os
.path
.exists(filename
):
1135 f
= os
.path
.join(sys
.path
[0], filename
)
1136 if os
.path
.exists(f
) and self
.canonic(f
) == self
.mainpyfile
:
1138 root
, ext
= os
.path
.splitext(filename
)
1140 filename
= filename
+ '.py'
1141 if os
.path
.isabs(filename
):
1143 for dirname
in sys
.path
:
1144 while os
.path
.islink(dirname
):
1145 dirname
= os
.readlink(dirname
)
1146 fullname
= os
.path
.join(dirname
, filename
)
1147 if os
.path
.exists(fullname
):
1151 def _runscript(self
, filename
):
1152 # The script has to run in __main__ namespace (or imports from
1153 # __main__ will break).
1155 # So we clear up the __main__ and set several special variables
1156 # (this gets rid of pdb's globals and cleans old variables on restarts).
1158 __main__
.__dict
__.clear()
1159 __main__
.__dict
__.update({"__name__" : "__main__",
1160 "__file__" : filename
,
1161 "__builtins__": __builtins__
,
1164 # When bdb sets tracing, a number of call and line events happens
1165 # BEFORE debugger even reaches user's code (and the exact sequence of
1166 # events depends on python version). So we take special measures to
1167 # avoid stopping before we reach the main script (see user_line and
1168 # user_call for details).
1169 self
._wait
_for
_mainpyfile
= 1
1170 self
.mainpyfile
= self
.canonic(filename
)
1171 self
._user
_requested
_quit
= 0
1172 with
open(filename
) as fp
:
1173 statement
= fp
.read()
1176 # Simplified interface
1178 def run(statement
, globals=None, locals=None):
1179 Pdb().run(statement
, globals, locals)
1181 def runeval(expression
, globals=None, locals=None):
1182 return Pdb().runeval(expression
, globals, locals)
1184 def runctx(statement
, globals, locals):
1186 run(statement
, globals, locals)
1188 def runcall(*args
, **kwds
):
1189 return Pdb().runcall(*args
, **kwds
)
1192 Pdb().set_trace(sys
._getframe
().f_back
)
1194 # Post-Mortem interface
1196 def post_mortem(t
=None):
1197 # handling the default
1199 # sys.exc_info() returns (type, value, traceback) if an exception is
1200 # being handled, otherwise it returns None
1201 t
= sys
.exc_info()[2]
1203 raise ValueError("A valid traceback must be passed if no "
1204 "exception is being handled")
1208 while t
.tb_next
is not None:
1210 p
.interaction(t
.tb_frame
, t
)
1213 post_mortem(sys
.last_traceback
)
1216 # Main program for testing
1218 TESTCMD
= 'import x; x.main()'
1225 for dirname
in sys
.path
:
1226 fullname
= os
.path
.join(dirname
, 'pdb.doc')
1227 if os
.path
.exists(fullname
):
1228 sts
= os
.system('${PAGER-more} '+fullname
)
1229 if sts
: print('*** Pager exit status:', sts
)
1232 print('Sorry, can\'t find the help file "pdb.doc"', end
=' ')
1233 print('along the Python search path')
1236 if not sys
.argv
[1:] or sys
.argv
[1] in ("--help", "-h"):
1237 print("usage: pdb.py scriptfile [arg] ...")
1240 mainpyfile
= sys
.argv
[1] # Get script filename
1241 if not os
.path
.exists(mainpyfile
):
1242 print('Error:', mainpyfile
, 'does not exist')
1245 del sys
.argv
[0] # Hide "pdb.py" from argument list
1247 # Replace pdb's dir with script's dir in front of module search path.
1248 sys
.path
[0] = os
.path
.dirname(mainpyfile
)
1250 # Note on saving/restoring sys.argv: it's a good idea when sys.argv was
1251 # modified by the script being debugged. It's a bad idea when it was
1252 # changed by the user from the command line. There is a "restart" command which
1253 # allows explicit specification of command line arguments.
1257 pdb
._runscript
(mainpyfile
)
1258 if pdb
._user
_requested
_quit
:
1260 print("The program finished and will be restarted")
1262 print("Restarting", mainpyfile
, "with arguments:")
1263 print("\t" + " ".join(sys
.argv
[1:]))
1265 # In most cases SystemExit does not warrant a post-mortem session.
1266 print("The program exited via sys.exit(). Exit status: ", end
=' ')
1267 print(sys
.exc_info()[1])
1269 traceback
.print_exc()
1270 print("Uncaught exception. Entering post mortem debugging")
1271 print("Running 'cont' or 'step' will restart the program")
1272 t
= sys
.exc_info()[2]
1273 while t
.tb_next
is not None:
1275 pdb
.interaction(t
.tb_frame
,t
)
1276 print("Post mortem debugger finished. The "+mainpyfile
+" will be restarted")
1279 # When invoked as main program, invoke the debugger on a script
1280 if __name__
== '__main__':