blob: ac53eba135c32176ff88557b31e8f56d6a6c358a [file] [log] [blame]
Benjamin Peterson90f5ba52010-03-11 22:53:45 +00001#! /usr/bin/env python3
Guido van Rossumf17361d1996-07-30 16:28:13 +00002
Georg Brandl02053ee2010-07-18 10:11:03 +00003"""
4The Python Debugger Pdb
5=======================
Guido van Rossum92df0c61992-01-14 18:30:15 +00006
Georg Brandl02053ee2010-07-18 10:11:03 +00007To use the debugger in its simplest form:
8
9 >>> import pdb
10 >>> pdb.run('<a statement>')
11
12The debugger's prompt is '(Pdb) '. This will stop in the first
13function call in <a statement>.
14
15Alternatively, if a statement terminated with an unhandled exception,
16you can use pdb's post-mortem facility to inspect the contents of the
17traceback:
18
19 >>> <a statement>
20 <exception traceback>
21 >>> import pdb
22 >>> pdb.pm()
23
24The commands recognized by the debugger are listed in the next
25section. Most can be abbreviated as indicated; e.g., h(elp) means
26that 'help' can be typed as 'h' or 'help' (but not as 'he' or 'hel',
27nor as 'H' or 'Help' or 'HELP'). Optional arguments are enclosed in
28square brackets. Alternatives in the command syntax are separated
29by a vertical bar (|).
30
31A blank line repeats the previous command literally, except for
32'list', where it lists the next 11 lines.
33
34Commands that the debugger doesn't recognize are assumed to be Python
35statements and are executed in the context of the program being
36debugged. Python statements can also be prefixed with an exclamation
37point ('!'). This is a powerful way to inspect the program being
38debugged; it is even possible to change variables or call functions.
39When an exception occurs in such a statement, the exception name is
40printed but the debugger's state is not changed.
41
42The debugger supports aliases, which can save typing. And aliases can
43have parameters (see the alias help entry) which allows one a certain
44level of adaptability to the context under examination.
45
46Multiple commands may be entered on a single line, separated by the
47pair ';;'. No intelligence is applied to separating the commands; the
48input is split at the first ';;', even if it is in the middle of a
49quoted string.
50
51If a file ".pdbrc" exists in your home directory or in the current
52directory, it is read in and executed as if it had been typed at the
53debugger prompt. This is particularly useful for aliases. If both
54files exist, the one in the home directory is read first and aliases
55defined there can be overriden by the local file.
56
57Aside from aliases, the debugger is not directly programmable; but it
58is implemented as a class from which you can derive your own debugger
59class, which you can make as fancy as you like.
60
61
62Debugger commands
63=================
64
Georg Brandl02053ee2010-07-18 10:11:03 +000065"""
Georg Brandl0d089622010-07-30 16:00:46 +000066# NOTE: the actual command documentation is collected from docstrings of the
67# commands and is appended to __doc__ after the class has been defined.
Guido van Rossum921c8241992-01-10 14:54:42 +000068
Georg Brandl44f2b642010-12-04 16:00:47 +000069import os
70import re
Guido van Rossum921c8241992-01-10 14:54:42 +000071import sys
Guido van Rossum23efba41992-01-27 16:58:47 +000072import cmd
73import bdb
Georg Brandl0a9c3e92010-07-30 18:46:38 +000074import dis
Georg Brandl1acb7462010-12-04 11:20:26 +000075import code
Barry Warsaw210bd202002-11-05 22:40:20 +000076import pprint
Georg Brandl44f2b642010-12-04 16:00:47 +000077import signal
Georg Brandle59ca2a2010-07-30 17:04:28 +000078import inspect
Georg Brandl1acb7462010-12-04 11:20:26 +000079import traceback
80import linecache
Guido van Rossumd8faa362007-04-27 19:54:29 +000081
82
83class Restart(Exception):
84 """Causes a debugger to be restarted for the debugged python program."""
85 pass
86
Skip Montanaro352674d2001-02-07 23:14:30 +000087__all__ = ["run", "pm", "Pdb", "runeval", "runctx", "runcall", "set_trace",
88 "post_mortem", "help"]
89
Barry Warsaw2bee8fe1999-09-09 16:32:41 +000090def find_function(funcname, filename):
Thomas Wouters89f507f2006-12-13 04:49:30 +000091 cre = re.compile(r'def\s+%s\s*[(]' % re.escape(funcname))
Tim Peters2344fae2001-01-15 00:50:52 +000092 try:
93 fp = open(filename)
94 except IOError:
95 return None
96 # consumer of this info expects the first line to be 1
97 lineno = 1
98 answer = None
Georg Brandlac9a2bb2010-11-29 20:19:15 +000099 while True:
Tim Peters2344fae2001-01-15 00:50:52 +0000100 line = fp.readline()
101 if line == '':
102 break
103 if cre.match(line):
104 answer = funcname, filename, lineno
105 break
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000106 lineno += 1
Tim Peters2344fae2001-01-15 00:50:52 +0000107 fp.close()
108 return answer
Guido van Rossum921c8241992-01-10 14:54:42 +0000109
Georg Brandl5ed2b5a2010-07-30 18:08:12 +0000110def getsourcelines(obj):
111 lines, lineno = inspect.findsource(obj)
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000112 if inspect.isframe(obj) and obj.f_globals is obj.f_locals:
Georg Brandl5ed2b5a2010-07-30 18:08:12 +0000113 # must be a module frame: do not try to cut a block out of it
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000114 return lines, 1
Georg Brandl5ed2b5a2010-07-30 18:08:12 +0000115 elif inspect.ismodule(obj):
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000116 return lines, 1
Georg Brandl5ed2b5a2010-07-30 18:08:12 +0000117 return inspect.getblock(lines[lineno:]), lineno+1
Guido van Rossum921c8241992-01-10 14:54:42 +0000118
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000119def lasti2lineno(code, lasti):
120 linestarts = list(dis.findlinestarts(code))
121 linestarts.reverse()
122 for i, lineno in linestarts:
123 if lasti >= i:
124 return lineno
125 return 0
126
127
Guido van Rossuma558e371994-11-10 22:27:35 +0000128# Interaction prompt line will separate file and call info from code
129# text using value of line_prefix string. A newline and arrow may
130# be to your liking. You can set it once pdb is imported using the
131# command "pdb.line_prefix = '\n% '".
Tim Peters2344fae2001-01-15 00:50:52 +0000132# line_prefix = ': ' # Use this to get the old situation back
133line_prefix = '\n-> ' # Probably a better default
Guido van Rossuma558e371994-11-10 22:27:35 +0000134
Guido van Rossum23efba41992-01-27 16:58:47 +0000135class Pdb(bdb.Bdb, cmd.Cmd):
Guido van Rossum2424f851998-09-11 22:50:09 +0000136
Georg Brandl44f2b642010-12-04 16:00:47 +0000137 def __init__(self, completekey='tab', stdin=None, stdout=None, skip=None,
138 nosigint=False):
Georg Brandl243ad662009-05-05 09:00:19 +0000139 bdb.Bdb.__init__(self, skip=skip)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000140 cmd.Cmd.__init__(self, completekey, stdin, stdout)
141 if stdout:
142 self.use_rawinput = 0
Tim Peters2344fae2001-01-15 00:50:52 +0000143 self.prompt = '(Pdb) '
144 self.aliases = {}
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000145 self.mainpyfile = ''
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000146 self._wait_for_mainpyfile = False
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000147 self.tb_lineno = {}
Tim Peters2344fae2001-01-15 00:50:52 +0000148 # Try to load readline if it exists
149 try:
150 import readline
151 except ImportError:
152 pass
Georg Brandl44f2b642010-12-04 16:00:47 +0000153 self.allow_kbdint = False
154 self.nosigint = nosigint
Guido van Rossum2424f851998-09-11 22:50:09 +0000155
Tim Peters2344fae2001-01-15 00:50:52 +0000156 # Read $HOME/.pdbrc and ./.pdbrc
157 self.rcLines = []
Raymond Hettinger54f02222002-06-01 14:18:47 +0000158 if 'HOME' in os.environ:
Tim Peters2344fae2001-01-15 00:50:52 +0000159 envHome = os.environ['HOME']
160 try:
Florent Xicluna7dde7922010-09-03 19:52:03 +0000161 with open(os.path.join(envHome, ".pdbrc")) as rcFile:
162 self.rcLines.extend(rcFile)
Tim Peters2344fae2001-01-15 00:50:52 +0000163 except IOError:
164 pass
Tim Peters2344fae2001-01-15 00:50:52 +0000165 try:
Florent Xicluna7dde7922010-09-03 19:52:03 +0000166 with open(".pdbrc") as rcFile:
167 self.rcLines.extend(rcFile)
Tim Peters2344fae2001-01-15 00:50:52 +0000168 except IOError:
169 pass
Guido van Rossum23efba41992-01-27 16:58:47 +0000170
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000171 self.commands = {} # associates a command list to breakpoint numbers
Benjamin Petersond23f8222009-04-05 19:13:16 +0000172 self.commands_doprompt = {} # for each bp num, tells if the prompt
173 # must be disp. after execing the cmd list
174 self.commands_silent = {} # for each bp num, tells if the stack trace
175 # must be disp. after execing the cmd list
176 self.commands_defining = False # True while in the process of defining
177 # a command list
178 self.commands_bnum = None # The breakpoint number for which we are
179 # defining a list
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000180
Georg Brandl44f2b642010-12-04 16:00:47 +0000181 def sigint_handler(self, signum, frame):
182 if self.allow_kbdint:
183 raise KeyboardInterrupt
184 self.message("\nProgram interrupted. (Use 'cont' to resume).")
185 self.set_step()
186 self.set_trace(frame)
187 # restore previous signal handler
188 signal.signal(signal.SIGINT, self._previous_sigint_handler)
189
Tim Peters2344fae2001-01-15 00:50:52 +0000190 def reset(self):
191 bdb.Bdb.reset(self)
192 self.forget()
Guido van Rossum23efba41992-01-27 16:58:47 +0000193
Tim Peters2344fae2001-01-15 00:50:52 +0000194 def forget(self):
195 self.lineno = None
196 self.stack = []
197 self.curindex = 0
198 self.curframe = None
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000199 self.tb_lineno.clear()
Guido van Rossum2424f851998-09-11 22:50:09 +0000200
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000201 def setup(self, f, tb):
Tim Peters2344fae2001-01-15 00:50:52 +0000202 self.forget()
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000203 self.stack, self.curindex = self.get_stack(f, tb)
204 while tb:
205 # when setting up post-mortem debugging with a traceback, save all
206 # the original line numbers to be displayed along the current line
207 # numbers (which can be different, e.g. due to finally clauses)
208 lineno = lasti2lineno(tb.tb_frame.f_code, tb.tb_lasti)
209 self.tb_lineno[tb.tb_frame] = lineno
210 tb = tb.tb_next
Tim Peters2344fae2001-01-15 00:50:52 +0000211 self.curframe = self.stack[self.curindex][0]
Benjamin Petersond23f8222009-04-05 19:13:16 +0000212 # The f_locals dictionary is updated from the actual frame
213 # locals whenever the .f_locals accessor is called, so we
214 # cache it here to ensure that modifications are not overwritten.
215 self.curframe_locals = self.curframe.f_locals
Georg Brandle0230912010-07-30 08:29:39 +0000216 return self.execRcLines()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000217
Tim Peters2344fae2001-01-15 00:50:52 +0000218 # Can be executed earlier than 'setup' if desired
219 def execRcLines(self):
Georg Brandle0230912010-07-30 08:29:39 +0000220 if not self.rcLines:
221 return
222 # local copy because of recursion
223 rcLines = self.rcLines
224 rcLines.reverse()
225 # execute every line only once
226 self.rcLines = []
227 while rcLines:
228 line = rcLines.pop().strip()
229 if line and line[0] != '#':
230 if self.onecmd(line):
231 # if onecmd returns True, the command wants to exit
232 # from the interaction, save leftover rc lines
233 # to execute before next interaction
234 self.rcLines += reversed(rcLines)
235 return True
Guido van Rossum2424f851998-09-11 22:50:09 +0000236
Tim Peters280488b2002-08-23 18:19:30 +0000237 # Override Bdb methods
Michael W. Hudsondd32a912002-08-15 14:59:02 +0000238
239 def user_call(self, frame, argument_list):
240 """This method is called when there is the remote possibility
241 that we ever need to stop in this function."""
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000242 if self._wait_for_mainpyfile:
243 return
Michael W. Hudson01eb85c2003-01-31 17:48:29 +0000244 if self.stop_here(frame):
Georg Brandl0d089622010-07-30 16:00:46 +0000245 self.message('--Call--')
Michael W. Hudson01eb85c2003-01-31 17:48:29 +0000246 self.interaction(frame, None)
Guido van Rossum2424f851998-09-11 22:50:09 +0000247
Tim Peters2344fae2001-01-15 00:50:52 +0000248 def user_line(self, frame):
249 """This function is called when we stop or break at this line."""
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000250 if self._wait_for_mainpyfile:
251 if (self.mainpyfile != self.canonic(frame.f_code.co_filename)
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000252 or frame.f_lineno <= 0):
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000253 return
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000254 self._wait_for_mainpyfile = False
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000255 if self.bp_commands(frame):
256 self.interaction(frame, None)
257
Georg Brandle0230912010-07-30 08:29:39 +0000258 def bp_commands(self, frame):
Georg Brandl3078df02009-05-05 09:11:31 +0000259 """Call every command that was set for the current active breakpoint
260 (if there is one).
261
262 Returns True if the normal interaction function must be called,
263 False otherwise."""
264 # self.currentbp is set in bdb in Bdb.break_here if a breakpoint was hit
265 if getattr(self, "currentbp", False) and \
266 self.currentbp in self.commands:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000267 currentbp = self.currentbp
268 self.currentbp = 0
269 lastcmd_back = self.lastcmd
270 self.setup(frame, None)
271 for line in self.commands[currentbp]:
272 self.onecmd(line)
273 self.lastcmd = lastcmd_back
274 if not self.commands_silent[currentbp]:
275 self.print_stack_entry(self.stack[self.curindex])
276 if self.commands_doprompt[currentbp]:
Georg Brandl44f2b642010-12-04 16:00:47 +0000277 self._cmdloop()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000278 self.forget()
279 return
280 return 1
Guido van Rossum9e1ee971997-07-11 13:43:53 +0000281
Tim Peters2344fae2001-01-15 00:50:52 +0000282 def user_return(self, frame, return_value):
283 """This function is called when a return trap is set here."""
Georg Brandl34cc0f52010-07-30 09:43:00 +0000284 if self._wait_for_mainpyfile:
285 return
Tim Peters2344fae2001-01-15 00:50:52 +0000286 frame.f_locals['__return__'] = return_value
Georg Brandl0d089622010-07-30 16:00:46 +0000287 self.message('--Return--')
Tim Peters2344fae2001-01-15 00:50:52 +0000288 self.interaction(frame, None)
Guido van Rossum2424f851998-09-11 22:50:09 +0000289
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000290 def user_exception(self, frame, exc_info):
Tim Peters2344fae2001-01-15 00:50:52 +0000291 """This function is called if an exception occurs,
292 but only if we are to stop at or just below this level."""
Georg Brandl34cc0f52010-07-30 09:43:00 +0000293 if self._wait_for_mainpyfile:
294 return
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000295 exc_type, exc_value, exc_traceback = exc_info
Tim Peters2344fae2001-01-15 00:50:52 +0000296 frame.f_locals['__exception__'] = exc_type, exc_value
Georg Brandl0d089622010-07-30 16:00:46 +0000297 self.message(traceback.format_exception_only(exc_type,
298 exc_value)[-1].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000299 self.interaction(frame, exc_traceback)
Guido van Rossum2424f851998-09-11 22:50:09 +0000300
Tim Peters2344fae2001-01-15 00:50:52 +0000301 # General interaction function
Georg Brandl44f2b642010-12-04 16:00:47 +0000302 def _cmdloop(self):
303 while True:
304 try:
305 # keyboard interrupts allow for an easy way to cancel
306 # the current command, so allow them during interactive input
307 self.allow_kbdint = True
308 self.cmdloop()
309 self.allow_kbdint = False
310 break
311 except KeyboardInterrupt:
312 self.message('--KeyboardInterrupt--')
Tim Peters2344fae2001-01-15 00:50:52 +0000313
314 def interaction(self, frame, traceback):
Georg Brandle0230912010-07-30 08:29:39 +0000315 if self.setup(frame, traceback):
316 # no interaction desired at this time (happens if .pdbrc contains
317 # a command like "continue")
318 self.forget()
319 return
Tim Peters2344fae2001-01-15 00:50:52 +0000320 self.print_stack_entry(self.stack[self.curindex])
Georg Brandl44f2b642010-12-04 16:00:47 +0000321 self._cmdloop()
Tim Peters2344fae2001-01-15 00:50:52 +0000322 self.forget()
323
Benjamin Petersond23f8222009-04-05 19:13:16 +0000324 def displayhook(self, obj):
325 """Custom displayhook for the exec in default(), which prevents
326 assignment of the _ variable in the builtins.
327 """
Georg Brandl9fa2e022009-09-16 16:40:45 +0000328 # reproduce the behavior of the standard displayhook, not printing None
329 if obj is not None:
Georg Brandl0d089622010-07-30 16:00:46 +0000330 self.message(repr(obj))
Benjamin Petersond23f8222009-04-05 19:13:16 +0000331
Tim Peters2344fae2001-01-15 00:50:52 +0000332 def default(self, line):
333 if line[:1] == '!': line = line[1:]
Benjamin Petersond23f8222009-04-05 19:13:16 +0000334 locals = self.curframe_locals
Tim Peters2344fae2001-01-15 00:50:52 +0000335 globals = self.curframe.f_globals
336 try:
337 code = compile(line + '\n', '<stdin>', 'single')
Christian Heimes679db4a2008-01-18 09:56:22 +0000338 save_stdout = sys.stdout
339 save_stdin = sys.stdin
Benjamin Petersond23f8222009-04-05 19:13:16 +0000340 save_displayhook = sys.displayhook
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000341 try:
342 sys.stdin = self.stdin
343 sys.stdout = self.stdout
Benjamin Petersond23f8222009-04-05 19:13:16 +0000344 sys.displayhook = self.displayhook
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000345 exec(code, globals, locals)
346 finally:
347 sys.stdout = save_stdout
348 sys.stdin = save_stdin
Benjamin Petersond23f8222009-04-05 19:13:16 +0000349 sys.displayhook = save_displayhook
Tim Peters2344fae2001-01-15 00:50:52 +0000350 except:
Georg Brandl0d089622010-07-30 16:00:46 +0000351 exc_info = sys.exc_info()[:2]
352 self.error(traceback.format_exception_only(*exc_info)[-1].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000353
354 def precmd(self, line):
355 """Handle alias expansion and ';;' separator."""
Guido van Rossum08454592002-07-12 13:10:53 +0000356 if not line.strip():
Tim Peters2344fae2001-01-15 00:50:52 +0000357 return line
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000358 args = line.split()
Raymond Hettinger54f02222002-06-01 14:18:47 +0000359 while args[0] in self.aliases:
Tim Peters2344fae2001-01-15 00:50:52 +0000360 line = self.aliases[args[0]]
361 ii = 1
362 for tmpArg in args[1:]:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000363 line = line.replace("%" + str(ii),
Tim Peters2344fae2001-01-15 00:50:52 +0000364 tmpArg)
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000365 ii += 1
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000366 line = line.replace("%*", ' '.join(args[1:]))
367 args = line.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000368 # split into ';;' separated commands
369 # unless it's an alias command
370 if args[0] != 'alias':
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000371 marker = line.find(';;')
Tim Peters2344fae2001-01-15 00:50:52 +0000372 if marker >= 0:
373 # queue up everything after marker
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000374 next = line[marker+2:].lstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000375 self.cmdqueue.append(next)
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000376 line = line[:marker].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000377 return line
378
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000379 def onecmd(self, line):
380 """Interpret the argument as though it had been typed in response
381 to the prompt.
382
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000383 Checks whether this line is typed at the normal prompt or in
384 a breakpoint command list definition.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000385 """
386 if not self.commands_defining:
387 return cmd.Cmd.onecmd(self, line)
388 else:
389 return self.handle_command_def(line)
390
Georg Brandlb90ffd82010-07-30 22:20:16 +0000391 def handle_command_def(self, line):
Georg Brandl44f8bf92010-07-30 08:54:49 +0000392 """Handles one command line during command list definition."""
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000393 cmd, arg, line = self.parseline(line)
Georg Brandl44f8bf92010-07-30 08:54:49 +0000394 if not cmd:
395 return
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000396 if cmd == 'silent':
397 self.commands_silent[self.commands_bnum] = True
398 return # continue to handle other cmd def in the cmd list
399 elif cmd == 'end':
400 self.cmdqueue = []
401 return 1 # end of cmd list
402 cmdlist = self.commands[self.commands_bnum]
Georg Brandl44f8bf92010-07-30 08:54:49 +0000403 if arg:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000404 cmdlist.append(cmd+' '+arg)
405 else:
406 cmdlist.append(cmd)
407 # Determine if we must stop
408 try:
409 func = getattr(self, 'do_' + cmd)
410 except AttributeError:
411 func = self.default
Georg Brandl3078df02009-05-05 09:11:31 +0000412 # one of the resuming commands
413 if func.__name__ in self.commands_resuming:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000414 self.commands_doprompt[self.commands_bnum] = False
415 self.cmdqueue = []
416 return 1
417 return
418
Georg Brandl0d089622010-07-30 16:00:46 +0000419 # interface abstraction functions
420
421 def message(self, msg):
422 print(msg, file=self.stdout)
423
424 def error(self, msg):
425 print('***', msg, file=self.stdout)
426
Tim Peters2344fae2001-01-15 00:50:52 +0000427 # Command definitions, called by cmdloop()
428 # The argument is the remaining string on the command line
429 # Return true to exit from the command loop
430
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000431 def do_commands(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000432 """commands [bpnumber]
433 (com) ...
434 (com) end
435 (Pdb)
Georg Brandl3078df02009-05-05 09:11:31 +0000436
Georg Brandl0d089622010-07-30 16:00:46 +0000437 Specify a list of commands for breakpoint number bpnumber.
438 The commands themselves are entered on the following lines.
439 Type a line containing just 'end' to terminate the commands.
440 The commands are executed when the breakpoint is hit.
441
442 To remove all commands from a breakpoint, type commands and
443 follow it immediately with end; that is, give no commands.
444
445 With no bpnumber argument, commands refers to the last
446 breakpoint set.
447
448 You can use breakpoint commands to start your program up
449 again. Simply use the continue command, or step, or any other
450 command that resumes execution.
451
452 Specifying any command resuming execution (currently continue,
453 step, next, return, jump, quit and their abbreviations)
454 terminates the command list (as if that command was
455 immediately followed by end). This is because any time you
456 resume execution (even with a simple next or step), you may
457 encounter another breakpoint -- which could have its own
458 command list, leading to ambiguities about which list to
459 execute.
460
461 If you use the 'silent' command in the command list, the usual
462 message about stopping at a breakpoint is not printed. This
463 may be desirable for breakpoints that are to print a specific
464 message and then continue. If none of the other commands
465 print anything, you will see no sign that the breakpoint was
466 reached.
467 """
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000468 if not arg:
Georg Brandl7410dd12010-07-30 12:01:20 +0000469 bnum = len(bdb.Breakpoint.bpbynumber) - 1
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000470 else:
471 try:
472 bnum = int(arg)
473 except:
Georg Brandl0d089622010-07-30 16:00:46 +0000474 self.error("Usage: commands [bnum]\n ...\n end")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000475 return
476 self.commands_bnum = bnum
Georg Brandlb90ffd82010-07-30 22:20:16 +0000477 # Save old definitions for the case of a keyboard interrupt.
478 if bnum in self.commands:
479 old_command_defs = (self.commands[bnum],
480 self.commands_doprompt[bnum],
481 self.commands_silent[bnum])
482 else:
483 old_command_defs = None
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000484 self.commands[bnum] = []
485 self.commands_doprompt[bnum] = True
486 self.commands_silent[bnum] = False
Georg Brandlb90ffd82010-07-30 22:20:16 +0000487
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000488 prompt_back = self.prompt
489 self.prompt = '(com) '
490 self.commands_defining = True
Georg Brandl44f8bf92010-07-30 08:54:49 +0000491 try:
492 self.cmdloop()
Georg Brandlb90ffd82010-07-30 22:20:16 +0000493 except KeyboardInterrupt:
494 # Restore old definitions.
495 if old_command_defs:
496 self.commands[bnum] = old_command_defs[0]
497 self.commands_doprompt[bnum] = old_command_defs[1]
498 self.commands_silent[bnum] = old_command_defs[2]
499 else:
500 del self.commands[bnum]
501 del self.commands_doprompt[bnum]
502 del self.commands_silent[bnum]
503 self.error('command definition aborted, old commands restored')
Georg Brandl44f8bf92010-07-30 08:54:49 +0000504 finally:
505 self.commands_defining = False
506 self.prompt = prompt_back
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000507
Tim Peters2344fae2001-01-15 00:50:52 +0000508 def do_break(self, arg, temporary = 0):
Georg Brandl0d089622010-07-30 16:00:46 +0000509 """b(reak) [ ([filename:]lineno | function) [, condition] ]
510 Without argument, list all breaks.
511
512 With a line number argument, set a break at this line in the
513 current file. With a function name, set a break at the first
514 executable line of that function. If a second argument is
515 present, it is a string specifying an expression which must
516 evaluate to true before the breakpoint is honored.
517
518 The line number may be prefixed with a filename and a colon,
519 to specify a breakpoint in another file (probably one that
520 hasn't been loaded yet). The file is searched for on
521 sys.path; the .py suffix may be omitted.
522 """
Tim Peters2344fae2001-01-15 00:50:52 +0000523 if not arg:
524 if self.breaks: # There's at least one
Georg Brandl0d089622010-07-30 16:00:46 +0000525 self.message("Num Type Disp Enb Where")
Tim Peters2344fae2001-01-15 00:50:52 +0000526 for bp in bdb.Breakpoint.bpbynumber:
527 if bp:
Georg Brandl0d089622010-07-30 16:00:46 +0000528 self.message(bp.bpformat())
Tim Peters2344fae2001-01-15 00:50:52 +0000529 return
530 # parse arguments; comma has lowest precedence
531 # and cannot occur in filename
532 filename = None
533 lineno = None
534 cond = None
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000535 comma = arg.find(',')
Tim Peters2344fae2001-01-15 00:50:52 +0000536 if comma > 0:
537 # parse stuff after comma: "condition"
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000538 cond = arg[comma+1:].lstrip()
539 arg = arg[:comma].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000540 # parse stuff before comma: [filename:]lineno | function
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000541 colon = arg.rfind(':')
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000542 funcname = None
Tim Peters2344fae2001-01-15 00:50:52 +0000543 if colon >= 0:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000544 filename = arg[:colon].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000545 f = self.lookupmodule(filename)
546 if not f:
Georg Brandl0d089622010-07-30 16:00:46 +0000547 self.error('%r not found from sys.path' % filename)
Tim Peters2344fae2001-01-15 00:50:52 +0000548 return
549 else:
550 filename = f
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000551 arg = arg[colon+1:].lstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000552 try:
553 lineno = int(arg)
Georg Brandlf93390a2010-10-14 07:17:44 +0000554 except ValueError:
Georg Brandl0d089622010-07-30 16:00:46 +0000555 self.error('Bad lineno: %s' % arg)
Tim Peters2344fae2001-01-15 00:50:52 +0000556 return
557 else:
558 # no colon; can be lineno or function
559 try:
560 lineno = int(arg)
561 except ValueError:
562 try:
563 func = eval(arg,
564 self.curframe.f_globals,
Benjamin Petersond23f8222009-04-05 19:13:16 +0000565 self.curframe_locals)
Tim Peters2344fae2001-01-15 00:50:52 +0000566 except:
567 func = arg
568 try:
Christian Heimesff737952007-11-27 10:40:20 +0000569 if hasattr(func, '__func__'):
570 func = func.__func__
Neal Norwitz221085d2007-02-25 20:55:47 +0000571 code = func.__code__
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000572 #use co_name to identify the bkpt (function names
573 #could be aliased, but co_name is invariant)
574 funcname = code.co_name
Tim Peters2344fae2001-01-15 00:50:52 +0000575 lineno = code.co_firstlineno
576 filename = code.co_filename
577 except:
578 # last thing to try
579 (ok, filename, ln) = self.lineinfo(arg)
580 if not ok:
Georg Brandl0d089622010-07-30 16:00:46 +0000581 self.error('The specified object %r is not a function '
582 'or was not found along sys.path.' % arg)
Tim Peters2344fae2001-01-15 00:50:52 +0000583 return
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000584 funcname = ok # ok contains a function name
Tim Peters2344fae2001-01-15 00:50:52 +0000585 lineno = int(ln)
586 if not filename:
587 filename = self.defaultFile()
588 # Check for reasonable breakpoint
589 line = self.checkline(filename, lineno)
590 if line:
591 # now set the break point
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000592 err = self.set_break(filename, line, temporary, cond, funcname)
Georg Brandl0d089622010-07-30 16:00:46 +0000593 if err:
594 self.error(err, file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000595 else:
596 bp = self.get_breaks(filename, line)[-1]
Georg Brandl0d089622010-07-30 16:00:46 +0000597 self.message("Breakpoint %d at %s:%d" %
598 (bp.number, bp.file, bp.line))
Tim Peters2344fae2001-01-15 00:50:52 +0000599
600 # To be overridden in derived debuggers
601 def defaultFile(self):
602 """Produce a reasonable default."""
603 filename = self.curframe.f_code.co_filename
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000604 if filename == '<string>' and self.mainpyfile:
605 filename = self.mainpyfile
Tim Peters2344fae2001-01-15 00:50:52 +0000606 return filename
607
608 do_b = do_break
609
610 def do_tbreak(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000611 """tbreak [ ([filename:]lineno | function) [, condition] ]
612 Same arguments as break, but sets a temporary breakpoint: it
613 is automatically deleted when first hit.
614 """
Tim Peters2344fae2001-01-15 00:50:52 +0000615 self.do_break(arg, 1)
616
617 def lineinfo(self, identifier):
618 failed = (None, None, None)
619 # Input is identifier, may be in single quotes
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000620 idstring = identifier.split("'")
Tim Peters2344fae2001-01-15 00:50:52 +0000621 if len(idstring) == 1:
622 # not in single quotes
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000623 id = idstring[0].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000624 elif len(idstring) == 3:
625 # quoted
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000626 id = idstring[1].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000627 else:
628 return failed
629 if id == '': return failed
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000630 parts = id.split('.')
Tim Peters2344fae2001-01-15 00:50:52 +0000631 # Protection for derived debuggers
632 if parts[0] == 'self':
633 del parts[0]
634 if len(parts) == 0:
635 return failed
636 # Best first guess at file to look at
637 fname = self.defaultFile()
638 if len(parts) == 1:
639 item = parts[0]
640 else:
641 # More than one part.
642 # First is module, second is method/class
643 f = self.lookupmodule(parts[0])
644 if f:
645 fname = f
646 item = parts[1]
647 answer = find_function(item, fname)
648 return answer or failed
649
650 def checkline(self, filename, lineno):
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000651 """Check whether specified line seems to be executable.
Tim Peters2344fae2001-01-15 00:50:52 +0000652
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000653 Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
654 line or EOF). Warning: testing is not comprehensive.
655 """
Georg Brandl1e30bd32010-07-30 07:21:26 +0000656 # this method should be callable before starting debugging, so default
657 # to "no globals" if there is no current frame
658 globs = self.curframe.f_globals if hasattr(self, 'curframe') else None
659 line = linecache.getline(filename, lineno, globs)
Tim Peters2344fae2001-01-15 00:50:52 +0000660 if not line:
Georg Brandl0d089622010-07-30 16:00:46 +0000661 self.message('End of file')
Tim Peters2344fae2001-01-15 00:50:52 +0000662 return 0
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000663 line = line.strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000664 # Don't allow setting breakpoint at a blank line
Guido van Rossum08454592002-07-12 13:10:53 +0000665 if (not line or (line[0] == '#') or
666 (line[:3] == '"""') or line[:3] == "'''"):
Georg Brandl0d089622010-07-30 16:00:46 +0000667 self.error('Blank or comment')
Tim Peters2344fae2001-01-15 00:50:52 +0000668 return 0
Tim Peters2344fae2001-01-15 00:50:52 +0000669 return lineno
670
671 def do_enable(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000672 """enable bpnumber [bpnumber ...]
673 Enables the breakpoints given as a space separated list of
674 breakpoint numbers.
675 """
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000676 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000677 for i in args:
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000678 try:
Georg Brandl7410dd12010-07-30 12:01:20 +0000679 bp = self.get_bpbynumber(i)
680 except ValueError as err:
Georg Brandl0d089622010-07-30 16:00:46 +0000681 self.error(err)
Georg Brandl7410dd12010-07-30 12:01:20 +0000682 else:
Tim Peters2344fae2001-01-15 00:50:52 +0000683 bp.enable()
Georg Brandl0d089622010-07-30 16:00:46 +0000684 self.message('Enabled %s' % bp)
Tim Peters2344fae2001-01-15 00:50:52 +0000685
686 def do_disable(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000687 """disable bpnumber [bpnumber ...]
688 Disables the breakpoints given as a space separated list of
689 breakpoint numbers. Disabling a breakpoint means it cannot
690 cause the program to stop execution, but unlike clearing a
691 breakpoint, it remains in the list of breakpoints and can be
692 (re-)enabled.
693 """
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000694 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000695 for i in args:
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000696 try:
Georg Brandl7410dd12010-07-30 12:01:20 +0000697 bp = self.get_bpbynumber(i)
698 except ValueError as err:
Georg Brandl0d089622010-07-30 16:00:46 +0000699 self.error(err)
Georg Brandl7410dd12010-07-30 12:01:20 +0000700 else:
Tim Peters2344fae2001-01-15 00:50:52 +0000701 bp.disable()
Georg Brandl0d089622010-07-30 16:00:46 +0000702 self.message('Disabled %s' % bp)
Tim Peters2344fae2001-01-15 00:50:52 +0000703
704 def do_condition(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000705 """condition bpnumber [condition]
706 Set a new condition for the breakpoint, an expression which
707 must evaluate to true before the breakpoint is honored. If
708 condition is absent, any existing condition is removed; i.e.,
709 the breakpoint is made unconditional.
710 """
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000711 args = arg.split(' ', 1)
Thomas Woutersb2137042007-02-01 18:02:27 +0000712 try:
Tim Peters2344fae2001-01-15 00:50:52 +0000713 cond = args[1]
Georg Brandl7410dd12010-07-30 12:01:20 +0000714 except IndexError:
Tim Peters2344fae2001-01-15 00:50:52 +0000715 cond = None
Guido van Rossumd8faa362007-04-27 19:54:29 +0000716 try:
Georg Brandl7410dd12010-07-30 12:01:20 +0000717 bp = self.get_bpbynumber(args[0].strip())
718 except ValueError as err:
Georg Brandl0d089622010-07-30 16:00:46 +0000719 self.error(err)
Georg Brandl7410dd12010-07-30 12:01:20 +0000720 else:
Tim Peters2344fae2001-01-15 00:50:52 +0000721 bp.cond = cond
722 if not cond:
Georg Brandl0d089622010-07-30 16:00:46 +0000723 self.message('Breakpoint %d is now unconditional.' % bp.number)
Georg Brandl7410dd12010-07-30 12:01:20 +0000724 else:
Georg Brandl0d089622010-07-30 16:00:46 +0000725 self.message('New condition set for breakpoint %d.' % bp.number)
Tim Peters2344fae2001-01-15 00:50:52 +0000726
Georg Brandl7410dd12010-07-30 12:01:20 +0000727 def do_ignore(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000728 """ignore bpnumber [count]
729 Set the ignore count for the given breakpoint number. If
730 count is omitted, the ignore count is set to 0. A breakpoint
731 becomes active when the ignore count is zero. When non-zero,
732 the count is decremented each time the breakpoint is reached
733 and the breakpoint is not disabled and any associated
734 condition evaluates to true.
735 """
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000736 args = arg.split()
Thomas Woutersb2137042007-02-01 18:02:27 +0000737 try:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000738 count = int(args[1].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000739 except:
740 count = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +0000741 try:
Georg Brandl7410dd12010-07-30 12:01:20 +0000742 bp = self.get_bpbynumber(args[0].strip())
743 except ValueError as err:
Georg Brandl0d089622010-07-30 16:00:46 +0000744 self.error(err)
Georg Brandl7410dd12010-07-30 12:01:20 +0000745 else:
Tim Peters2344fae2001-01-15 00:50:52 +0000746 bp.ignore = count
Guido van Rossum08454592002-07-12 13:10:53 +0000747 if count > 0:
Guido van Rossum08454592002-07-12 13:10:53 +0000748 if count > 1:
Georg Brandl0d089622010-07-30 16:00:46 +0000749 countstr = '%d crossings' % count
Tim Peters2344fae2001-01-15 00:50:52 +0000750 else:
Georg Brandl0d089622010-07-30 16:00:46 +0000751 countstr = '1 crossing'
752 self.message('Will ignore next %s of breakpoint %d.' %
753 (countstr, bp.number))
Tim Peters2344fae2001-01-15 00:50:52 +0000754 else:
Georg Brandl0d089622010-07-30 16:00:46 +0000755 self.message('Will stop next time breakpoint %d is reached.'
756 % bp.number)
Tim Peters2344fae2001-01-15 00:50:52 +0000757
758 def do_clear(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000759 """cl(ear) filename:lineno\ncl(ear) [bpnumber [bpnumber...]]
760 With a space separated list of breakpoint numbers, clear
761 those breakpoints. Without argument, clear all breaks (but
762 first ask confirmation). With a filename:lineno argument,
763 clear all breaks at that line in that file.
764 """
Tim Peters2344fae2001-01-15 00:50:52 +0000765 if not arg:
766 try:
Guido van Rossumc5b6ab02007-05-27 09:19:52 +0000767 reply = input('Clear all breaks? ')
Tim Peters2344fae2001-01-15 00:50:52 +0000768 except EOFError:
769 reply = 'no'
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000770 reply = reply.strip().lower()
Tim Peters2344fae2001-01-15 00:50:52 +0000771 if reply in ('y', 'yes'):
Georg Brandl7410dd12010-07-30 12:01:20 +0000772 bplist = [bp for bp in bdb.Breakpoint.bpbynumber if bp]
Tim Peters2344fae2001-01-15 00:50:52 +0000773 self.clear_all_breaks()
Georg Brandl7410dd12010-07-30 12:01:20 +0000774 for bp in bplist:
Georg Brandl0d089622010-07-30 16:00:46 +0000775 self.message('Deleted %s' % bp)
Tim Peters2344fae2001-01-15 00:50:52 +0000776 return
777 if ':' in arg:
778 # Make sure it works for "clear C:\foo\bar.py:12"
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000779 i = arg.rfind(':')
Tim Peters2344fae2001-01-15 00:50:52 +0000780 filename = arg[:i]
781 arg = arg[i+1:]
782 try:
783 lineno = int(arg)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000784 except ValueError:
Tim Peters2344fae2001-01-15 00:50:52 +0000785 err = "Invalid line number (%s)" % arg
786 else:
Georg Brandl7410dd12010-07-30 12:01:20 +0000787 bplist = self.get_breaks(filename, lineno)
Tim Peters2344fae2001-01-15 00:50:52 +0000788 err = self.clear_break(filename, lineno)
Georg Brandl7410dd12010-07-30 12:01:20 +0000789 if err:
Georg Brandl0d089622010-07-30 16:00:46 +0000790 self.error(err)
Georg Brandl7410dd12010-07-30 12:01:20 +0000791 else:
792 for bp in bplist:
Georg Brandl0d089622010-07-30 16:00:46 +0000793 self.message('Deleted %s' % bp)
Tim Peters2344fae2001-01-15 00:50:52 +0000794 return
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000795 numberlist = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000796 for i in numberlist:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000797 try:
Georg Brandl7410dd12010-07-30 12:01:20 +0000798 bp = self.get_bpbynumber(i)
799 except ValueError as err:
Georg Brandl0d089622010-07-30 16:00:46 +0000800 self.error(err)
Tim Peters2344fae2001-01-15 00:50:52 +0000801 else:
Senthil Kumaran6f107042010-11-29 11:54:17 +0000802 self.clear_bpbynumber(i)
Georg Brandl0d089622010-07-30 16:00:46 +0000803 self.message('Deleted %s' % bp)
Tim Peters2344fae2001-01-15 00:50:52 +0000804 do_cl = do_clear # 'c' is already an abbreviation for 'continue'
805
806 def do_where(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000807 """w(here)
808 Print a stack trace, with the most recent frame at the bottom.
809 An arrow indicates the "current frame", which determines the
810 context of most commands. 'bt' is an alias for this command.
811 """
Tim Peters2344fae2001-01-15 00:50:52 +0000812 self.print_stack_trace()
813 do_w = do_where
Guido van Rossum6bd68352001-01-20 17:57:37 +0000814 do_bt = do_where
Tim Peters2344fae2001-01-15 00:50:52 +0000815
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000816 def _select_frame(self, number):
817 assert 0 <= number < len(self.stack)
818 self.curindex = number
819 self.curframe = self.stack[self.curindex][0]
820 self.curframe_locals = self.curframe.f_locals
821 self.print_stack_entry(self.stack[self.curindex])
822 self.lineno = None
823
Tim Peters2344fae2001-01-15 00:50:52 +0000824 def do_up(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000825 """u(p) [count]
826 Move the current frame count (default one) levels up in the
827 stack trace (to an older frame).
828 """
Tim Peters2344fae2001-01-15 00:50:52 +0000829 if self.curindex == 0:
Georg Brandl0d089622010-07-30 16:00:46 +0000830 self.error('Oldest frame')
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000831 return
832 try:
833 count = int(arg or 1)
834 except ValueError:
Georg Brandl0d089622010-07-30 16:00:46 +0000835 self.error('Invalid frame count (%s)' % arg)
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000836 return
837 if count < 0:
838 newframe = 0
Tim Peters2344fae2001-01-15 00:50:52 +0000839 else:
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000840 newframe = max(0, self.curindex - count)
841 self._select_frame(newframe)
Tim Peters2344fae2001-01-15 00:50:52 +0000842 do_u = do_up
843
844 def do_down(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000845 """d(own) [count]
846 Move the current frame count (default one) levels down in the
847 stack trace (to a newer frame).
848 """
Tim Peters2344fae2001-01-15 00:50:52 +0000849 if self.curindex + 1 == len(self.stack):
Georg Brandl0d089622010-07-30 16:00:46 +0000850 self.error('Newest frame')
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000851 return
852 try:
853 count = int(arg or 1)
854 except ValueError:
Georg Brandl0d089622010-07-30 16:00:46 +0000855 self.error('Invalid frame count (%s)' % arg)
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000856 return
857 if count < 0:
858 newframe = len(self.stack) - 1
Tim Peters2344fae2001-01-15 00:50:52 +0000859 else:
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000860 newframe = min(len(self.stack) - 1, self.curindex + count)
861 self._select_frame(newframe)
Tim Peters2344fae2001-01-15 00:50:52 +0000862 do_d = do_down
863
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000864 def do_until(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000865 """unt(il) [lineno]
866 Without argument, continue execution until the line with a
867 number greater than the current one is reached. With a line
868 number, continue execution until a line with a number greater
869 or equal to that is reached. In both cases, also stop when
870 the current frame returns.
871 """
Georg Brandl2dfec552010-07-30 08:43:32 +0000872 if arg:
873 try:
874 lineno = int(arg)
875 except ValueError:
Georg Brandl0d089622010-07-30 16:00:46 +0000876 self.error('Error in argument: %r' % arg)
Georg Brandl2dfec552010-07-30 08:43:32 +0000877 return
878 if lineno <= self.curframe.f_lineno:
Georg Brandl0d089622010-07-30 16:00:46 +0000879 self.error('"until" line number is smaller than current '
880 'line number')
Georg Brandl2dfec552010-07-30 08:43:32 +0000881 return
882 else:
883 lineno = None
884 self.set_until(self.curframe, lineno)
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000885 return 1
886 do_unt = do_until
887
Tim Peters2344fae2001-01-15 00:50:52 +0000888 def do_step(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000889 """s(tep)
890 Execute the current line, stop at the first possible occasion
891 (either in a function that is called or in the current
892 function).
893 """
Tim Peters2344fae2001-01-15 00:50:52 +0000894 self.set_step()
895 return 1
896 do_s = do_step
897
898 def do_next(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000899 """n(ext)
900 Continue execution until the next line in the current function
901 is reached or it returns.
902 """
Tim Peters2344fae2001-01-15 00:50:52 +0000903 self.set_next(self.curframe)
904 return 1
905 do_n = do_next
906
Guido van Rossumd8faa362007-04-27 19:54:29 +0000907 def do_run(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000908 """run [args...]
909 Restart the debugged python program. If a string is supplied
910 it is splitted with "shlex", and the result is used as the new
911 sys.argv. History, breakpoints, actions and debugger options
912 are preserved. "restart" is an alias for "run".
913 """
Guido van Rossumd8faa362007-04-27 19:54:29 +0000914 if arg:
915 import shlex
916 argv0 = sys.argv[0:1]
917 sys.argv = shlex.split(arg)
918 sys.argv[:0] = argv0
Georg Brandl0d089622010-07-30 16:00:46 +0000919 # this is caught in the main debugger loop
Guido van Rossumd8faa362007-04-27 19:54:29 +0000920 raise Restart
921
922 do_restart = do_run
923
Tim Peters2344fae2001-01-15 00:50:52 +0000924 def do_return(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000925 """r(eturn)
926 Continue execution until the current function returns.
927 """
Tim Peters2344fae2001-01-15 00:50:52 +0000928 self.set_return(self.curframe)
929 return 1
930 do_r = do_return
931
932 def do_continue(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000933 """c(ont(inue))
934 Continue execution, only stop when a breakpoint is encountered.
935 """
Georg Brandl44f2b642010-12-04 16:00:47 +0000936 if not self.nosigint:
937 self._previous_sigint_handler = \
938 signal.signal(signal.SIGINT, self.sigint_handler)
Tim Peters2344fae2001-01-15 00:50:52 +0000939 self.set_continue()
940 return 1
941 do_c = do_cont = do_continue
942
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000943 def do_jump(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000944 """j(ump) lineno
945 Set the next line that will be executed. Only available in
946 the bottom-most frame. This lets you jump back and execute
947 code again, or jump forward to skip code that you don't want
948 to run.
949
950 It should be noted that not all jumps are allowed -- for
951 instance it is not possible to jump into the middle of a
952 for loop or out of a finally clause.
953 """
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000954 if self.curindex + 1 != len(self.stack):
Georg Brandl0d089622010-07-30 16:00:46 +0000955 self.error('You can only jump within the bottom frame')
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000956 return
957 try:
958 arg = int(arg)
959 except ValueError:
Georg Brandl0d089622010-07-30 16:00:46 +0000960 self.error("The 'jump' command requires a line number")
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000961 else:
962 try:
963 # Do the jump, fix up our copy of the stack, and display the
964 # new position
965 self.curframe.f_lineno = arg
966 self.stack[self.curindex] = self.stack[self.curindex][0], arg
967 self.print_stack_entry(self.stack[self.curindex])
Guido van Rossumb940e112007-01-10 16:19:56 +0000968 except ValueError as e:
Georg Brandl0d089622010-07-30 16:00:46 +0000969 self.error('Jump failed: %s' % e)
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000970 do_j = do_jump
971
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000972 def do_debug(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000973 """debug code
974 Enter a recursive debugger that steps through the code
975 argument (which is an arbitrary expression or statement to be
976 executed in the current environment).
977 """
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000978 sys.settrace(None)
979 globals = self.curframe.f_globals
Benjamin Petersond23f8222009-04-05 19:13:16 +0000980 locals = self.curframe_locals
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000981 p = Pdb(self.completekey, self.stdin, self.stdout)
Guido van Rossumed538d82003-04-09 19:36:34 +0000982 p.prompt = "(%s) " % self.prompt.strip()
Georg Brandl0d089622010-07-30 16:00:46 +0000983 self.message("ENTERING RECURSIVE DEBUGGER")
Guido van Rossumed538d82003-04-09 19:36:34 +0000984 sys.call_tracing(p.run, (arg, globals, locals))
Georg Brandl0d089622010-07-30 16:00:46 +0000985 self.message("LEAVING RECURSIVE DEBUGGER")
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000986 sys.settrace(self.trace_dispatch)
987 self.lastcmd = p.lastcmd
988
Tim Peters2344fae2001-01-15 00:50:52 +0000989 def do_quit(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000990 """q(uit)\nexit
991 Quit from the debugger. The program being executed is aborted.
992 """
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000993 self._user_requested_quit = True
Tim Peters2344fae2001-01-15 00:50:52 +0000994 self.set_quit()
995 return 1
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000996
Tim Peters2344fae2001-01-15 00:50:52 +0000997 do_q = do_quit
Guido van Rossumd1c08f32002-04-15 00:48:24 +0000998 do_exit = do_quit
Tim Peters2344fae2001-01-15 00:50:52 +0000999
Guido van Rossumeef26072003-01-13 21:13:55 +00001000 def do_EOF(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001001 """EOF
1002 Handles the receipt of EOF as a command.
1003 """
1004 self.message('')
Georg Brandlac9a2bb2010-11-29 20:19:15 +00001005 self._user_requested_quit = True
Guido van Rossumeef26072003-01-13 21:13:55 +00001006 self.set_quit()
1007 return 1
1008
Tim Peters2344fae2001-01-15 00:50:52 +00001009 def do_args(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001010 """a(rgs)
1011 Print the argument list of the current function.
1012 """
Benjamin Petersond23f8222009-04-05 19:13:16 +00001013 co = self.curframe.f_code
1014 dict = self.curframe_locals
Tim Peters2344fae2001-01-15 00:50:52 +00001015 n = co.co_argcount
1016 if co.co_flags & 4: n = n+1
1017 if co.co_flags & 8: n = n+1
1018 for i in range(n):
1019 name = co.co_varnames[i]
Georg Brandl0d089622010-07-30 16:00:46 +00001020 if name in dict:
1021 self.message('%s = %r' % (name, dict[name]))
1022 else:
1023 self.message('%s = *** undefined ***' % (name,))
Tim Peters2344fae2001-01-15 00:50:52 +00001024 do_a = do_args
Guido van Rossum2424f851998-09-11 22:50:09 +00001025
Tim Peters2344fae2001-01-15 00:50:52 +00001026 def do_retval(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001027 """retval
1028 Print the return value for the last return of a function.
1029 """
Benjamin Petersond23f8222009-04-05 19:13:16 +00001030 if '__return__' in self.curframe_locals:
Georg Brandl0d089622010-07-30 16:00:46 +00001031 self.message(repr(self.curframe_locals['__return__']))
Tim Peters2344fae2001-01-15 00:50:52 +00001032 else:
Georg Brandl0d089622010-07-30 16:00:46 +00001033 self.error('Not yet returned!')
Tim Peters2344fae2001-01-15 00:50:52 +00001034 do_rv = do_retval
Guido van Rossum2424f851998-09-11 22:50:09 +00001035
Barry Warsaw210bd202002-11-05 22:40:20 +00001036 def _getval(self, arg):
Tim Peters2344fae2001-01-15 00:50:52 +00001037 try:
Benjamin Petersond23f8222009-04-05 19:13:16 +00001038 return eval(arg, self.curframe.f_globals, self.curframe_locals)
Tim Peters2344fae2001-01-15 00:50:52 +00001039 except:
Georg Brandl0d089622010-07-30 16:00:46 +00001040 exc_info = sys.exc_info()[:2]
1041 self.error(traceback.format_exception_only(*exc_info)[-1].strip())
Barry Warsaw210bd202002-11-05 22:40:20 +00001042 raise
Guido van Rossum2424f851998-09-11 22:50:09 +00001043
Barry Warsaw210bd202002-11-05 22:40:20 +00001044 def do_p(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001045 """p(rint) expression
1046 Print the value of the expression.
1047 """
Barry Warsaw210bd202002-11-05 22:40:20 +00001048 try:
Georg Brandl0d089622010-07-30 16:00:46 +00001049 self.message(repr(self._getval(arg)))
Barry Warsaw210bd202002-11-05 22:40:20 +00001050 except:
1051 pass
Georg Brandlc9879242007-09-04 07:07:56 +00001052 # make "print" an alias of "p" since print isn't a Python statement anymore
1053 do_print = do_p
Barry Warsaw210bd202002-11-05 22:40:20 +00001054
1055 def do_pp(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001056 """pp expression
1057 Pretty-print the value of the expression.
1058 """
Barry Warsaw210bd202002-11-05 22:40:20 +00001059 try:
Georg Brandl0d089622010-07-30 16:00:46 +00001060 self.message(pprint.pformat(self._getval(arg)))
Barry Warsaw210bd202002-11-05 22:40:20 +00001061 except:
1062 pass
Guido van Rossum2424f851998-09-11 22:50:09 +00001063
Tim Peters2344fae2001-01-15 00:50:52 +00001064 def do_list(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001065 """l(ist) [first [,last] | .]
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001066
1067 List source code for the current file. Without arguments,
1068 list 11 lines around the current line or continue the previous
1069 listing. With . as argument, list 11 lines around the current
1070 line. With one argument, list 11 lines starting at that line.
1071 With two arguments, list the given range; if the second
1072 argument is less than the first, it is a count.
1073
1074 The current line in the current frame is indicated by "->".
1075 If an exception is being debugged, the line where the
1076 exception was originally raised or propagated is indicated by
1077 ">>", if it differs from the current line.
Georg Brandl0d089622010-07-30 16:00:46 +00001078 """
Tim Peters2344fae2001-01-15 00:50:52 +00001079 self.lastcmd = 'list'
1080 last = None
Georg Brandla91a94b2010-07-30 07:14:01 +00001081 if arg and arg != '.':
Tim Peters2344fae2001-01-15 00:50:52 +00001082 try:
Georg Brandl0d089622010-07-30 16:00:46 +00001083 if ',' in arg:
1084 first, last = arg.split(',')
1085 first = int(first.strip())
1086 last = int(last.strip())
Tim Peters2344fae2001-01-15 00:50:52 +00001087 if last < first:
Georg Brandl0d089622010-07-30 16:00:46 +00001088 # assume it's a count
Tim Peters2344fae2001-01-15 00:50:52 +00001089 last = first + last
1090 else:
Georg Brandl0d089622010-07-30 16:00:46 +00001091 first = int(arg.strip())
1092 first = max(1, first - 5)
1093 except ValueError:
1094 self.error('Error in argument: %r' % arg)
Tim Peters2344fae2001-01-15 00:50:52 +00001095 return
Georg Brandla91a94b2010-07-30 07:14:01 +00001096 elif self.lineno is None or arg == '.':
Tim Peters2344fae2001-01-15 00:50:52 +00001097 first = max(1, self.curframe.f_lineno - 5)
1098 else:
1099 first = self.lineno + 1
1100 if last is None:
1101 last = first + 10
1102 filename = self.curframe.f_code.co_filename
1103 breaklist = self.get_file_breaks(filename)
1104 try:
Georg Brandle59ca2a2010-07-30 17:04:28 +00001105 lines = linecache.getlines(filename, self.curframe.f_globals)
1106 self._print_lines(lines[first-1:last], first, breaklist,
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001107 self.curframe)
Georg Brandle59ca2a2010-07-30 17:04:28 +00001108 self.lineno = min(last, len(lines))
1109 if len(lines) < last:
1110 self.message('[EOF]')
Tim Peters2344fae2001-01-15 00:50:52 +00001111 except KeyboardInterrupt:
1112 pass
1113 do_l = do_list
Guido van Rossum2424f851998-09-11 22:50:09 +00001114
Georg Brandle59ca2a2010-07-30 17:04:28 +00001115 def do_longlist(self, arg):
1116 """longlist | ll
1117 List the whole source code for the current function or frame.
1118 """
1119 filename = self.curframe.f_code.co_filename
1120 breaklist = self.get_file_breaks(filename)
1121 try:
Georg Brandl5ed2b5a2010-07-30 18:08:12 +00001122 lines, lineno = getsourcelines(self.curframe)
Georg Brandle59ca2a2010-07-30 17:04:28 +00001123 except IOError as err:
1124 self.error(err)
1125 return
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001126 self._print_lines(lines, lineno, breaklist, self.curframe)
Georg Brandle59ca2a2010-07-30 17:04:28 +00001127 do_ll = do_longlist
1128
1129 def do_source(self, arg):
1130 """source expression
1131 Try to get source code for the given object and display it.
1132 """
1133 try:
1134 obj = self._getval(arg)
1135 except:
1136 return
1137 try:
Georg Brandl5ed2b5a2010-07-30 18:08:12 +00001138 lines, lineno = getsourcelines(obj)
Georg Brandle59ca2a2010-07-30 17:04:28 +00001139 except (IOError, TypeError) as err:
1140 self.error(err)
1141 return
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001142 self._print_lines(lines, lineno)
Georg Brandle59ca2a2010-07-30 17:04:28 +00001143
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001144 def _print_lines(self, lines, start, breaks=(), frame=None):
Georg Brandle59ca2a2010-07-30 17:04:28 +00001145 """Print a range of lines."""
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001146 if frame:
1147 current_lineno = frame.f_lineno
1148 exc_lineno = self.tb_lineno.get(frame, -1)
1149 else:
1150 current_lineno = exc_lineno = -1
Georg Brandle59ca2a2010-07-30 17:04:28 +00001151 for lineno, line in enumerate(lines, start):
1152 s = str(lineno).rjust(3)
1153 if len(s) < 4:
1154 s += ' '
1155 if lineno in breaks:
1156 s += 'B'
1157 else:
1158 s += ' '
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001159 if lineno == current_lineno:
Georg Brandle59ca2a2010-07-30 17:04:28 +00001160 s += '->'
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001161 elif lineno == exc_lineno:
Georg Brandle59ca2a2010-07-30 17:04:28 +00001162 s += '>>'
1163 self.message(s + '\t' + line.rstrip())
1164
Tim Peters2344fae2001-01-15 00:50:52 +00001165 def do_whatis(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001166 """whatis arg
1167 Print the type of the argument.
1168 """
Tim Peters2344fae2001-01-15 00:50:52 +00001169 try:
Georg Brandl0d089622010-07-30 16:00:46 +00001170 value = self._getval(arg)
Tim Peters2344fae2001-01-15 00:50:52 +00001171 except:
Georg Brandl0d089622010-07-30 16:00:46 +00001172 # _getval() already printed the error
Tim Peters2344fae2001-01-15 00:50:52 +00001173 return
1174 code = None
1175 # Is it a function?
Georg Brandl0d089622010-07-30 16:00:46 +00001176 try:
1177 code = value.__code__
1178 except Exception:
1179 pass
Tim Peters2344fae2001-01-15 00:50:52 +00001180 if code:
Georg Brandl0d089622010-07-30 16:00:46 +00001181 self.message('Function %s' % code.co_name)
Tim Peters2344fae2001-01-15 00:50:52 +00001182 return
1183 # Is it an instance method?
Georg Brandl0d089622010-07-30 16:00:46 +00001184 try:
1185 code = value.__func__.__code__
1186 except Exception:
1187 pass
Tim Peters2344fae2001-01-15 00:50:52 +00001188 if code:
Georg Brandl0d089622010-07-30 16:00:46 +00001189 self.message('Method %s' % code.co_name)
1190 return
1191 # Is it a class?
1192 if value.__class__ is type:
1193 self.message('Class %s.%s' % (value.__module__, value.__name__))
Tim Peters2344fae2001-01-15 00:50:52 +00001194 return
1195 # None of the above...
Georg Brandl0d089622010-07-30 16:00:46 +00001196 self.message(type(value))
Guido van Rossum8e2ec561993-07-29 09:37:38 +00001197
Georg Brandl1acb7462010-12-04 11:20:26 +00001198 def do_interact(self, arg):
1199 """interact
1200
1201 Start an interative interpreter whose global namespace
1202 contains all the (global and local) names found in the current scope.
1203 """
1204 ns = self.curframe.f_globals.copy()
1205 ns.update(self.curframe_locals)
1206 code.interact("*interactive*", local=ns)
1207
Tim Peters2344fae2001-01-15 00:50:52 +00001208 def do_alias(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001209 """alias [name [command [parameter parameter ...] ]]
1210 Create an alias called 'name' that executes 'command'. The
1211 command must *not* be enclosed in quotes. Replaceable
1212 parameters can be indicated by %1, %2, and so on, while %* is
1213 replaced by all the parameters. If no command is given, the
1214 current alias for name is shown. If no name is given, all
1215 aliases are listed.
1216
1217 Aliases may be nested and can contain anything that can be
1218 legally typed at the pdb prompt. Note! You *can* override
1219 internal pdb commands with aliases! Those internal commands
1220 are then hidden until the alias is removed. Aliasing is
1221 recursively applied to the first word of the command line; all
1222 other words in the line are left alone.
1223
1224 As an example, here are two useful aliases (especially when
1225 placed in the .pdbrc file):
1226
1227 # Print instance variables (usage "pi classInst")
1228 alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
1229 # Print instance variables in self
1230 alias ps pi self
1231 """
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +00001232 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +00001233 if len(args) == 0:
Benjamin Petersonbe74a372009-09-11 21:17:13 +00001234 keys = sorted(self.aliases.keys())
Tim Peters2344fae2001-01-15 00:50:52 +00001235 for alias in keys:
Georg Brandl0d089622010-07-30 16:00:46 +00001236 self.message("%s = %s" % (alias, self.aliases[alias]))
Tim Peters2344fae2001-01-15 00:50:52 +00001237 return
Guido van Rossum08454592002-07-12 13:10:53 +00001238 if args[0] in self.aliases and len(args) == 1:
Georg Brandl0d089622010-07-30 16:00:46 +00001239 self.message("%s = %s" % (args[0], self.aliases[args[0]]))
Tim Peters2344fae2001-01-15 00:50:52 +00001240 else:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +00001241 self.aliases[args[0]] = ' '.join(args[1:])
Guido van Rossum23efba41992-01-27 16:58:47 +00001242
Tim Peters2344fae2001-01-15 00:50:52 +00001243 def do_unalias(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001244 """unalias name
1245 Delete the specified alias.
1246 """
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +00001247 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +00001248 if len(args) == 0: return
Raymond Hettinger54f02222002-06-01 14:18:47 +00001249 if args[0] in self.aliases:
Tim Peters2344fae2001-01-15 00:50:52 +00001250 del self.aliases[args[0]]
Guido van Rossum00230781993-03-29 11:39:45 +00001251
Georg Brandl0d089622010-07-30 16:00:46 +00001252 # List of all the commands making the program resume execution.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001253 commands_resuming = ['do_continue', 'do_step', 'do_next', 'do_return',
1254 'do_quit', 'do_jump']
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001255
Tim Peters2344fae2001-01-15 00:50:52 +00001256 # Print a traceback starting at the top stack frame.
1257 # The most recently entered frame is printed last;
1258 # this is different from dbx and gdb, but consistent with
1259 # the Python interpreter's stack trace.
1260 # It is also consistent with the up/down commands (which are
1261 # compatible with dbx and gdb: up moves towards 'main()'
1262 # and down moves towards the most recent stack frame).
Guido van Rossum2424f851998-09-11 22:50:09 +00001263
Tim Peters2344fae2001-01-15 00:50:52 +00001264 def print_stack_trace(self):
1265 try:
1266 for frame_lineno in self.stack:
1267 self.print_stack_entry(frame_lineno)
1268 except KeyboardInterrupt:
1269 pass
Guido van Rossum2424f851998-09-11 22:50:09 +00001270
Tim Peters2344fae2001-01-15 00:50:52 +00001271 def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix):
1272 frame, lineno = frame_lineno
1273 if frame is self.curframe:
Georg Brandl0d089622010-07-30 16:00:46 +00001274 prefix = '> '
Tim Peters2344fae2001-01-15 00:50:52 +00001275 else:
Georg Brandl0d089622010-07-30 16:00:46 +00001276 prefix = ' '
1277 self.message(prefix +
1278 self.format_stack_entry(frame_lineno, prompt_prefix))
Guido van Rossum2424f851998-09-11 22:50:09 +00001279
Georg Brandl0d089622010-07-30 16:00:46 +00001280 # Provide help
Guido van Rossum921c8241992-01-10 14:54:42 +00001281
Georg Brandl0d089622010-07-30 16:00:46 +00001282 def do_help(self, arg):
1283 """h(elp)
1284 Without argument, print the list of available commands.
1285 With a command name as argument, print help about that command.
1286 "help pdb" shows the full pdb documentation.
1287 "help exec" gives help on the ! command.
1288 """
1289 if not arg:
1290 return cmd.Cmd.do_help(self, arg)
1291 try:
1292 try:
1293 topic = getattr(self, 'help_' + arg)
1294 return topic()
1295 except AttributeError:
1296 command = getattr(self, 'do_' + arg)
1297 except AttributeError:
1298 self.error('No help for %r' % arg)
1299 else:
Georg Brandl9e7dbc82010-10-14 07:14:31 +00001300 if sys.flags.optimize >= 2:
1301 self.error('No help for %r; please do not run Python with -OO '
1302 'if you need command help' % arg)
1303 return
Georg Brandl0d089622010-07-30 16:00:46 +00001304 self.message(command.__doc__.rstrip())
Guido van Rossum921c8241992-01-10 14:54:42 +00001305
Georg Brandl0d089622010-07-30 16:00:46 +00001306 do_h = do_help
Barry Warsaw210bd202002-11-05 22:40:20 +00001307
Tim Peters2344fae2001-01-15 00:50:52 +00001308 def help_exec(self):
Georg Brandl0d089622010-07-30 16:00:46 +00001309 """(!) statement
1310 Execute the (one-line) statement in the context of the current
1311 stack frame. The exclamation point can be omitted unless the
1312 first word of the statement resembles a debugger command. To
1313 assign to a global variable you must always prefix the command
1314 with a 'global' command, e.g.:
1315 (Pdb) global list_options; list_options = ['-l']
1316 (Pdb)
1317 """
Georg Brandl9e7dbc82010-10-14 07:14:31 +00001318 self.message((self.help_exec.__doc__ or '').strip())
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001319
Tim Peters2344fae2001-01-15 00:50:52 +00001320 def help_pdb(self):
1321 help()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001322
Georg Brandl0d089622010-07-30 16:00:46 +00001323 # other helper functions
1324
Tim Peters2344fae2001-01-15 00:50:52 +00001325 def lookupmodule(self, filename):
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001326 """Helper function for break/clear parsing -- may be overridden.
1327
1328 lookupmodule() translates (possibly incomplete) file or module name
1329 into an absolute file name.
1330 """
1331 if os.path.isabs(filename) and os.path.exists(filename):
Tim Peterse718f612004-10-12 21:51:32 +00001332 return filename
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001333 f = os.path.join(sys.path[0], filename)
1334 if os.path.exists(f) and self.canonic(f) == self.mainpyfile:
1335 return f
Tim Peters2344fae2001-01-15 00:50:52 +00001336 root, ext = os.path.splitext(filename)
1337 if ext == '':
1338 filename = filename + '.py'
1339 if os.path.isabs(filename):
1340 return filename
1341 for dirname in sys.path:
1342 while os.path.islink(dirname):
1343 dirname = os.readlink(dirname)
1344 fullname = os.path.join(dirname, filename)
1345 if os.path.exists(fullname):
1346 return fullname
1347 return None
Guido van Rossumb5699c71998-07-20 23:13:54 +00001348
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001349 def _runscript(self, filename):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001350 # The script has to run in __main__ namespace (or imports from
1351 # __main__ will break).
1352 #
1353 # So we clear up the __main__ and set several special variables
1354 # (this gets rid of pdb's globals and cleans old variables on restarts).
1355 import __main__
1356 __main__.__dict__.clear()
1357 __main__.__dict__.update({"__name__" : "__main__",
1358 "__file__" : filename,
1359 "__builtins__": __builtins__,
1360 })
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001361
1362 # When bdb sets tracing, a number of call and line events happens
1363 # BEFORE debugger even reaches user's code (and the exact sequence of
1364 # events depends on python version). So we take special measures to
1365 # avoid stopping before we reach the main script (see user_line and
1366 # user_call for details).
Georg Brandlac9a2bb2010-11-29 20:19:15 +00001367 self._wait_for_mainpyfile = True
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001368 self.mainpyfile = self.canonic(filename)
Georg Brandlac9a2bb2010-11-29 20:19:15 +00001369 self._user_requested_quit = False
Georg Brandld07ac642009-08-13 07:50:57 +00001370 with open(filename, "rb") as fp:
1371 statement = "exec(compile(%r, %r, 'exec'))" % \
1372 (fp.read(), self.mainpyfile)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001373 self.run(statement)
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001374
Georg Brandl9e7dbc82010-10-14 07:14:31 +00001375# Collect all command help into docstring, if not run with -OO
Georg Brandl0d089622010-07-30 16:00:46 +00001376
Georg Brandl9e7dbc82010-10-14 07:14:31 +00001377if __doc__ is not None:
1378 # unfortunately we can't guess this order from the class definition
1379 _help_order = [
1380 'help', 'where', 'down', 'up', 'break', 'tbreak', 'clear', 'disable',
1381 'enable', 'ignore', 'condition', 'commands', 'step', 'next', 'until',
1382 'jump', 'return', 'retval', 'run', 'continue', 'list', 'longlist',
Georg Brandl1acb7462010-12-04 11:20:26 +00001383 'args', 'print', 'pp', 'whatis', 'source', 'interact', 'alias',
1384 'unalias', 'debug', 'quit',
Georg Brandl9e7dbc82010-10-14 07:14:31 +00001385 ]
Georg Brandl0d089622010-07-30 16:00:46 +00001386
Georg Brandl9e7dbc82010-10-14 07:14:31 +00001387 for _command in _help_order:
1388 __doc__ += getattr(Pdb, 'do_' + _command).__doc__.strip() + '\n\n'
1389 __doc__ += Pdb.help_exec.__doc__
Georg Brandl0d089622010-07-30 16:00:46 +00001390
Georg Brandl9e7dbc82010-10-14 07:14:31 +00001391 del _help_order, _command
1392
Georg Brandl0d089622010-07-30 16:00:46 +00001393
Guido van Rossum35771131992-09-08 11:59:04 +00001394# Simplified interface
1395
Guido van Rossum5e38b6f1995-02-27 13:13:40 +00001396def run(statement, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +00001397 Pdb().run(statement, globals, locals)
Guido van Rossum5e38b6f1995-02-27 13:13:40 +00001398
1399def runeval(expression, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +00001400 return Pdb().runeval(expression, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001401
1402def runctx(statement, globals, locals):
Tim Peters2344fae2001-01-15 00:50:52 +00001403 # B/W compatibility
1404 run(statement, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001405
Raymond Hettinger2ef7e6c2004-10-24 00:32:24 +00001406def runcall(*args, **kwds):
1407 return Pdb().runcall(*args, **kwds)
Guido van Rossum4e160981992-09-02 20:43:20 +00001408
Guido van Rossumb6775db1994-08-01 11:34:53 +00001409def set_trace():
Johannes Gijsbers84a6c202004-11-07 11:35:30 +00001410 Pdb().set_trace(sys._getframe().f_back)
Guido van Rossum35771131992-09-08 11:59:04 +00001411
1412# Post-Mortem interface
1413
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001414def post_mortem(t=None):
1415 # handling the default
1416 if t is None:
1417 # sys.exc_info() returns (type, value, traceback) if an exception is
1418 # being handled, otherwise it returns None
1419 t = sys.exc_info()[2]
Georg Brandl0d089622010-07-30 16:00:46 +00001420 if t is None:
1421 raise ValueError("A valid traceback must be passed if no "
1422 "exception is being handled")
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001423
Tim Peters2344fae2001-01-15 00:50:52 +00001424 p = Pdb()
1425 p.reset()
Benjamin Peterson1a6e0d02008-10-25 15:49:17 +00001426 p.interaction(None, t)
Guido van Rossum35771131992-09-08 11:59:04 +00001427
1428def pm():
Tim Peters2344fae2001-01-15 00:50:52 +00001429 post_mortem(sys.last_traceback)
Guido van Rossum35771131992-09-08 11:59:04 +00001430
1431
1432# Main program for testing
1433
Guido van Rossum23efba41992-01-27 16:58:47 +00001434TESTCMD = 'import x; x.main()'
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001435
Guido van Rossum921c8241992-01-10 14:54:42 +00001436def test():
Tim Peters2344fae2001-01-15 00:50:52 +00001437 run(TESTCMD)
Guido van Rossume61fa0a1993-10-22 13:56:35 +00001438
1439# print help
1440def help():
Georg Brandl02053ee2010-07-18 10:11:03 +00001441 import pydoc
1442 pydoc.pager(__doc__)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001443
Georg Brandle0230912010-07-30 08:29:39 +00001444_usage = """\
1445usage: pdb.py [-c command] ... pyfile [arg] ...
1446
1447Debug the Python program given by pyfile.
1448
1449Initial commands are read from .pdbrc files in your home directory
1450and in the current directory, if they exist. Commands supplied with
1451-c are executed after commands from .pdbrc files.
1452
1453To let the script run until an exception occurs, use "-c continue".
Georg Brandl2dfec552010-07-30 08:43:32 +00001454To let the script run up to a given line X in the debugged file, use
1455"-c 'until X'"."""
Georg Brandle0230912010-07-30 08:29:39 +00001456
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001457def main():
Georg Brandle0230912010-07-30 08:29:39 +00001458 import getopt
1459
1460 opts, args = getopt.getopt(sys.argv[1:], 'hc:', ['--help', '--command='])
1461
1462 if not args:
1463 print(_usage)
Tim Peters2344fae2001-01-15 00:50:52 +00001464 sys.exit(2)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001465
Georg Brandle0230912010-07-30 08:29:39 +00001466 commands = []
1467 for opt, optarg in opts:
1468 if opt in ['-h', '--help']:
1469 print(_usage)
1470 sys.exit()
1471 elif opt in ['-c', '--command']:
1472 commands.append(optarg)
1473
1474 mainpyfile = args[0] # Get script filename
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001475 if not os.path.exists(mainpyfile):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001476 print('Error:', mainpyfile, 'does not exist')
Tim Peters2344fae2001-01-15 00:50:52 +00001477 sys.exit(1)
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001478
Georg Brandle0230912010-07-30 08:29:39 +00001479 sys.argv[:] = args # Hide "pdb.py" and pdb options from argument list
Guido van Rossumec577d51996-09-10 17:39:34 +00001480
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001481 # Replace pdb's dir with script's dir in front of module search path.
1482 sys.path[0] = os.path.dirname(mainpyfile)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001483
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001484 # Note on saving/restoring sys.argv: it's a good idea when sys.argv was
1485 # modified by the script being debugged. It's a bad idea when it was
Georg Brandl3078df02009-05-05 09:11:31 +00001486 # changed by the user from the command line. There is a "restart" command
1487 # which allows explicit specification of command line arguments.
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001488 pdb = Pdb()
Georg Brandle0230912010-07-30 08:29:39 +00001489 pdb.rcLines.extend(commands)
Georg Brandl1e30bd32010-07-30 07:21:26 +00001490 while True:
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001491 try:
1492 pdb._runscript(mainpyfile)
1493 if pdb._user_requested_quit:
1494 break
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001495 print("The program finished and will be restarted")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001496 except Restart:
1497 print("Restarting", mainpyfile, "with arguments:")
Georg Brandle0230912010-07-30 08:29:39 +00001498 print("\t" + " ".join(args))
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001499 except SystemExit:
1500 # In most cases SystemExit does not warrant a post-mortem session.
Georg Brandle0230912010-07-30 08:29:39 +00001501 print("The program exited via sys.exit(). Exit status:", end=' ')
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001502 print(sys.exc_info()[1])
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001503 except:
1504 traceback.print_exc()
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001505 print("Uncaught exception. Entering post mortem debugging")
1506 print("Running 'cont' or 'step' will restart the program")
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001507 t = sys.exc_info()[2]
Benjamin Peterson1a6e0d02008-10-25 15:49:17 +00001508 pdb.interaction(None, t)
Georg Brandl3078df02009-05-05 09:11:31 +00001509 print("Post mortem debugger finished. The " + mainpyfile +
1510 " will be restarted")
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001511
1512
1513# When invoked as main program, invoke the debugger on a script
Guido van Rossumd8faa362007-04-27 19:54:29 +00001514if __name__ == '__main__':
1515 import pdb
1516 pdb.main()