3 """A Python debugger."""
5 # (See pdb.doc for documentation.)
11 from reprlib
import Repr
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('--Call--', file=self
.stdout
)
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('--Return--', file=self
.stdout
)
188 self
.interaction(frame
, None)
190 def user_exception(self
, frame
, exc_info
):
191 """This function is called if an exception occurs,
192 but only if we are to stop at or just below this level."""
193 exc_type
, exc_value
, exc_traceback
= exc_info
194 frame
.f_locals
['__exception__'] = exc_type
, exc_value
195 exc_type_name
= exc_type
.__name
__
196 print(exc_type_name
+ ':', _saferepr(exc_value
), file=self
.stdout
)
197 self
.interaction(frame
, exc_traceback
)
199 # General interaction function
201 def interaction(self
, frame
, traceback
):
202 self
.setup(frame
, traceback
)
203 self
.print_stack_entry(self
.stack
[self
.curindex
])
207 def displayhook(self
, obj
):
208 """Custom displayhook for the exec in default(), which prevents
209 assignment of the _ variable in the builtins.
213 def default(self
, line
):
214 if line
[:1] == '!': line
= line
[1:]
215 locals = self
.curframe_locals
216 globals = self
.curframe
.f_globals
218 code
= compile(line
+ '\n', '<stdin>', 'single')
219 save_stdout
= sys
.stdout
220 save_stdin
= sys
.stdin
221 save_displayhook
= sys
.displayhook
223 sys
.stdin
= self
.stdin
224 sys
.stdout
= self
.stdout
225 sys
.displayhook
= self
.displayhook
226 exec(code
, globals, locals)
228 sys
.stdout
= save_stdout
229 sys
.stdin
= save_stdin
230 sys
.displayhook
= save_displayhook
232 t
, v
= sys
.exc_info()[:2]
233 if type(t
) == type(''):
235 else: exc_type_name
= t
.__name
__
236 print('***', exc_type_name
+ ':', v
, file=self
.stdout
)
238 def precmd(self
, line
):
239 """Handle alias expansion and ';;' separator."""
243 while args
[0] in self
.aliases
:
244 line
= self
.aliases
[args
[0]]
246 for tmpArg
in args
[1:]:
247 line
= line
.replace("%" + str(ii
),
250 line
= line
.replace("%*", ' '.join(args
[1:]))
252 # split into ';;' separated commands
253 # unless it's an alias command
254 if args
[0] != 'alias':
255 marker
= line
.find(';;')
257 # queue up everything after marker
258 next
= line
[marker
+2:].lstrip()
259 self
.cmdqueue
.append(next
)
260 line
= line
[:marker
].rstrip()
263 def onecmd(self
, line
):
264 """Interpret the argument as though it had been typed in response
267 Checks whether this line is typed at the normal prompt or in
268 a breakpoint command list definition.
270 if not self
.commands_defining
:
271 return cmd
.Cmd
.onecmd(self
, line
)
273 return self
.handle_command_def(line
)
275 def handle_command_def(self
,line
):
276 """ Handles one command line during command list definition. """
277 cmd
, arg
, line
= self
.parseline(line
)
279 self
.commands_silent
[self
.commands_bnum
] = True
280 return # continue to handle other cmd def in the cmd list
283 return 1 # end of cmd list
284 cmdlist
= self
.commands
[self
.commands_bnum
]
286 cmdlist
.append(cmd
+' '+arg
)
289 # Determine if we must stop
291 func
= getattr(self
, 'do_' + cmd
)
292 except AttributeError:
294 # one of the resuming commands
295 if func
.__name
__ in self
.commands_resuming
:
296 self
.commands_doprompt
[self
.commands_bnum
] = False
301 # Command definitions, called by cmdloop()
302 # The argument is the remaining string on the command line
303 # Return true to exit from the command loop
305 do_h
= cmd
.Cmd
.do_help
307 def do_commands(self
, arg
):
308 """Defines a list of commands associated to a breakpoint.
310 Those commands will be executed whenever the breakpoint causes
311 the program to stop execution."""
313 bnum
= len(bdb
.Breakpoint
.bpbynumber
)-1
318 print("Usage : commands [bnum]\n ...\n end",
321 self
.commands_bnum
= bnum
322 self
.commands
[bnum
] = []
323 self
.commands_doprompt
[bnum
] = True
324 self
.commands_silent
[bnum
] = False
325 prompt_back
= self
.prompt
326 self
.prompt
= '(com) '
327 self
.commands_defining
= True
329 self
.commands_defining
= False
330 self
.prompt
= prompt_back
332 def do_break(self
, arg
, temporary
= 0):
333 # break [ ([filename:]lineno | function) [, "condition"] ]
335 if self
.breaks
: # There's at least one
336 print("Num Type Disp Enb Where", file=self
.stdout
)
337 for bp
in bdb
.Breakpoint
.bpbynumber
:
339 bp
.bpprint(self
.stdout
)
341 # parse arguments; comma has lowest precedence
342 # and cannot occur in filename
346 comma
= arg
.find(',')
348 # parse stuff after comma: "condition"
349 cond
= arg
[comma
+1:].lstrip()
350 arg
= arg
[:comma
].rstrip()
351 # parse stuff before comma: [filename:]lineno | function
352 colon
= arg
.rfind(':')
355 filename
= arg
[:colon
].rstrip()
356 f
= self
.lookupmodule(filename
)
358 print('*** ', repr(filename
), end
=' ', file=self
.stdout
)
359 print('not found from sys.path', file=self
.stdout
)
363 arg
= arg
[colon
+1:].lstrip()
366 except ValueError as msg
:
367 print('*** Bad lineno:', arg
, file=self
.stdout
)
370 # no colon; can be lineno or function
376 self
.curframe
.f_globals
,
377 self
.curframe_locals
)
381 if hasattr(func
, '__func__'):
384 #use co_name to identify the bkpt (function names
385 #could be aliased, but co_name is invariant)
386 funcname
= code
.co_name
387 lineno
= code
.co_firstlineno
388 filename
= code
.co_filename
391 (ok
, filename
, ln
) = self
.lineinfo(arg
)
393 print('*** The specified object', end
=' ', file=self
.stdout
)
394 print(repr(arg
), end
=' ', file=self
.stdout
)
395 print('is not a function', file=self
.stdout
)
396 print('or was not found along sys.path.', file=self
.stdout
)
398 funcname
= ok
# ok contains a function name
401 filename
= self
.defaultFile()
402 # Check for reasonable breakpoint
403 line
= self
.checkline(filename
, lineno
)
405 # now set the break point
406 err
= self
.set_break(filename
, line
, temporary
, cond
, funcname
)
407 if err
: print('***', err
, file=self
.stdout
)
409 bp
= self
.get_breaks(filename
, line
)[-1]
410 print("Breakpoint %d at %s:%d" % (bp
.number
,
412 bp
.line
), file=self
.stdout
)
414 # To be overridden in derived debuggers
415 def defaultFile(self
):
416 """Produce a reasonable default."""
417 filename
= self
.curframe
.f_code
.co_filename
418 if filename
== '<string>' and self
.mainpyfile
:
419 filename
= self
.mainpyfile
424 def do_tbreak(self
, arg
):
425 self
.do_break(arg
, 1)
427 def lineinfo(self
, identifier
):
428 failed
= (None, None, None)
429 # Input is identifier, may be in single quotes
430 idstring
= identifier
.split("'")
431 if len(idstring
) == 1:
432 # not in single quotes
433 id = idstring
[0].strip()
434 elif len(idstring
) == 3:
436 id = idstring
[1].strip()
439 if id == '': return failed
440 parts
= id.split('.')
441 # Protection for derived debuggers
442 if parts
[0] == 'self':
446 # Best first guess at file to look at
447 fname
= self
.defaultFile()
451 # More than one part.
452 # First is module, second is method/class
453 f
= self
.lookupmodule(parts
[0])
457 answer
= find_function(item
, fname
)
458 return answer
or failed
460 def checkline(self
, filename
, lineno
):
461 """Check whether specified line seems to be executable.
463 Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
464 line or EOF). Warning: testing is not comprehensive.
466 line
= linecache
.getline(filename
, lineno
, self
.curframe
.f_globals
)
468 print('End of file', file=self
.stdout
)
471 # Don't allow setting breakpoint at a blank line
472 if (not line
or (line
[0] == '#') or
473 (line
[:3] == '"""') or line
[:3] == "'''"):
474 print('*** Blank or comment', file=self
.stdout
)
478 def do_enable(self
, arg
):
484 print('Breakpoint index %r is not a number' % i
, file=self
.stdout
)
487 if not (0 <= i
< len(bdb
.Breakpoint
.bpbynumber
)):
488 print('No breakpoint numbered', i
, file=self
.stdout
)
491 bp
= bdb
.Breakpoint
.bpbynumber
[i
]
495 def do_disable(self
, arg
):
501 print('Breakpoint index %r is not a number' % i
, file=self
.stdout
)
504 if not (0 <= i
< len(bdb
.Breakpoint
.bpbynumber
)):
505 print('No breakpoint numbered', i
, file=self
.stdout
)
508 bp
= bdb
.Breakpoint
.bpbynumber
[i
]
512 def do_condition(self
, arg
):
513 # arg is breakpoint number and condition
514 args
= arg
.split(' ', 1)
516 bpnum
= int(args
[0].strip())
518 # something went wrong
519 print('Breakpoint index %r is not a number' % args
[0], file=self
.stdout
)
526 bp
= bdb
.Breakpoint
.bpbynumber
[bpnum
]
528 print('Breakpoint index %r is not valid' % args
[0],
534 print('Breakpoint', bpnum
, end
=' ', file=self
.stdout
)
535 print('is now unconditional.', file=self
.stdout
)
537 def do_ignore(self
,arg
):
538 """arg is bp number followed by ignore count."""
541 bpnum
= int(args
[0].strip())
543 # something went wrong
544 print('Breakpoint index %r is not a number' % args
[0], file=self
.stdout
)
547 count
= int(args
[1].strip())
551 bp
= bdb
.Breakpoint
.bpbynumber
[bpnum
]
553 print('Breakpoint index %r is not valid' % args
[0],
559 reply
= 'Will ignore next '
561 reply
= reply
+ '%d crossings' % count
563 reply
= reply
+ '1 crossing'
564 print(reply
+ ' of breakpoint %d.' % bpnum
, file=self
.stdout
)
566 print('Will stop next time breakpoint', end
=' ', file=self
.stdout
)
567 print(bpnum
, 'is reached.', file=self
.stdout
)
569 def do_clear(self
, arg
):
570 """Three possibilities, tried in this order:
571 clear -> clear all breaks, ask for confirmation
572 clear file:lineno -> clear all breaks at file:lineno
573 clear bpno bpno ... -> clear breakpoints by number"""
576 reply
= input('Clear all breaks? ')
579 reply
= reply
.strip().lower()
580 if reply
in ('y', 'yes'):
581 self
.clear_all_breaks()
584 # Make sure it works for "clear C:\foo\bar.py:12"
591 err
= "Invalid line number (%s)" % arg
593 err
= self
.clear_break(filename
, lineno
)
594 if err
: print('***', err
, file=self
.stdout
)
596 numberlist
= arg
.split()
601 print('Breakpoint index %r is not a number' % i
, file=self
.stdout
)
604 if not (0 <= i
< len(bdb
.Breakpoint
.bpbynumber
)):
605 print('No breakpoint numbered', i
, file=self
.stdout
)
607 err
= self
.clear_bpbynumber(i
)
609 print('***', err
, file=self
.stdout
)
611 print('Deleted breakpoint', i
, file=self
.stdout
)
612 do_cl
= do_clear
# 'c' is already an abbreviation for 'continue'
614 def do_where(self
, arg
):
615 self
.print_stack_trace()
619 def do_up(self
, arg
):
620 if self
.curindex
== 0:
621 print('*** Oldest frame', file=self
.stdout
)
623 self
.curindex
= self
.curindex
- 1
624 self
.curframe
= self
.stack
[self
.curindex
][0]
625 self
.curframe_locals
= self
.curframe
.f_locals
626 self
.print_stack_entry(self
.stack
[self
.curindex
])
630 def do_down(self
, arg
):
631 if self
.curindex
+ 1 == len(self
.stack
):
632 print('*** Newest frame', file=self
.stdout
)
634 self
.curindex
= self
.curindex
+ 1
635 self
.curframe
= self
.stack
[self
.curindex
][0]
636 self
.curframe_locals
= self
.curframe
.f_locals
637 self
.print_stack_entry(self
.stack
[self
.curindex
])
641 def do_until(self
, arg
):
642 self
.set_until(self
.curframe
)
646 def do_step(self
, arg
):
651 def do_next(self
, arg
):
652 self
.set_next(self
.curframe
)
656 def do_run(self
, arg
):
657 """Restart program by raising an exception to be caught in the main
658 debugger loop. If arguments were given, set them in sys.argv."""
661 argv0
= sys
.argv
[0:1]
662 sys
.argv
= shlex
.split(arg
)
668 def do_return(self
, arg
):
669 self
.set_return(self
.curframe
)
673 def do_continue(self
, arg
):
676 do_c
= do_cont
= do_continue
678 def do_jump(self
, arg
):
679 if self
.curindex
+ 1 != len(self
.stack
):
680 print("*** You can only jump within the bottom frame", file=self
.stdout
)
685 print("*** The 'jump' command requires a line number.", file=self
.stdout
)
688 # Do the jump, fix up our copy of the stack, and display the
690 self
.curframe
.f_lineno
= arg
691 self
.stack
[self
.curindex
] = self
.stack
[self
.curindex
][0], arg
692 self
.print_stack_entry(self
.stack
[self
.curindex
])
693 except ValueError as e
:
694 print('*** Jump failed:', e
, file=self
.stdout
)
697 def do_debug(self
, arg
):
699 globals = self
.curframe
.f_globals
700 locals = self
.curframe_locals
701 p
= Pdb(self
.completekey
, self
.stdin
, self
.stdout
)
702 p
.prompt
= "(%s) " % self
.prompt
.strip()
703 print("ENTERING RECURSIVE DEBUGGER", file=self
.stdout
)
704 sys
.call_tracing(p
.run
, (arg
, globals, locals))
705 print("LEAVING RECURSIVE DEBUGGER", file=self
.stdout
)
706 sys
.settrace(self
.trace_dispatch
)
707 self
.lastcmd
= p
.lastcmd
709 def do_quit(self
, arg
):
710 self
._user
_requested
_quit
= 1
717 def do_EOF(self
, arg
):
718 print(file=self
.stdout
)
719 self
._user
_requested
_quit
= 1
723 def do_args(self
, arg
):
724 co
= self
.curframe
.f_code
725 dict = self
.curframe_locals
727 if co
.co_flags
& 4: n
= n
+1
728 if co
.co_flags
& 8: n
= n
+1
730 name
= co
.co_varnames
[i
]
731 print(name
, '=', end
=' ', file=self
.stdout
)
732 if name
in dict: print(dict[name
], file=self
.stdout
)
733 else: print("*** undefined ***", file=self
.stdout
)
736 def do_retval(self
, arg
):
737 if '__return__' in self
.curframe_locals
:
738 print(self
.curframe_locals
['__return__'], file=self
.stdout
)
740 print('*** Not yet returned!', file=self
.stdout
)
743 def _getval(self
, arg
):
745 return eval(arg
, self
.curframe
.f_globals
, self
.curframe_locals
)
747 t
, v
= sys
.exc_info()[:2]
748 if isinstance(t
, str):
750 else: exc_type_name
= t
.__name
__
751 print('***', exc_type_name
+ ':', repr(v
), file=self
.stdout
)
756 print(repr(self
._getval
(arg
)), file=self
.stdout
)
759 # make "print" an alias of "p" since print isn't a Python statement anymore
762 def do_pp(self
, arg
):
764 pprint
.pprint(self
._getval
(arg
), self
.stdout
)
768 def do_list(self
, arg
):
769 self
.lastcmd
= 'list'
773 x
= eval(arg
, {}, {})
774 if type(x
) == type(()):
779 # Assume it's a count
782 first
= max(1, int(x
) - 5)
784 print('*** Error in argument:', repr(arg
), file=self
.stdout
)
786 elif self
.lineno
is None:
787 first
= max(1, self
.curframe
.f_lineno
- 5)
789 first
= self
.lineno
+ 1
792 filename
= self
.curframe
.f_code
.co_filename
793 breaklist
= self
.get_file_breaks(filename
)
795 for lineno
in range(first
, last
+1):
796 line
= linecache
.getline(filename
, lineno
,
797 self
.curframe
.f_globals
)
799 print('[EOF]', file=self
.stdout
)
802 s
= repr(lineno
).rjust(3)
803 if len(s
) < 4: s
= s
+ ' '
804 if lineno
in breaklist
: s
= s
+ 'B'
806 if lineno
== self
.curframe
.f_lineno
:
808 print(s
+ '\t' + line
, end
='', file=self
.stdout
)
810 except KeyboardInterrupt:
814 def do_whatis(self
, arg
):
816 value
= eval(arg
, self
.curframe
.f_globals
,
817 self
.curframe_locals
)
819 t
, v
= sys
.exc_info()[:2]
820 if type(t
) == type(''):
822 else: exc_type_name
= t
.__name
__
823 print('***', exc_type_name
+ ':', repr(v
), file=self
.stdout
)
827 try: code
= value
.__code
__
830 print('Function', code
.co_name
, file=self
.stdout
)
832 # Is it an instance method?
833 try: code
= value
.__func
__.__code
__
836 print('Method', code
.co_name
, file=self
.stdout
)
838 # None of the above...
839 print(type(value
), file=self
.stdout
)
841 def do_alias(self
, arg
):
844 keys
= self
.aliases
.keys()
847 print("%s = %s" % (alias
, self
.aliases
[alias
]), file=self
.stdout
)
849 if args
[0] in self
.aliases
and len(args
) == 1:
850 print("%s = %s" % (args
[0], self
.aliases
[args
[0]]), file=self
.stdout
)
852 self
.aliases
[args
[0]] = ' '.join(args
[1:])
854 def do_unalias(self
, arg
):
856 if len(args
) == 0: return
857 if args
[0] in self
.aliases
:
858 del self
.aliases
[args
[0]]
860 #list of all the commands making the program resume execution.
861 commands_resuming
= ['do_continue', 'do_step', 'do_next', 'do_return',
862 'do_quit', 'do_jump']
864 # Print a traceback starting at the top stack frame.
865 # The most recently entered frame is printed last;
866 # this is different from dbx and gdb, but consistent with
867 # the Python interpreter's stack trace.
868 # It is also consistent with the up/down commands (which are
869 # compatible with dbx and gdb: up moves towards 'main()'
870 # and down moves towards the most recent stack frame).
872 def print_stack_trace(self
):
874 for frame_lineno
in self
.stack
:
875 self
.print_stack_entry(frame_lineno
)
876 except KeyboardInterrupt:
879 def print_stack_entry(self
, frame_lineno
, prompt_prefix
=line_prefix
):
880 frame
, lineno
= frame_lineno
881 if frame
is self
.curframe
:
882 print('>', end
=' ', file=self
.stdout
)
884 print(' ', end
=' ', file=self
.stdout
)
885 print(self
.format_stack_entry(frame_lineno
,
886 prompt_prefix
), file=self
.stdout
)
889 # Help methods (derived from pdb.doc)
896 Without argument, print the list of available commands.
897 With a command name as argument, print help about that command
898 "help pdb" pipes the full documentation file to the $PAGER
899 "help exec" gives help on the ! command""", file=self
.stdout
)
901 def help_where(self
):
906 Print a stack trace, with the most recent frame at the bottom.
907 An arrow indicates the "current frame", which determines the
908 context of most commands. 'bt' is an alias for this command.""", file=self
.stdout
)
917 Move the current frame one level down in the stack trace
918 (to a newer frame).""", file=self
.stdout
)
925 Move the current frame one level up in the stack trace
926 (to an older frame).""", file=self
.stdout
)
928 def help_break(self
):
932 print("""b(reak) ([file:]lineno | function) [, condition]
933 With a line number argument, set a break there in the current
934 file. With a function name, set a break at first executable line
935 of that function. Without argument, list all breaks. If a second
936 argument is present, it is a string specifying an expression
937 which must evaluate to true before the breakpoint is honored.
939 The line number may be prefixed with a filename and a colon,
940 to specify a breakpoint in another file (probably one that
941 hasn't been loaded yet). The file is searched for on sys.path;
942 the .py suffix may be omitted.""", file=self
.stdout
)
944 def help_clear(self
):
948 print("cl(ear) filename:lineno", file=self
.stdout
)
949 print("""cl(ear) [bpnumber [bpnumber...]]
950 With a space separated list of breakpoint numbers, clear
951 those breakpoints. Without argument, clear all breaks (but
952 first ask confirmation). With a filename:lineno argument,
953 clear all breaks at that line in that file.""", file=self
.stdout
)
955 def help_tbreak(self
):
956 print("""tbreak same arguments as break, but breakpoint is
957 removed when first hit.""", file=self
.stdout
)
959 def help_enable(self
):
960 print("""enable bpnumber [bpnumber ...]
961 Enables the breakpoints given as a space separated list of
962 bp numbers.""", file=self
.stdout
)
964 def help_disable(self
):
965 print("""disable bpnumber [bpnumber ...]
966 Disables the breakpoints given as a space separated list of
967 bp numbers.""", file=self
.stdout
)
969 def help_ignore(self
):
970 print("""ignore bpnumber count
971 Sets the ignore count for the given breakpoint number. A breakpoint
972 becomes active when the ignore count is zero. When non-zero, the
973 count is decremented each time the breakpoint is reached and the
974 breakpoint is not disabled and any associated condition evaluates
975 to true.""", file=self
.stdout
)
977 def help_condition(self
):
978 print("""condition bpnumber str_condition
979 str_condition is a string specifying an expression which
980 must evaluate to true before the breakpoint is honored.
981 If str_condition is absent, any existing condition is removed;
982 i.e., the breakpoint is made unconditional.""", file=self
.stdout
)
989 Execute the current line, stop at the first possible occasion
990 (either in a function that is called or in the current function).""", file=self
.stdout
)
992 def help_until(self
):
997 Continue execution until the line with a number greater than the current
998 one is reached or until the current frame returns""")
1000 def help_next(self
):
1005 Continue execution until the next line in the current function
1006 is reached or it returns.""", file=self
.stdout
)
1008 def help_return(self
):
1013 Continue execution until the current function returns.""", file=self
.stdout
)
1015 def help_continue(self
):
1018 def help_cont(self
):
1022 print("""c(ont(inue))
1023 Continue execution, only stop when a breakpoint is encountered.""", file=self
.stdout
)
1025 def help_jump(self
):
1029 print("""j(ump) lineno
1030 Set the next line that will be executed.""", file=self
.stdout
)
1032 def help_debug(self
):
1034 Enter a recursive debugger that steps through the code argument
1035 (which is an arbitrary expression or statement to be executed
1036 in the current environment).""", file=self
.stdout
)
1038 def help_list(self
):
1042 print("""l(ist) [first [,last]]
1043 List source code for the current file.
1044 Without arguments, list 11 lines around the current line
1045 or continue the previous listing.
1046 With one argument, list 11 lines starting at that line.
1047 With two arguments, list the given range;
1048 if the second argument is less than the first, it is a count.""", file=self
.stdout
)
1050 def help_args(self
):
1055 Print the arguments of the current function.""", file=self
.stdout
)
1058 print("""p(rint) expression
1059 Print the value of the expression.""", file=self
.stdout
)
1062 print("""pp expression
1063 Pretty-print the value of the expression.""", file=self
.stdout
)
1065 def help_exec(self
):
1066 print("""(!) statement
1067 Execute the (one-line) statement in the context of
1068 the current stack frame.
1069 The exclamation point can be omitted unless the first word
1070 of the statement resembles a debugger command.
1071 To assign to a global variable you must always prefix the
1072 command with a 'global' command, e.g.:
1073 (Pdb) global list_options; list_options = ['-l']
1074 (Pdb)""", file=self
.stdout
)
1077 print("""run [args...]
1078 Restart the debugged python program. If a string is supplied, it is
1079 splitted with "shlex" and the result is used as the new sys.argv.
1080 History, breakpoints, actions and debugger options are preserved.
1081 "restart" is an alias for "run".""")
1083 help_restart
= help_run
1085 def help_quit(self
):
1089 print("""q(uit) or exit - Quit from the debugger.
1090 The program being executed is aborted.""", file=self
.stdout
)
1094 def help_whatis(self
):
1096 Prints the type of the argument.""", file=self
.stdout
)
1100 Handles the receipt of EOF as a command.""", file=self
.stdout
)
1102 def help_alias(self
):
1103 print("""alias [name [command [parameter parameter ...] ]]
1104 Creates an alias called 'name' the executes 'command'. The command
1105 must *not* be enclosed in quotes. Replaceable parameters are
1106 indicated by %1, %2, and so on, while %* is replaced by all the
1107 parameters. If no command is given, the current alias for name
1108 is shown. If no name is given, all aliases are listed.
1110 Aliases may be nested and can contain anything that can be
1111 legally typed at the pdb prompt. Note! You *can* override
1112 internal pdb commands with aliases! Those internal commands
1113 are then hidden until the alias is removed. Aliasing is recursively
1114 applied to the first word of the command line; all other words
1115 in the line are left alone.
1117 Some useful aliases (especially when placed in the .pdbrc file) are:
1119 #Print instance variables (usage "pi classInst")
1120 alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
1122 #Print instance variables in self
1124 """, file=self
.stdout
)
1126 def help_unalias(self
):
1127 print("""unalias name
1128 Deletes the specified alias.""", file=self
.stdout
)
1130 def help_commands(self
):
1131 print("""commands [bpnumber]
1136 Specify a list of commands for breakpoint number bpnumber. The
1137 commands themselves appear on the following lines. Type a line
1138 containing just 'end' to terminate the commands.
1140 To remove all commands from a breakpoint, type commands and
1141 follow it immediately with end; that is, give no commands.
1143 With no bpnumber argument, commands refers to the last
1146 You can use breakpoint commands to start your program up again.
1147 Simply use the continue command, or step, or any other
1148 command that resumes execution.
1150 Specifying any command resuming execution (currently continue,
1151 step, next, return, jump, quit and their abbreviations) terminates
1152 the command list (as if that command was immediately followed by end).
1153 This is because any time you resume execution
1154 (even with a simple next or step), you may encounter
1155 another breakpoint--which could have its own command list, leading to
1156 ambiguities about which list to execute.
1158 If you use the 'silent' command in the command list, the
1159 usual message about stopping at a breakpoint is not printed. This may
1160 be desirable for breakpoints that are to print a specific message and
1161 then continue. If none of the other commands print anything, you
1162 see no sign that the breakpoint was reached.
1163 """, file=self
.stdout
)
1168 def lookupmodule(self
, filename
):
1169 """Helper function for break/clear parsing -- may be overridden.
1171 lookupmodule() translates (possibly incomplete) file or module name
1172 into an absolute file name.
1174 if os
.path
.isabs(filename
) and os
.path
.exists(filename
):
1176 f
= os
.path
.join(sys
.path
[0], filename
)
1177 if os
.path
.exists(f
) and self
.canonic(f
) == self
.mainpyfile
:
1179 root
, ext
= os
.path
.splitext(filename
)
1181 filename
= filename
+ '.py'
1182 if os
.path
.isabs(filename
):
1184 for dirname
in sys
.path
:
1185 while os
.path
.islink(dirname
):
1186 dirname
= os
.readlink(dirname
)
1187 fullname
= os
.path
.join(dirname
, filename
)
1188 if os
.path
.exists(fullname
):
1192 def _runscript(self
, filename
):
1193 # The script has to run in __main__ namespace (or imports from
1194 # __main__ will break).
1196 # So we clear up the __main__ and set several special variables
1197 # (this gets rid of pdb's globals and cleans old variables on restarts).
1199 __main__
.__dict
__.clear()
1200 __main__
.__dict
__.update({"__name__" : "__main__",
1201 "__file__" : filename
,
1202 "__builtins__": __builtins__
,
1205 # When bdb sets tracing, a number of call and line events happens
1206 # BEFORE debugger even reaches user's code (and the exact sequence of
1207 # events depends on python version). So we take special measures to
1208 # avoid stopping before we reach the main script (see user_line and
1209 # user_call for details).
1210 self
._wait
_for
_mainpyfile
= 1
1211 self
.mainpyfile
= self
.canonic(filename
)
1212 self
._user
_requested
_quit
= 0
1213 with
open(filename
) as fp
:
1214 statement
= fp
.read()
1217 # Simplified interface
1219 def run(statement
, globals=None, locals=None):
1220 Pdb().run(statement
, globals, locals)
1222 def runeval(expression
, globals=None, locals=None):
1223 return Pdb().runeval(expression
, globals, locals)
1225 def runctx(statement
, globals, locals):
1227 run(statement
, globals, locals)
1229 def runcall(*args
, **kwds
):
1230 return Pdb().runcall(*args
, **kwds
)
1233 Pdb().set_trace(sys
._getframe
().f_back
)
1235 # Post-Mortem interface
1237 def post_mortem(t
=None):
1238 # handling the default
1240 # sys.exc_info() returns (type, value, traceback) if an exception is
1241 # being handled, otherwise it returns None
1242 t
= sys
.exc_info()[2]
1244 raise ValueError("A valid traceback must be passed if no "
1245 "exception is being handled")
1249 p
.interaction(None, t
)
1252 post_mortem(sys
.last_traceback
)
1255 # Main program for testing
1257 TESTCMD
= 'import x; x.main()'
1264 for dirname
in sys
.path
:
1265 fullname
= os
.path
.join(dirname
, 'pdb.doc')
1266 if os
.path
.exists(fullname
):
1267 sts
= os
.system('${PAGER-more} '+fullname
)
1268 if sts
: print('*** Pager exit status:', sts
)
1271 print('Sorry, can\'t find the help file "pdb.doc"', end
=' ')
1272 print('along the Python search path')
1275 if not sys
.argv
[1:] or sys
.argv
[1] in ("--help", "-h"):
1276 print("usage: pdb.py scriptfile [arg] ...")
1279 mainpyfile
= sys
.argv
[1] # Get script filename
1280 if not os
.path
.exists(mainpyfile
):
1281 print('Error:', mainpyfile
, 'does not exist')
1284 del sys
.argv
[0] # Hide "pdb.py" from argument list
1286 # Replace pdb's dir with script's dir in front of module search path.
1287 sys
.path
[0] = os
.path
.dirname(mainpyfile
)
1289 # Note on saving/restoring sys.argv: it's a good idea when sys.argv was
1290 # modified by the script being debugged. It's a bad idea when it was
1291 # changed by the user from the command line. There is a "restart" command
1292 # which allows explicit specification of command line arguments.
1296 pdb
._runscript
(mainpyfile
)
1297 if pdb
._user
_requested
_quit
:
1299 print("The program finished and will be restarted")
1301 print("Restarting", mainpyfile
, "with arguments:")
1302 print("\t" + " ".join(sys
.argv
[1:]))
1304 # In most cases SystemExit does not warrant a post-mortem session.
1305 print("The program exited via sys.exit(). Exit status: ", end
=' ')
1306 print(sys
.exc_info()[1])
1308 traceback
.print_exc()
1309 print("Uncaught exception. Entering post mortem debugging")
1310 print("Running 'cont' or 'step' will restart the program")
1311 t
= sys
.exc_info()[2]
1312 pdb
.interaction(None, t
)
1313 print("Post mortem debugger finished. The " + mainpyfile
+
1314 " will be restarted")
1317 # When invoked as main program, invoke the debugger on a script
1318 if __name__
== '__main__':