blob: 8c7c12b92cbe0e0e79ba506df685e6bdc0a56d4e [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
Georg Brandlcbc79c72010-12-04 16:21:42 +0000128class _rstr(str):
129 """String that doesn't quote its repr."""
130 def __repr__(self):
131 return self
132
133
Guido van Rossuma558e371994-11-10 22:27:35 +0000134# Interaction prompt line will separate file and call info from code
135# text using value of line_prefix string. A newline and arrow may
136# be to your liking. You can set it once pdb is imported using the
137# command "pdb.line_prefix = '\n% '".
Tim Peters2344fae2001-01-15 00:50:52 +0000138# line_prefix = ': ' # Use this to get the old situation back
139line_prefix = '\n-> ' # Probably a better default
Guido van Rossuma558e371994-11-10 22:27:35 +0000140
Guido van Rossum23efba41992-01-27 16:58:47 +0000141class Pdb(bdb.Bdb, cmd.Cmd):
Guido van Rossum2424f851998-09-11 22:50:09 +0000142
Georg Brandl44f2b642010-12-04 16:00:47 +0000143 def __init__(self, completekey='tab', stdin=None, stdout=None, skip=None,
144 nosigint=False):
Georg Brandl243ad662009-05-05 09:00:19 +0000145 bdb.Bdb.__init__(self, skip=skip)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000146 cmd.Cmd.__init__(self, completekey, stdin, stdout)
147 if stdout:
148 self.use_rawinput = 0
Tim Peters2344fae2001-01-15 00:50:52 +0000149 self.prompt = '(Pdb) '
150 self.aliases = {}
Georg Brandlcbc79c72010-12-04 16:21:42 +0000151 self.displaying = {}
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000152 self.mainpyfile = ''
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000153 self._wait_for_mainpyfile = False
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000154 self.tb_lineno = {}
Tim Peters2344fae2001-01-15 00:50:52 +0000155 # Try to load readline if it exists
156 try:
157 import readline
158 except ImportError:
159 pass
Georg Brandl44f2b642010-12-04 16:00:47 +0000160 self.allow_kbdint = False
161 self.nosigint = nosigint
Guido van Rossum2424f851998-09-11 22:50:09 +0000162
Tim Peters2344fae2001-01-15 00:50:52 +0000163 # Read $HOME/.pdbrc and ./.pdbrc
164 self.rcLines = []
Raymond Hettinger54f02222002-06-01 14:18:47 +0000165 if 'HOME' in os.environ:
Tim Peters2344fae2001-01-15 00:50:52 +0000166 envHome = os.environ['HOME']
167 try:
Florent Xicluna7dde7922010-09-03 19:52:03 +0000168 with open(os.path.join(envHome, ".pdbrc")) as rcFile:
169 self.rcLines.extend(rcFile)
Tim Peters2344fae2001-01-15 00:50:52 +0000170 except IOError:
171 pass
Tim Peters2344fae2001-01-15 00:50:52 +0000172 try:
Florent Xicluna7dde7922010-09-03 19:52:03 +0000173 with open(".pdbrc") as rcFile:
174 self.rcLines.extend(rcFile)
Tim Peters2344fae2001-01-15 00:50:52 +0000175 except IOError:
176 pass
Guido van Rossum23efba41992-01-27 16:58:47 +0000177
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000178 self.commands = {} # associates a command list to breakpoint numbers
Benjamin Petersond23f8222009-04-05 19:13:16 +0000179 self.commands_doprompt = {} # for each bp num, tells if the prompt
180 # must be disp. after execing the cmd list
181 self.commands_silent = {} # for each bp num, tells if the stack trace
182 # must be disp. after execing the cmd list
183 self.commands_defining = False # True while in the process of defining
184 # a command list
185 self.commands_bnum = None # The breakpoint number for which we are
186 # defining a list
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000187
Georg Brandl44f2b642010-12-04 16:00:47 +0000188 def sigint_handler(self, signum, frame):
189 if self.allow_kbdint:
190 raise KeyboardInterrupt
191 self.message("\nProgram interrupted. (Use 'cont' to resume).")
192 self.set_step()
193 self.set_trace(frame)
194 # restore previous signal handler
195 signal.signal(signal.SIGINT, self._previous_sigint_handler)
196
Tim Peters2344fae2001-01-15 00:50:52 +0000197 def reset(self):
198 bdb.Bdb.reset(self)
199 self.forget()
Guido van Rossum23efba41992-01-27 16:58:47 +0000200
Tim Peters2344fae2001-01-15 00:50:52 +0000201 def forget(self):
202 self.lineno = None
203 self.stack = []
204 self.curindex = 0
205 self.curframe = None
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000206 self.tb_lineno.clear()
Guido van Rossum2424f851998-09-11 22:50:09 +0000207
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000208 def setup(self, f, tb):
Tim Peters2344fae2001-01-15 00:50:52 +0000209 self.forget()
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000210 self.stack, self.curindex = self.get_stack(f, tb)
211 while tb:
212 # when setting up post-mortem debugging with a traceback, save all
213 # the original line numbers to be displayed along the current line
214 # numbers (which can be different, e.g. due to finally clauses)
215 lineno = lasti2lineno(tb.tb_frame.f_code, tb.tb_lasti)
216 self.tb_lineno[tb.tb_frame] = lineno
217 tb = tb.tb_next
Tim Peters2344fae2001-01-15 00:50:52 +0000218 self.curframe = self.stack[self.curindex][0]
Benjamin Petersond23f8222009-04-05 19:13:16 +0000219 # The f_locals dictionary is updated from the actual frame
220 # locals whenever the .f_locals accessor is called, so we
221 # cache it here to ensure that modifications are not overwritten.
222 self.curframe_locals = self.curframe.f_locals
Georg Brandle0230912010-07-30 08:29:39 +0000223 return self.execRcLines()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000224
Tim Peters2344fae2001-01-15 00:50:52 +0000225 # Can be executed earlier than 'setup' if desired
226 def execRcLines(self):
Georg Brandle0230912010-07-30 08:29:39 +0000227 if not self.rcLines:
228 return
229 # local copy because of recursion
230 rcLines = self.rcLines
231 rcLines.reverse()
232 # execute every line only once
233 self.rcLines = []
234 while rcLines:
235 line = rcLines.pop().strip()
236 if line and line[0] != '#':
237 if self.onecmd(line):
238 # if onecmd returns True, the command wants to exit
239 # from the interaction, save leftover rc lines
240 # to execute before next interaction
241 self.rcLines += reversed(rcLines)
242 return True
Guido van Rossum2424f851998-09-11 22:50:09 +0000243
Tim Peters280488b2002-08-23 18:19:30 +0000244 # Override Bdb methods
Michael W. Hudsondd32a912002-08-15 14:59:02 +0000245
246 def user_call(self, frame, argument_list):
247 """This method is called when there is the remote possibility
248 that we ever need to stop in this function."""
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000249 if self._wait_for_mainpyfile:
250 return
Michael W. Hudson01eb85c2003-01-31 17:48:29 +0000251 if self.stop_here(frame):
Georg Brandl0d089622010-07-30 16:00:46 +0000252 self.message('--Call--')
Michael W. Hudson01eb85c2003-01-31 17:48:29 +0000253 self.interaction(frame, None)
Guido van Rossum2424f851998-09-11 22:50:09 +0000254
Tim Peters2344fae2001-01-15 00:50:52 +0000255 def user_line(self, frame):
256 """This function is called when we stop or break at this line."""
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000257 if self._wait_for_mainpyfile:
258 if (self.mainpyfile != self.canonic(frame.f_code.co_filename)
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000259 or frame.f_lineno <= 0):
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000260 return
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000261 self._wait_for_mainpyfile = False
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000262 if self.bp_commands(frame):
263 self.interaction(frame, None)
264
Georg Brandle0230912010-07-30 08:29:39 +0000265 def bp_commands(self, frame):
Georg Brandl3078df02009-05-05 09:11:31 +0000266 """Call every command that was set for the current active breakpoint
267 (if there is one).
268
269 Returns True if the normal interaction function must be called,
270 False otherwise."""
271 # self.currentbp is set in bdb in Bdb.break_here if a breakpoint was hit
272 if getattr(self, "currentbp", False) and \
273 self.currentbp in self.commands:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000274 currentbp = self.currentbp
275 self.currentbp = 0
276 lastcmd_back = self.lastcmd
277 self.setup(frame, None)
278 for line in self.commands[currentbp]:
279 self.onecmd(line)
280 self.lastcmd = lastcmd_back
281 if not self.commands_silent[currentbp]:
282 self.print_stack_entry(self.stack[self.curindex])
283 if self.commands_doprompt[currentbp]:
Georg Brandl44f2b642010-12-04 16:00:47 +0000284 self._cmdloop()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000285 self.forget()
286 return
287 return 1
Guido van Rossum9e1ee971997-07-11 13:43:53 +0000288
Tim Peters2344fae2001-01-15 00:50:52 +0000289 def user_return(self, frame, return_value):
290 """This function is called when a return trap is set here."""
Georg Brandl34cc0f52010-07-30 09:43:00 +0000291 if self._wait_for_mainpyfile:
292 return
Tim Peters2344fae2001-01-15 00:50:52 +0000293 frame.f_locals['__return__'] = return_value
Georg Brandl0d089622010-07-30 16:00:46 +0000294 self.message('--Return--')
Tim Peters2344fae2001-01-15 00:50:52 +0000295 self.interaction(frame, None)
Guido van Rossum2424f851998-09-11 22:50:09 +0000296
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000297 def user_exception(self, frame, exc_info):
Tim Peters2344fae2001-01-15 00:50:52 +0000298 """This function is called if an exception occurs,
299 but only if we are to stop at or just below this level."""
Georg Brandl34cc0f52010-07-30 09:43:00 +0000300 if self._wait_for_mainpyfile:
301 return
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000302 exc_type, exc_value, exc_traceback = exc_info
Tim Peters2344fae2001-01-15 00:50:52 +0000303 frame.f_locals['__exception__'] = exc_type, exc_value
Georg Brandl0d089622010-07-30 16:00:46 +0000304 self.message(traceback.format_exception_only(exc_type,
305 exc_value)[-1].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000306 self.interaction(frame, exc_traceback)
Guido van Rossum2424f851998-09-11 22:50:09 +0000307
Tim Peters2344fae2001-01-15 00:50:52 +0000308 # General interaction function
Georg Brandl44f2b642010-12-04 16:00:47 +0000309 def _cmdloop(self):
310 while True:
311 try:
312 # keyboard interrupts allow for an easy way to cancel
313 # the current command, so allow them during interactive input
314 self.allow_kbdint = True
315 self.cmdloop()
316 self.allow_kbdint = False
317 break
318 except KeyboardInterrupt:
319 self.message('--KeyboardInterrupt--')
Tim Peters2344fae2001-01-15 00:50:52 +0000320
Georg Brandlcbc79c72010-12-04 16:21:42 +0000321 # Called before loop, handles display expressions
322 def preloop(self):
323 displaying = self.displaying.get(self.curframe)
324 if displaying:
325 for expr, oldvalue in displaying.items():
326 newvalue = self._getval_except(expr)
327 # check for identity first; this prevents custom __eq__ to
328 # be called at every loop, and also prevents instances whose
329 # fields are changed to be displayed
330 if newvalue is not oldvalue and newvalue != oldvalue:
331 displaying[expr] = newvalue
332 self.message('display %s: %r [old: %r]' %
333 (expr, newvalue, oldvalue))
334
Tim Peters2344fae2001-01-15 00:50:52 +0000335 def interaction(self, frame, traceback):
Georg Brandle0230912010-07-30 08:29:39 +0000336 if self.setup(frame, traceback):
337 # no interaction desired at this time (happens if .pdbrc contains
338 # a command like "continue")
339 self.forget()
340 return
Tim Peters2344fae2001-01-15 00:50:52 +0000341 self.print_stack_entry(self.stack[self.curindex])
Georg Brandl44f2b642010-12-04 16:00:47 +0000342 self._cmdloop()
Tim Peters2344fae2001-01-15 00:50:52 +0000343 self.forget()
344
Benjamin Petersond23f8222009-04-05 19:13:16 +0000345 def displayhook(self, obj):
346 """Custom displayhook for the exec in default(), which prevents
347 assignment of the _ variable in the builtins.
348 """
Georg Brandl9fa2e022009-09-16 16:40:45 +0000349 # reproduce the behavior of the standard displayhook, not printing None
350 if obj is not None:
Georg Brandl0d089622010-07-30 16:00:46 +0000351 self.message(repr(obj))
Benjamin Petersond23f8222009-04-05 19:13:16 +0000352
Tim Peters2344fae2001-01-15 00:50:52 +0000353 def default(self, line):
354 if line[:1] == '!': line = line[1:]
Benjamin Petersond23f8222009-04-05 19:13:16 +0000355 locals = self.curframe_locals
Tim Peters2344fae2001-01-15 00:50:52 +0000356 globals = self.curframe.f_globals
357 try:
358 code = compile(line + '\n', '<stdin>', 'single')
Christian Heimes679db4a2008-01-18 09:56:22 +0000359 save_stdout = sys.stdout
360 save_stdin = sys.stdin
Benjamin Petersond23f8222009-04-05 19:13:16 +0000361 save_displayhook = sys.displayhook
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000362 try:
363 sys.stdin = self.stdin
364 sys.stdout = self.stdout
Benjamin Petersond23f8222009-04-05 19:13:16 +0000365 sys.displayhook = self.displayhook
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000366 exec(code, globals, locals)
367 finally:
368 sys.stdout = save_stdout
369 sys.stdin = save_stdin
Benjamin Petersond23f8222009-04-05 19:13:16 +0000370 sys.displayhook = save_displayhook
Tim Peters2344fae2001-01-15 00:50:52 +0000371 except:
Georg Brandl0d089622010-07-30 16:00:46 +0000372 exc_info = sys.exc_info()[:2]
373 self.error(traceback.format_exception_only(*exc_info)[-1].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000374
375 def precmd(self, line):
376 """Handle alias expansion and ';;' separator."""
Guido van Rossum08454592002-07-12 13:10:53 +0000377 if not line.strip():
Tim Peters2344fae2001-01-15 00:50:52 +0000378 return line
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000379 args = line.split()
Raymond Hettinger54f02222002-06-01 14:18:47 +0000380 while args[0] in self.aliases:
Tim Peters2344fae2001-01-15 00:50:52 +0000381 line = self.aliases[args[0]]
382 ii = 1
383 for tmpArg in args[1:]:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000384 line = line.replace("%" + str(ii),
Tim Peters2344fae2001-01-15 00:50:52 +0000385 tmpArg)
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000386 ii += 1
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000387 line = line.replace("%*", ' '.join(args[1:]))
388 args = line.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000389 # split into ';;' separated commands
390 # unless it's an alias command
391 if args[0] != 'alias':
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000392 marker = line.find(';;')
Tim Peters2344fae2001-01-15 00:50:52 +0000393 if marker >= 0:
394 # queue up everything after marker
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000395 next = line[marker+2:].lstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000396 self.cmdqueue.append(next)
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000397 line = line[:marker].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000398 return line
399
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000400 def onecmd(self, line):
401 """Interpret the argument as though it had been typed in response
402 to the prompt.
403
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000404 Checks whether this line is typed at the normal prompt or in
405 a breakpoint command list definition.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000406 """
407 if not self.commands_defining:
408 return cmd.Cmd.onecmd(self, line)
409 else:
410 return self.handle_command_def(line)
411
Georg Brandlb90ffd82010-07-30 22:20:16 +0000412 def handle_command_def(self, line):
Georg Brandl44f8bf92010-07-30 08:54:49 +0000413 """Handles one command line during command list definition."""
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000414 cmd, arg, line = self.parseline(line)
Georg Brandl44f8bf92010-07-30 08:54:49 +0000415 if not cmd:
416 return
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000417 if cmd == 'silent':
418 self.commands_silent[self.commands_bnum] = True
419 return # continue to handle other cmd def in the cmd list
420 elif cmd == 'end':
421 self.cmdqueue = []
422 return 1 # end of cmd list
423 cmdlist = self.commands[self.commands_bnum]
Georg Brandl44f8bf92010-07-30 08:54:49 +0000424 if arg:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000425 cmdlist.append(cmd+' '+arg)
426 else:
427 cmdlist.append(cmd)
428 # Determine if we must stop
429 try:
430 func = getattr(self, 'do_' + cmd)
431 except AttributeError:
432 func = self.default
Georg Brandl3078df02009-05-05 09:11:31 +0000433 # one of the resuming commands
434 if func.__name__ in self.commands_resuming:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000435 self.commands_doprompt[self.commands_bnum] = False
436 self.cmdqueue = []
437 return 1
438 return
439
Georg Brandl0d089622010-07-30 16:00:46 +0000440 # interface abstraction functions
441
442 def message(self, msg):
443 print(msg, file=self.stdout)
444
445 def error(self, msg):
446 print('***', msg, file=self.stdout)
447
Tim Peters2344fae2001-01-15 00:50:52 +0000448 # Command definitions, called by cmdloop()
449 # The argument is the remaining string on the command line
450 # Return true to exit from the command loop
451
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000452 def do_commands(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000453 """commands [bpnumber]
454 (com) ...
455 (com) end
456 (Pdb)
Georg Brandl3078df02009-05-05 09:11:31 +0000457
Georg Brandl0d089622010-07-30 16:00:46 +0000458 Specify a list of commands for breakpoint number bpnumber.
459 The commands themselves are entered on the following lines.
460 Type a line containing just 'end' to terminate the commands.
461 The commands are executed when the breakpoint is hit.
462
463 To remove all commands from a breakpoint, type commands and
464 follow it immediately with end; that is, give no commands.
465
466 With no bpnumber argument, commands refers to the last
467 breakpoint set.
468
469 You can use breakpoint commands to start your program up
470 again. Simply use the continue command, or step, or any other
471 command that resumes execution.
472
473 Specifying any command resuming execution (currently continue,
474 step, next, return, jump, quit and their abbreviations)
475 terminates the command list (as if that command was
476 immediately followed by end). This is because any time you
477 resume execution (even with a simple next or step), you may
478 encounter another breakpoint -- which could have its own
479 command list, leading to ambiguities about which list to
480 execute.
481
482 If you use the 'silent' command in the command list, the usual
483 message about stopping at a breakpoint is not printed. This
484 may be desirable for breakpoints that are to print a specific
485 message and then continue. If none of the other commands
486 print anything, you will see no sign that the breakpoint was
487 reached.
488 """
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000489 if not arg:
Georg Brandl7410dd12010-07-30 12:01:20 +0000490 bnum = len(bdb.Breakpoint.bpbynumber) - 1
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000491 else:
492 try:
493 bnum = int(arg)
494 except:
Georg Brandl0d089622010-07-30 16:00:46 +0000495 self.error("Usage: commands [bnum]\n ...\n end")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000496 return
497 self.commands_bnum = bnum
Georg Brandlb90ffd82010-07-30 22:20:16 +0000498 # Save old definitions for the case of a keyboard interrupt.
499 if bnum in self.commands:
500 old_command_defs = (self.commands[bnum],
501 self.commands_doprompt[bnum],
502 self.commands_silent[bnum])
503 else:
504 old_command_defs = None
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000505 self.commands[bnum] = []
506 self.commands_doprompt[bnum] = True
507 self.commands_silent[bnum] = False
Georg Brandlb90ffd82010-07-30 22:20:16 +0000508
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000509 prompt_back = self.prompt
510 self.prompt = '(com) '
511 self.commands_defining = True
Georg Brandl44f8bf92010-07-30 08:54:49 +0000512 try:
513 self.cmdloop()
Georg Brandlb90ffd82010-07-30 22:20:16 +0000514 except KeyboardInterrupt:
515 # Restore old definitions.
516 if old_command_defs:
517 self.commands[bnum] = old_command_defs[0]
518 self.commands_doprompt[bnum] = old_command_defs[1]
519 self.commands_silent[bnum] = old_command_defs[2]
520 else:
521 del self.commands[bnum]
522 del self.commands_doprompt[bnum]
523 del self.commands_silent[bnum]
524 self.error('command definition aborted, old commands restored')
Georg Brandl44f8bf92010-07-30 08:54:49 +0000525 finally:
526 self.commands_defining = False
527 self.prompt = prompt_back
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000528
Tim Peters2344fae2001-01-15 00:50:52 +0000529 def do_break(self, arg, temporary = 0):
Georg Brandl0d089622010-07-30 16:00:46 +0000530 """b(reak) [ ([filename:]lineno | function) [, condition] ]
531 Without argument, list all breaks.
532
533 With a line number argument, set a break at this line in the
534 current file. With a function name, set a break at the first
535 executable line of that function. If a second argument is
536 present, it is a string specifying an expression which must
537 evaluate to true before the breakpoint is honored.
538
539 The line number may be prefixed with a filename and a colon,
540 to specify a breakpoint in another file (probably one that
541 hasn't been loaded yet). The file is searched for on
542 sys.path; the .py suffix may be omitted.
543 """
Tim Peters2344fae2001-01-15 00:50:52 +0000544 if not arg:
545 if self.breaks: # There's at least one
Georg Brandl0d089622010-07-30 16:00:46 +0000546 self.message("Num Type Disp Enb Where")
Tim Peters2344fae2001-01-15 00:50:52 +0000547 for bp in bdb.Breakpoint.bpbynumber:
548 if bp:
Georg Brandl0d089622010-07-30 16:00:46 +0000549 self.message(bp.bpformat())
Tim Peters2344fae2001-01-15 00:50:52 +0000550 return
551 # parse arguments; comma has lowest precedence
552 # and cannot occur in filename
553 filename = None
554 lineno = None
555 cond = None
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000556 comma = arg.find(',')
Tim Peters2344fae2001-01-15 00:50:52 +0000557 if comma > 0:
558 # parse stuff after comma: "condition"
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000559 cond = arg[comma+1:].lstrip()
560 arg = arg[:comma].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000561 # parse stuff before comma: [filename:]lineno | function
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000562 colon = arg.rfind(':')
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000563 funcname = None
Tim Peters2344fae2001-01-15 00:50:52 +0000564 if colon >= 0:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000565 filename = arg[:colon].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000566 f = self.lookupmodule(filename)
567 if not f:
Georg Brandl0d089622010-07-30 16:00:46 +0000568 self.error('%r not found from sys.path' % filename)
Tim Peters2344fae2001-01-15 00:50:52 +0000569 return
570 else:
571 filename = f
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000572 arg = arg[colon+1:].lstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000573 try:
574 lineno = int(arg)
Georg Brandlf93390a2010-10-14 07:17:44 +0000575 except ValueError:
Georg Brandl0d089622010-07-30 16:00:46 +0000576 self.error('Bad lineno: %s' % arg)
Tim Peters2344fae2001-01-15 00:50:52 +0000577 return
578 else:
579 # no colon; can be lineno or function
580 try:
581 lineno = int(arg)
582 except ValueError:
583 try:
584 func = eval(arg,
585 self.curframe.f_globals,
Benjamin Petersond23f8222009-04-05 19:13:16 +0000586 self.curframe_locals)
Tim Peters2344fae2001-01-15 00:50:52 +0000587 except:
588 func = arg
589 try:
Christian Heimesff737952007-11-27 10:40:20 +0000590 if hasattr(func, '__func__'):
591 func = func.__func__
Neal Norwitz221085d2007-02-25 20:55:47 +0000592 code = func.__code__
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000593 #use co_name to identify the bkpt (function names
594 #could be aliased, but co_name is invariant)
595 funcname = code.co_name
Tim Peters2344fae2001-01-15 00:50:52 +0000596 lineno = code.co_firstlineno
597 filename = code.co_filename
598 except:
599 # last thing to try
600 (ok, filename, ln) = self.lineinfo(arg)
601 if not ok:
Georg Brandl0d089622010-07-30 16:00:46 +0000602 self.error('The specified object %r is not a function '
603 'or was not found along sys.path.' % arg)
Tim Peters2344fae2001-01-15 00:50:52 +0000604 return
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000605 funcname = ok # ok contains a function name
Tim Peters2344fae2001-01-15 00:50:52 +0000606 lineno = int(ln)
607 if not filename:
608 filename = self.defaultFile()
609 # Check for reasonable breakpoint
610 line = self.checkline(filename, lineno)
611 if line:
612 # now set the break point
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000613 err = self.set_break(filename, line, temporary, cond, funcname)
Georg Brandl0d089622010-07-30 16:00:46 +0000614 if err:
615 self.error(err, file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000616 else:
617 bp = self.get_breaks(filename, line)[-1]
Georg Brandl0d089622010-07-30 16:00:46 +0000618 self.message("Breakpoint %d at %s:%d" %
619 (bp.number, bp.file, bp.line))
Tim Peters2344fae2001-01-15 00:50:52 +0000620
621 # To be overridden in derived debuggers
622 def defaultFile(self):
623 """Produce a reasonable default."""
624 filename = self.curframe.f_code.co_filename
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000625 if filename == '<string>' and self.mainpyfile:
626 filename = self.mainpyfile
Tim Peters2344fae2001-01-15 00:50:52 +0000627 return filename
628
629 do_b = do_break
630
631 def do_tbreak(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000632 """tbreak [ ([filename:]lineno | function) [, condition] ]
633 Same arguments as break, but sets a temporary breakpoint: it
634 is automatically deleted when first hit.
635 """
Tim Peters2344fae2001-01-15 00:50:52 +0000636 self.do_break(arg, 1)
637
638 def lineinfo(self, identifier):
639 failed = (None, None, None)
640 # Input is identifier, may be in single quotes
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000641 idstring = identifier.split("'")
Tim Peters2344fae2001-01-15 00:50:52 +0000642 if len(idstring) == 1:
643 # not in single quotes
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000644 id = idstring[0].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000645 elif len(idstring) == 3:
646 # quoted
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000647 id = idstring[1].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000648 else:
649 return failed
650 if id == '': return failed
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000651 parts = id.split('.')
Tim Peters2344fae2001-01-15 00:50:52 +0000652 # Protection for derived debuggers
653 if parts[0] == 'self':
654 del parts[0]
655 if len(parts) == 0:
656 return failed
657 # Best first guess at file to look at
658 fname = self.defaultFile()
659 if len(parts) == 1:
660 item = parts[0]
661 else:
662 # More than one part.
663 # First is module, second is method/class
664 f = self.lookupmodule(parts[0])
665 if f:
666 fname = f
667 item = parts[1]
668 answer = find_function(item, fname)
669 return answer or failed
670
671 def checkline(self, filename, lineno):
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000672 """Check whether specified line seems to be executable.
Tim Peters2344fae2001-01-15 00:50:52 +0000673
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000674 Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
675 line or EOF). Warning: testing is not comprehensive.
676 """
Georg Brandl1e30bd32010-07-30 07:21:26 +0000677 # this method should be callable before starting debugging, so default
678 # to "no globals" if there is no current frame
679 globs = self.curframe.f_globals if hasattr(self, 'curframe') else None
680 line = linecache.getline(filename, lineno, globs)
Tim Peters2344fae2001-01-15 00:50:52 +0000681 if not line:
Georg Brandl0d089622010-07-30 16:00:46 +0000682 self.message('End of file')
Tim Peters2344fae2001-01-15 00:50:52 +0000683 return 0
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000684 line = line.strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000685 # Don't allow setting breakpoint at a blank line
Guido van Rossum08454592002-07-12 13:10:53 +0000686 if (not line or (line[0] == '#') or
687 (line[:3] == '"""') or line[:3] == "'''"):
Georg Brandl0d089622010-07-30 16:00:46 +0000688 self.error('Blank or comment')
Tim Peters2344fae2001-01-15 00:50:52 +0000689 return 0
Tim Peters2344fae2001-01-15 00:50:52 +0000690 return lineno
691
692 def do_enable(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000693 """enable bpnumber [bpnumber ...]
694 Enables the breakpoints given as a space separated list of
695 breakpoint numbers.
696 """
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000697 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000698 for i in args:
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000699 try:
Georg Brandl7410dd12010-07-30 12:01:20 +0000700 bp = self.get_bpbynumber(i)
701 except ValueError as err:
Georg Brandl0d089622010-07-30 16:00:46 +0000702 self.error(err)
Georg Brandl7410dd12010-07-30 12:01:20 +0000703 else:
Tim Peters2344fae2001-01-15 00:50:52 +0000704 bp.enable()
Georg Brandl0d089622010-07-30 16:00:46 +0000705 self.message('Enabled %s' % bp)
Tim Peters2344fae2001-01-15 00:50:52 +0000706
707 def do_disable(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000708 """disable bpnumber [bpnumber ...]
709 Disables the breakpoints given as a space separated list of
710 breakpoint numbers. Disabling a breakpoint means it cannot
711 cause the program to stop execution, but unlike clearing a
712 breakpoint, it remains in the list of breakpoints and can be
713 (re-)enabled.
714 """
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000715 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000716 for i in args:
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000717 try:
Georg Brandl7410dd12010-07-30 12:01:20 +0000718 bp = self.get_bpbynumber(i)
719 except ValueError as err:
Georg Brandl0d089622010-07-30 16:00:46 +0000720 self.error(err)
Georg Brandl7410dd12010-07-30 12:01:20 +0000721 else:
Tim Peters2344fae2001-01-15 00:50:52 +0000722 bp.disable()
Georg Brandl0d089622010-07-30 16:00:46 +0000723 self.message('Disabled %s' % bp)
Tim Peters2344fae2001-01-15 00:50:52 +0000724
725 def do_condition(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000726 """condition bpnumber [condition]
727 Set a new condition for the breakpoint, an expression which
728 must evaluate to true before the breakpoint is honored. If
729 condition is absent, any existing condition is removed; i.e.,
730 the breakpoint is made unconditional.
731 """
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000732 args = arg.split(' ', 1)
Thomas Woutersb2137042007-02-01 18:02:27 +0000733 try:
Tim Peters2344fae2001-01-15 00:50:52 +0000734 cond = args[1]
Georg Brandl7410dd12010-07-30 12:01:20 +0000735 except IndexError:
Tim Peters2344fae2001-01-15 00:50:52 +0000736 cond = None
Guido van Rossumd8faa362007-04-27 19:54:29 +0000737 try:
Georg Brandl7410dd12010-07-30 12:01:20 +0000738 bp = self.get_bpbynumber(args[0].strip())
739 except ValueError as err:
Georg Brandl0d089622010-07-30 16:00:46 +0000740 self.error(err)
Georg Brandl7410dd12010-07-30 12:01:20 +0000741 else:
Tim Peters2344fae2001-01-15 00:50:52 +0000742 bp.cond = cond
743 if not cond:
Georg Brandl0d089622010-07-30 16:00:46 +0000744 self.message('Breakpoint %d is now unconditional.' % bp.number)
Georg Brandl7410dd12010-07-30 12:01:20 +0000745 else:
Georg Brandl0d089622010-07-30 16:00:46 +0000746 self.message('New condition set for breakpoint %d.' % bp.number)
Tim Peters2344fae2001-01-15 00:50:52 +0000747
Georg Brandl7410dd12010-07-30 12:01:20 +0000748 def do_ignore(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000749 """ignore bpnumber [count]
750 Set the ignore count for the given breakpoint number. If
751 count is omitted, the ignore count is set to 0. A breakpoint
752 becomes active when the ignore count is zero. When non-zero,
753 the count is decremented each time the breakpoint is reached
754 and the breakpoint is not disabled and any associated
755 condition evaluates to true.
756 """
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000757 args = arg.split()
Thomas Woutersb2137042007-02-01 18:02:27 +0000758 try:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000759 count = int(args[1].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000760 except:
761 count = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +0000762 try:
Georg Brandl7410dd12010-07-30 12:01:20 +0000763 bp = self.get_bpbynumber(args[0].strip())
764 except ValueError as err:
Georg Brandl0d089622010-07-30 16:00:46 +0000765 self.error(err)
Georg Brandl7410dd12010-07-30 12:01:20 +0000766 else:
Tim Peters2344fae2001-01-15 00:50:52 +0000767 bp.ignore = count
Guido van Rossum08454592002-07-12 13:10:53 +0000768 if count > 0:
Guido van Rossum08454592002-07-12 13:10:53 +0000769 if count > 1:
Georg Brandl0d089622010-07-30 16:00:46 +0000770 countstr = '%d crossings' % count
Tim Peters2344fae2001-01-15 00:50:52 +0000771 else:
Georg Brandl0d089622010-07-30 16:00:46 +0000772 countstr = '1 crossing'
773 self.message('Will ignore next %s of breakpoint %d.' %
774 (countstr, bp.number))
Tim Peters2344fae2001-01-15 00:50:52 +0000775 else:
Georg Brandl0d089622010-07-30 16:00:46 +0000776 self.message('Will stop next time breakpoint %d is reached.'
777 % bp.number)
Tim Peters2344fae2001-01-15 00:50:52 +0000778
779 def do_clear(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000780 """cl(ear) filename:lineno\ncl(ear) [bpnumber [bpnumber...]]
781 With a space separated list of breakpoint numbers, clear
782 those breakpoints. Without argument, clear all breaks (but
783 first ask confirmation). With a filename:lineno argument,
784 clear all breaks at that line in that file.
785 """
Tim Peters2344fae2001-01-15 00:50:52 +0000786 if not arg:
787 try:
Guido van Rossumc5b6ab02007-05-27 09:19:52 +0000788 reply = input('Clear all breaks? ')
Tim Peters2344fae2001-01-15 00:50:52 +0000789 except EOFError:
790 reply = 'no'
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000791 reply = reply.strip().lower()
Tim Peters2344fae2001-01-15 00:50:52 +0000792 if reply in ('y', 'yes'):
Georg Brandl7410dd12010-07-30 12:01:20 +0000793 bplist = [bp for bp in bdb.Breakpoint.bpbynumber if bp]
Tim Peters2344fae2001-01-15 00:50:52 +0000794 self.clear_all_breaks()
Georg Brandl7410dd12010-07-30 12:01:20 +0000795 for bp in bplist:
Georg Brandl0d089622010-07-30 16:00:46 +0000796 self.message('Deleted %s' % bp)
Tim Peters2344fae2001-01-15 00:50:52 +0000797 return
798 if ':' in arg:
799 # Make sure it works for "clear C:\foo\bar.py:12"
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000800 i = arg.rfind(':')
Tim Peters2344fae2001-01-15 00:50:52 +0000801 filename = arg[:i]
802 arg = arg[i+1:]
803 try:
804 lineno = int(arg)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000805 except ValueError:
Tim Peters2344fae2001-01-15 00:50:52 +0000806 err = "Invalid line number (%s)" % arg
807 else:
Georg Brandl7410dd12010-07-30 12:01:20 +0000808 bplist = self.get_breaks(filename, lineno)
Tim Peters2344fae2001-01-15 00:50:52 +0000809 err = self.clear_break(filename, lineno)
Georg Brandl7410dd12010-07-30 12:01:20 +0000810 if err:
Georg Brandl0d089622010-07-30 16:00:46 +0000811 self.error(err)
Georg Brandl7410dd12010-07-30 12:01:20 +0000812 else:
813 for bp in bplist:
Georg Brandl0d089622010-07-30 16:00:46 +0000814 self.message('Deleted %s' % bp)
Tim Peters2344fae2001-01-15 00:50:52 +0000815 return
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000816 numberlist = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000817 for i in numberlist:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000818 try:
Georg Brandl7410dd12010-07-30 12:01:20 +0000819 bp = self.get_bpbynumber(i)
820 except ValueError as err:
Georg Brandl0d089622010-07-30 16:00:46 +0000821 self.error(err)
Tim Peters2344fae2001-01-15 00:50:52 +0000822 else:
Senthil Kumaran6f107042010-11-29 11:54:17 +0000823 self.clear_bpbynumber(i)
Georg Brandl0d089622010-07-30 16:00:46 +0000824 self.message('Deleted %s' % bp)
Tim Peters2344fae2001-01-15 00:50:52 +0000825 do_cl = do_clear # 'c' is already an abbreviation for 'continue'
826
827 def do_where(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000828 """w(here)
829 Print a stack trace, with the most recent frame at the bottom.
830 An arrow indicates the "current frame", which determines the
831 context of most commands. 'bt' is an alias for this command.
832 """
Tim Peters2344fae2001-01-15 00:50:52 +0000833 self.print_stack_trace()
834 do_w = do_where
Guido van Rossum6bd68352001-01-20 17:57:37 +0000835 do_bt = do_where
Tim Peters2344fae2001-01-15 00:50:52 +0000836
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000837 def _select_frame(self, number):
838 assert 0 <= number < len(self.stack)
839 self.curindex = number
840 self.curframe = self.stack[self.curindex][0]
841 self.curframe_locals = self.curframe.f_locals
842 self.print_stack_entry(self.stack[self.curindex])
843 self.lineno = None
844
Tim Peters2344fae2001-01-15 00:50:52 +0000845 def do_up(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000846 """u(p) [count]
847 Move the current frame count (default one) levels up in the
848 stack trace (to an older frame).
849 """
Tim Peters2344fae2001-01-15 00:50:52 +0000850 if self.curindex == 0:
Georg Brandl0d089622010-07-30 16:00:46 +0000851 self.error('Oldest frame')
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000852 return
853 try:
854 count = int(arg or 1)
855 except ValueError:
Georg Brandl0d089622010-07-30 16:00:46 +0000856 self.error('Invalid frame count (%s)' % arg)
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000857 return
858 if count < 0:
859 newframe = 0
Tim Peters2344fae2001-01-15 00:50:52 +0000860 else:
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000861 newframe = max(0, self.curindex - count)
862 self._select_frame(newframe)
Tim Peters2344fae2001-01-15 00:50:52 +0000863 do_u = do_up
864
865 def do_down(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000866 """d(own) [count]
867 Move the current frame count (default one) levels down in the
868 stack trace (to a newer frame).
869 """
Tim Peters2344fae2001-01-15 00:50:52 +0000870 if self.curindex + 1 == len(self.stack):
Georg Brandl0d089622010-07-30 16:00:46 +0000871 self.error('Newest frame')
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000872 return
873 try:
874 count = int(arg or 1)
875 except ValueError:
Georg Brandl0d089622010-07-30 16:00:46 +0000876 self.error('Invalid frame count (%s)' % arg)
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000877 return
878 if count < 0:
879 newframe = len(self.stack) - 1
Tim Peters2344fae2001-01-15 00:50:52 +0000880 else:
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000881 newframe = min(len(self.stack) - 1, self.curindex + count)
882 self._select_frame(newframe)
Tim Peters2344fae2001-01-15 00:50:52 +0000883 do_d = do_down
884
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000885 def do_until(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000886 """unt(il) [lineno]
887 Without argument, continue execution until the line with a
888 number greater than the current one is reached. With a line
889 number, continue execution until a line with a number greater
890 or equal to that is reached. In both cases, also stop when
891 the current frame returns.
892 """
Georg Brandl2dfec552010-07-30 08:43:32 +0000893 if arg:
894 try:
895 lineno = int(arg)
896 except ValueError:
Georg Brandl0d089622010-07-30 16:00:46 +0000897 self.error('Error in argument: %r' % arg)
Georg Brandl2dfec552010-07-30 08:43:32 +0000898 return
899 if lineno <= self.curframe.f_lineno:
Georg Brandl0d089622010-07-30 16:00:46 +0000900 self.error('"until" line number is smaller than current '
901 'line number')
Georg Brandl2dfec552010-07-30 08:43:32 +0000902 return
903 else:
904 lineno = None
905 self.set_until(self.curframe, lineno)
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000906 return 1
907 do_unt = do_until
908
Tim Peters2344fae2001-01-15 00:50:52 +0000909 def do_step(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000910 """s(tep)
911 Execute the current line, stop at the first possible occasion
912 (either in a function that is called or in the current
913 function).
914 """
Tim Peters2344fae2001-01-15 00:50:52 +0000915 self.set_step()
916 return 1
917 do_s = do_step
918
919 def do_next(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000920 """n(ext)
921 Continue execution until the next line in the current function
922 is reached or it returns.
923 """
Tim Peters2344fae2001-01-15 00:50:52 +0000924 self.set_next(self.curframe)
925 return 1
926 do_n = do_next
927
Guido van Rossumd8faa362007-04-27 19:54:29 +0000928 def do_run(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000929 """run [args...]
930 Restart the debugged python program. If a string is supplied
931 it is splitted with "shlex", and the result is used as the new
932 sys.argv. History, breakpoints, actions and debugger options
933 are preserved. "restart" is an alias for "run".
934 """
Guido van Rossumd8faa362007-04-27 19:54:29 +0000935 if arg:
936 import shlex
937 argv0 = sys.argv[0:1]
938 sys.argv = shlex.split(arg)
939 sys.argv[:0] = argv0
Georg Brandl0d089622010-07-30 16:00:46 +0000940 # this is caught in the main debugger loop
Guido van Rossumd8faa362007-04-27 19:54:29 +0000941 raise Restart
942
943 do_restart = do_run
944
Tim Peters2344fae2001-01-15 00:50:52 +0000945 def do_return(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000946 """r(eturn)
947 Continue execution until the current function returns.
948 """
Tim Peters2344fae2001-01-15 00:50:52 +0000949 self.set_return(self.curframe)
950 return 1
951 do_r = do_return
952
953 def do_continue(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000954 """c(ont(inue))
955 Continue execution, only stop when a breakpoint is encountered.
956 """
Georg Brandl44f2b642010-12-04 16:00:47 +0000957 if not self.nosigint:
Andrew Svetlov539ee5d2012-12-04 21:08:28 +0200958 try:
959 self._previous_sigint_handler = \
960 signal.signal(signal.SIGINT, self.sigint_handler)
961 except ValueError:
962 # ValueError happens when do_continue() is invoked from
963 # a non-main thread in which case we just continue without
964 # SIGINT set. Would printing a message here (once) make
965 # sense?
966 pass
Tim Peters2344fae2001-01-15 00:50:52 +0000967 self.set_continue()
968 return 1
969 do_c = do_cont = do_continue
970
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000971 def do_jump(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000972 """j(ump) lineno
973 Set the next line that will be executed. Only available in
974 the bottom-most frame. This lets you jump back and execute
975 code again, or jump forward to skip code that you don't want
976 to run.
977
978 It should be noted that not all jumps are allowed -- for
979 instance it is not possible to jump into the middle of a
980 for loop or out of a finally clause.
981 """
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000982 if self.curindex + 1 != len(self.stack):
Georg Brandl0d089622010-07-30 16:00:46 +0000983 self.error('You can only jump within the bottom frame')
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000984 return
985 try:
986 arg = int(arg)
987 except ValueError:
Georg Brandl0d089622010-07-30 16:00:46 +0000988 self.error("The 'jump' command requires a line number")
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000989 else:
990 try:
991 # Do the jump, fix up our copy of the stack, and display the
992 # new position
993 self.curframe.f_lineno = arg
994 self.stack[self.curindex] = self.stack[self.curindex][0], arg
995 self.print_stack_entry(self.stack[self.curindex])
Guido van Rossumb940e112007-01-10 16:19:56 +0000996 except ValueError as e:
Georg Brandl0d089622010-07-30 16:00:46 +0000997 self.error('Jump failed: %s' % e)
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000998 do_j = do_jump
999
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001000 def do_debug(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001001 """debug code
1002 Enter a recursive debugger that steps through the code
1003 argument (which is an arbitrary expression or statement to be
1004 executed in the current environment).
1005 """
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001006 sys.settrace(None)
1007 globals = self.curframe.f_globals
Benjamin Petersond23f8222009-04-05 19:13:16 +00001008 locals = self.curframe_locals
Guido van Rossum7736b5b2008-01-15 21:44:53 +00001009 p = Pdb(self.completekey, self.stdin, self.stdout)
Guido van Rossumed538d82003-04-09 19:36:34 +00001010 p.prompt = "(%s) " % self.prompt.strip()
Georg Brandl0d089622010-07-30 16:00:46 +00001011 self.message("ENTERING RECURSIVE DEBUGGER")
Guido van Rossumed538d82003-04-09 19:36:34 +00001012 sys.call_tracing(p.run, (arg, globals, locals))
Georg Brandl0d089622010-07-30 16:00:46 +00001013 self.message("LEAVING RECURSIVE DEBUGGER")
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001014 sys.settrace(self.trace_dispatch)
1015 self.lastcmd = p.lastcmd
1016
Tim Peters2344fae2001-01-15 00:50:52 +00001017 def do_quit(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001018 """q(uit)\nexit
1019 Quit from the debugger. The program being executed is aborted.
1020 """
Georg Brandlac9a2bb2010-11-29 20:19:15 +00001021 self._user_requested_quit = True
Tim Peters2344fae2001-01-15 00:50:52 +00001022 self.set_quit()
1023 return 1
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001024
Tim Peters2344fae2001-01-15 00:50:52 +00001025 do_q = do_quit
Guido van Rossumd1c08f32002-04-15 00:48:24 +00001026 do_exit = do_quit
Tim Peters2344fae2001-01-15 00:50:52 +00001027
Guido van Rossumeef26072003-01-13 21:13:55 +00001028 def do_EOF(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001029 """EOF
1030 Handles the receipt of EOF as a command.
1031 """
1032 self.message('')
Georg Brandlac9a2bb2010-11-29 20:19:15 +00001033 self._user_requested_quit = True
Guido van Rossumeef26072003-01-13 21:13:55 +00001034 self.set_quit()
1035 return 1
1036
Tim Peters2344fae2001-01-15 00:50:52 +00001037 def do_args(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001038 """a(rgs)
1039 Print the argument list of the current function.
1040 """
Benjamin Petersond23f8222009-04-05 19:13:16 +00001041 co = self.curframe.f_code
1042 dict = self.curframe_locals
Tim Peters2344fae2001-01-15 00:50:52 +00001043 n = co.co_argcount
1044 if co.co_flags & 4: n = n+1
1045 if co.co_flags & 8: n = n+1
1046 for i in range(n):
1047 name = co.co_varnames[i]
Georg Brandl0d089622010-07-30 16:00:46 +00001048 if name in dict:
1049 self.message('%s = %r' % (name, dict[name]))
1050 else:
1051 self.message('%s = *** undefined ***' % (name,))
Tim Peters2344fae2001-01-15 00:50:52 +00001052 do_a = do_args
Guido van Rossum2424f851998-09-11 22:50:09 +00001053
Tim Peters2344fae2001-01-15 00:50:52 +00001054 def do_retval(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001055 """retval
1056 Print the return value for the last return of a function.
1057 """
Benjamin Petersond23f8222009-04-05 19:13:16 +00001058 if '__return__' in self.curframe_locals:
Georg Brandl0d089622010-07-30 16:00:46 +00001059 self.message(repr(self.curframe_locals['__return__']))
Tim Peters2344fae2001-01-15 00:50:52 +00001060 else:
Georg Brandl0d089622010-07-30 16:00:46 +00001061 self.error('Not yet returned!')
Tim Peters2344fae2001-01-15 00:50:52 +00001062 do_rv = do_retval
Guido van Rossum2424f851998-09-11 22:50:09 +00001063
Barry Warsaw210bd202002-11-05 22:40:20 +00001064 def _getval(self, arg):
Tim Peters2344fae2001-01-15 00:50:52 +00001065 try:
Benjamin Petersond23f8222009-04-05 19:13:16 +00001066 return eval(arg, self.curframe.f_globals, self.curframe_locals)
Tim Peters2344fae2001-01-15 00:50:52 +00001067 except:
Georg Brandl0d089622010-07-30 16:00:46 +00001068 exc_info = sys.exc_info()[:2]
1069 self.error(traceback.format_exception_only(*exc_info)[-1].strip())
Barry Warsaw210bd202002-11-05 22:40:20 +00001070 raise
Guido van Rossum2424f851998-09-11 22:50:09 +00001071
Georg Brandlcbc79c72010-12-04 16:21:42 +00001072 def _getval_except(self, arg, frame=None):
1073 try:
1074 if frame is None:
1075 return eval(arg, self.curframe.f_globals, self.curframe_locals)
1076 else:
1077 return eval(arg, frame.f_globals, frame.f_locals)
1078 except:
1079 exc_info = sys.exc_info()[:2]
1080 err = traceback.format_exception_only(*exc_info)[-1].strip()
1081 return _rstr('** raised %s **' % err)
1082
Barry Warsaw210bd202002-11-05 22:40:20 +00001083 def do_p(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001084 """p(rint) expression
1085 Print the value of the expression.
1086 """
Barry Warsaw210bd202002-11-05 22:40:20 +00001087 try:
Georg Brandl0d089622010-07-30 16:00:46 +00001088 self.message(repr(self._getval(arg)))
Barry Warsaw210bd202002-11-05 22:40:20 +00001089 except:
1090 pass
Georg Brandlc9879242007-09-04 07:07:56 +00001091 # make "print" an alias of "p" since print isn't a Python statement anymore
1092 do_print = do_p
Barry Warsaw210bd202002-11-05 22:40:20 +00001093
1094 def do_pp(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001095 """pp expression
1096 Pretty-print the value of the expression.
1097 """
Barry Warsaw210bd202002-11-05 22:40:20 +00001098 try:
Georg Brandl0d089622010-07-30 16:00:46 +00001099 self.message(pprint.pformat(self._getval(arg)))
Barry Warsaw210bd202002-11-05 22:40:20 +00001100 except:
1101 pass
Guido van Rossum2424f851998-09-11 22:50:09 +00001102
Tim Peters2344fae2001-01-15 00:50:52 +00001103 def do_list(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001104 """l(ist) [first [,last] | .]
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001105
1106 List source code for the current file. Without arguments,
1107 list 11 lines around the current line or continue the previous
1108 listing. With . as argument, list 11 lines around the current
1109 line. With one argument, list 11 lines starting at that line.
1110 With two arguments, list the given range; if the second
1111 argument is less than the first, it is a count.
1112
1113 The current line in the current frame is indicated by "->".
1114 If an exception is being debugged, the line where the
1115 exception was originally raised or propagated is indicated by
1116 ">>", if it differs from the current line.
Georg Brandl0d089622010-07-30 16:00:46 +00001117 """
Tim Peters2344fae2001-01-15 00:50:52 +00001118 self.lastcmd = 'list'
1119 last = None
Georg Brandla91a94b2010-07-30 07:14:01 +00001120 if arg and arg != '.':
Tim Peters2344fae2001-01-15 00:50:52 +00001121 try:
Georg Brandl0d089622010-07-30 16:00:46 +00001122 if ',' in arg:
1123 first, last = arg.split(',')
1124 first = int(first.strip())
1125 last = int(last.strip())
Tim Peters2344fae2001-01-15 00:50:52 +00001126 if last < first:
Georg Brandl0d089622010-07-30 16:00:46 +00001127 # assume it's a count
Tim Peters2344fae2001-01-15 00:50:52 +00001128 last = first + last
1129 else:
Georg Brandl0d089622010-07-30 16:00:46 +00001130 first = int(arg.strip())
1131 first = max(1, first - 5)
1132 except ValueError:
1133 self.error('Error in argument: %r' % arg)
Tim Peters2344fae2001-01-15 00:50:52 +00001134 return
Georg Brandla91a94b2010-07-30 07:14:01 +00001135 elif self.lineno is None or arg == '.':
Tim Peters2344fae2001-01-15 00:50:52 +00001136 first = max(1, self.curframe.f_lineno - 5)
1137 else:
1138 first = self.lineno + 1
1139 if last is None:
1140 last = first + 10
1141 filename = self.curframe.f_code.co_filename
1142 breaklist = self.get_file_breaks(filename)
1143 try:
Georg Brandle59ca2a2010-07-30 17:04:28 +00001144 lines = linecache.getlines(filename, self.curframe.f_globals)
1145 self._print_lines(lines[first-1:last], first, breaklist,
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001146 self.curframe)
Georg Brandle59ca2a2010-07-30 17:04:28 +00001147 self.lineno = min(last, len(lines))
1148 if len(lines) < last:
1149 self.message('[EOF]')
Tim Peters2344fae2001-01-15 00:50:52 +00001150 except KeyboardInterrupt:
1151 pass
1152 do_l = do_list
Guido van Rossum2424f851998-09-11 22:50:09 +00001153
Georg Brandle59ca2a2010-07-30 17:04:28 +00001154 def do_longlist(self, arg):
1155 """longlist | ll
1156 List the whole source code for the current function or frame.
1157 """
1158 filename = self.curframe.f_code.co_filename
1159 breaklist = self.get_file_breaks(filename)
1160 try:
Georg Brandl5ed2b5a2010-07-30 18:08:12 +00001161 lines, lineno = getsourcelines(self.curframe)
Georg Brandle59ca2a2010-07-30 17:04:28 +00001162 except IOError as err:
1163 self.error(err)
1164 return
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001165 self._print_lines(lines, lineno, breaklist, self.curframe)
Georg Brandle59ca2a2010-07-30 17:04:28 +00001166 do_ll = do_longlist
1167
1168 def do_source(self, arg):
1169 """source expression
1170 Try to get source code for the given object and display it.
1171 """
1172 try:
1173 obj = self._getval(arg)
1174 except:
1175 return
1176 try:
Georg Brandl5ed2b5a2010-07-30 18:08:12 +00001177 lines, lineno = getsourcelines(obj)
Georg Brandle59ca2a2010-07-30 17:04:28 +00001178 except (IOError, TypeError) as err:
1179 self.error(err)
1180 return
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001181 self._print_lines(lines, lineno)
Georg Brandle59ca2a2010-07-30 17:04:28 +00001182
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001183 def _print_lines(self, lines, start, breaks=(), frame=None):
Georg Brandle59ca2a2010-07-30 17:04:28 +00001184 """Print a range of lines."""
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001185 if frame:
1186 current_lineno = frame.f_lineno
1187 exc_lineno = self.tb_lineno.get(frame, -1)
1188 else:
1189 current_lineno = exc_lineno = -1
Georg Brandle59ca2a2010-07-30 17:04:28 +00001190 for lineno, line in enumerate(lines, start):
1191 s = str(lineno).rjust(3)
1192 if len(s) < 4:
1193 s += ' '
1194 if lineno in breaks:
1195 s += 'B'
1196 else:
1197 s += ' '
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001198 if lineno == current_lineno:
Georg Brandle59ca2a2010-07-30 17:04:28 +00001199 s += '->'
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001200 elif lineno == exc_lineno:
Georg Brandle59ca2a2010-07-30 17:04:28 +00001201 s += '>>'
1202 self.message(s + '\t' + line.rstrip())
1203
Tim Peters2344fae2001-01-15 00:50:52 +00001204 def do_whatis(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001205 """whatis arg
1206 Print the type of the argument.
1207 """
Tim Peters2344fae2001-01-15 00:50:52 +00001208 try:
Georg Brandl0d089622010-07-30 16:00:46 +00001209 value = self._getval(arg)
Tim Peters2344fae2001-01-15 00:50:52 +00001210 except:
Georg Brandl0d089622010-07-30 16:00:46 +00001211 # _getval() already printed the error
Tim Peters2344fae2001-01-15 00:50:52 +00001212 return
1213 code = None
1214 # Is it a function?
Georg Brandl0d089622010-07-30 16:00:46 +00001215 try:
1216 code = value.__code__
1217 except Exception:
1218 pass
Tim Peters2344fae2001-01-15 00:50:52 +00001219 if code:
Georg Brandl0d089622010-07-30 16:00:46 +00001220 self.message('Function %s' % code.co_name)
Tim Peters2344fae2001-01-15 00:50:52 +00001221 return
1222 # Is it an instance method?
Georg Brandl0d089622010-07-30 16:00:46 +00001223 try:
1224 code = value.__func__.__code__
1225 except Exception:
1226 pass
Tim Peters2344fae2001-01-15 00:50:52 +00001227 if code:
Georg Brandl0d089622010-07-30 16:00:46 +00001228 self.message('Method %s' % code.co_name)
1229 return
1230 # Is it a class?
1231 if value.__class__ is type:
1232 self.message('Class %s.%s' % (value.__module__, value.__name__))
Tim Peters2344fae2001-01-15 00:50:52 +00001233 return
1234 # None of the above...
Georg Brandl0d089622010-07-30 16:00:46 +00001235 self.message(type(value))
Guido van Rossum8e2ec561993-07-29 09:37:38 +00001236
Georg Brandlcbc79c72010-12-04 16:21:42 +00001237 def do_display(self, arg):
1238 """display [expression]
1239
1240 Display the value of the expression if it changed, each time execution
1241 stops in the current frame.
1242
1243 Without expression, list all display expressions for the current frame.
1244 """
1245 if not arg:
1246 self.message('Currently displaying:')
1247 for item in self.displaying.get(self.curframe, {}).items():
1248 self.message('%s: %r' % item)
1249 else:
1250 val = self._getval_except(arg)
1251 self.displaying.setdefault(self.curframe, {})[arg] = val
1252 self.message('display %s: %r' % (arg, val))
1253
1254 def do_undisplay(self, arg):
1255 """undisplay [expression]
1256
1257 Do not display the expression any more in the current frame.
1258
1259 Without expression, clear all display expressions for the current frame.
1260 """
1261 if arg:
1262 try:
1263 del self.displaying.get(self.curframe, {})[arg]
1264 except KeyError:
1265 self.error('not displaying %s' % arg)
1266 else:
1267 self.displaying.pop(self.curframe, None)
1268
Georg Brandl1acb7462010-12-04 11:20:26 +00001269 def do_interact(self, arg):
1270 """interact
1271
1272 Start an interative interpreter whose global namespace
1273 contains all the (global and local) names found in the current scope.
1274 """
1275 ns = self.curframe.f_globals.copy()
1276 ns.update(self.curframe_locals)
1277 code.interact("*interactive*", local=ns)
1278
Tim Peters2344fae2001-01-15 00:50:52 +00001279 def do_alias(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001280 """alias [name [command [parameter parameter ...] ]]
1281 Create an alias called 'name' that executes 'command'. The
1282 command must *not* be enclosed in quotes. Replaceable
1283 parameters can be indicated by %1, %2, and so on, while %* is
1284 replaced by all the parameters. If no command is given, the
1285 current alias for name is shown. If no name is given, all
1286 aliases are listed.
1287
1288 Aliases may be nested and can contain anything that can be
1289 legally typed at the pdb prompt. Note! You *can* override
1290 internal pdb commands with aliases! Those internal commands
1291 are then hidden until the alias is removed. Aliasing is
1292 recursively applied to the first word of the command line; all
1293 other words in the line are left alone.
1294
1295 As an example, here are two useful aliases (especially when
1296 placed in the .pdbrc file):
1297
1298 # Print instance variables (usage "pi classInst")
1299 alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
1300 # Print instance variables in self
1301 alias ps pi self
1302 """
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +00001303 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +00001304 if len(args) == 0:
Benjamin Petersonbe74a372009-09-11 21:17:13 +00001305 keys = sorted(self.aliases.keys())
Tim Peters2344fae2001-01-15 00:50:52 +00001306 for alias in keys:
Georg Brandl0d089622010-07-30 16:00:46 +00001307 self.message("%s = %s" % (alias, self.aliases[alias]))
Tim Peters2344fae2001-01-15 00:50:52 +00001308 return
Guido van Rossum08454592002-07-12 13:10:53 +00001309 if args[0] in self.aliases and len(args) == 1:
Georg Brandl0d089622010-07-30 16:00:46 +00001310 self.message("%s = %s" % (args[0], self.aliases[args[0]]))
Tim Peters2344fae2001-01-15 00:50:52 +00001311 else:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +00001312 self.aliases[args[0]] = ' '.join(args[1:])
Guido van Rossum23efba41992-01-27 16:58:47 +00001313
Tim Peters2344fae2001-01-15 00:50:52 +00001314 def do_unalias(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001315 """unalias name
1316 Delete the specified alias.
1317 """
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +00001318 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +00001319 if len(args) == 0: return
Raymond Hettinger54f02222002-06-01 14:18:47 +00001320 if args[0] in self.aliases:
Tim Peters2344fae2001-01-15 00:50:52 +00001321 del self.aliases[args[0]]
Guido van Rossum00230781993-03-29 11:39:45 +00001322
Georg Brandl0d089622010-07-30 16:00:46 +00001323 # List of all the commands making the program resume execution.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001324 commands_resuming = ['do_continue', 'do_step', 'do_next', 'do_return',
1325 'do_quit', 'do_jump']
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001326
Tim Peters2344fae2001-01-15 00:50:52 +00001327 # Print a traceback starting at the top stack frame.
1328 # The most recently entered frame is printed last;
1329 # this is different from dbx and gdb, but consistent with
1330 # the Python interpreter's stack trace.
1331 # It is also consistent with the up/down commands (which are
1332 # compatible with dbx and gdb: up moves towards 'main()'
1333 # and down moves towards the most recent stack frame).
Guido van Rossum2424f851998-09-11 22:50:09 +00001334
Tim Peters2344fae2001-01-15 00:50:52 +00001335 def print_stack_trace(self):
1336 try:
1337 for frame_lineno in self.stack:
1338 self.print_stack_entry(frame_lineno)
1339 except KeyboardInterrupt:
1340 pass
Guido van Rossum2424f851998-09-11 22:50:09 +00001341
Tim Peters2344fae2001-01-15 00:50:52 +00001342 def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix):
1343 frame, lineno = frame_lineno
1344 if frame is self.curframe:
Georg Brandl0d089622010-07-30 16:00:46 +00001345 prefix = '> '
Tim Peters2344fae2001-01-15 00:50:52 +00001346 else:
Georg Brandl0d089622010-07-30 16:00:46 +00001347 prefix = ' '
1348 self.message(prefix +
1349 self.format_stack_entry(frame_lineno, prompt_prefix))
Guido van Rossum2424f851998-09-11 22:50:09 +00001350
Georg Brandl0d089622010-07-30 16:00:46 +00001351 # Provide help
Guido van Rossum921c8241992-01-10 14:54:42 +00001352
Georg Brandl0d089622010-07-30 16:00:46 +00001353 def do_help(self, arg):
1354 """h(elp)
1355 Without argument, print the list of available commands.
1356 With a command name as argument, print help about that command.
1357 "help pdb" shows the full pdb documentation.
1358 "help exec" gives help on the ! command.
1359 """
1360 if not arg:
1361 return cmd.Cmd.do_help(self, arg)
1362 try:
1363 try:
1364 topic = getattr(self, 'help_' + arg)
1365 return topic()
1366 except AttributeError:
1367 command = getattr(self, 'do_' + arg)
1368 except AttributeError:
1369 self.error('No help for %r' % arg)
1370 else:
Georg Brandl9e7dbc82010-10-14 07:14:31 +00001371 if sys.flags.optimize >= 2:
1372 self.error('No help for %r; please do not run Python with -OO '
1373 'if you need command help' % arg)
1374 return
Georg Brandl0d089622010-07-30 16:00:46 +00001375 self.message(command.__doc__.rstrip())
Guido van Rossum921c8241992-01-10 14:54:42 +00001376
Georg Brandl0d089622010-07-30 16:00:46 +00001377 do_h = do_help
Barry Warsaw210bd202002-11-05 22:40:20 +00001378
Tim Peters2344fae2001-01-15 00:50:52 +00001379 def help_exec(self):
Georg Brandl0d089622010-07-30 16:00:46 +00001380 """(!) statement
1381 Execute the (one-line) statement in the context of the current
1382 stack frame. The exclamation point can be omitted unless the
1383 first word of the statement resembles a debugger command. To
1384 assign to a global variable you must always prefix the command
1385 with a 'global' command, e.g.:
1386 (Pdb) global list_options; list_options = ['-l']
1387 (Pdb)
1388 """
Georg Brandl9e7dbc82010-10-14 07:14:31 +00001389 self.message((self.help_exec.__doc__ or '').strip())
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001390
Tim Peters2344fae2001-01-15 00:50:52 +00001391 def help_pdb(self):
1392 help()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001393
Georg Brandl0d089622010-07-30 16:00:46 +00001394 # other helper functions
1395
Tim Peters2344fae2001-01-15 00:50:52 +00001396 def lookupmodule(self, filename):
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001397 """Helper function for break/clear parsing -- may be overridden.
1398
1399 lookupmodule() translates (possibly incomplete) file or module name
1400 into an absolute file name.
1401 """
1402 if os.path.isabs(filename) and os.path.exists(filename):
Tim Peterse718f612004-10-12 21:51:32 +00001403 return filename
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001404 f = os.path.join(sys.path[0], filename)
1405 if os.path.exists(f) and self.canonic(f) == self.mainpyfile:
1406 return f
Tim Peters2344fae2001-01-15 00:50:52 +00001407 root, ext = os.path.splitext(filename)
1408 if ext == '':
1409 filename = filename + '.py'
1410 if os.path.isabs(filename):
1411 return filename
1412 for dirname in sys.path:
1413 while os.path.islink(dirname):
1414 dirname = os.readlink(dirname)
1415 fullname = os.path.join(dirname, filename)
1416 if os.path.exists(fullname):
1417 return fullname
1418 return None
Guido van Rossumb5699c71998-07-20 23:13:54 +00001419
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001420 def _runscript(self, filename):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001421 # The script has to run in __main__ namespace (or imports from
1422 # __main__ will break).
1423 #
1424 # So we clear up the __main__ and set several special variables
1425 # (this gets rid of pdb's globals and cleans old variables on restarts).
1426 import __main__
1427 __main__.__dict__.clear()
1428 __main__.__dict__.update({"__name__" : "__main__",
1429 "__file__" : filename,
1430 "__builtins__": __builtins__,
1431 })
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001432
1433 # When bdb sets tracing, a number of call and line events happens
1434 # BEFORE debugger even reaches user's code (and the exact sequence of
1435 # events depends on python version). So we take special measures to
1436 # avoid stopping before we reach the main script (see user_line and
1437 # user_call for details).
Georg Brandlac9a2bb2010-11-29 20:19:15 +00001438 self._wait_for_mainpyfile = True
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001439 self.mainpyfile = self.canonic(filename)
Georg Brandlac9a2bb2010-11-29 20:19:15 +00001440 self._user_requested_quit = False
Georg Brandld07ac642009-08-13 07:50:57 +00001441 with open(filename, "rb") as fp:
1442 statement = "exec(compile(%r, %r, 'exec'))" % \
1443 (fp.read(), self.mainpyfile)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001444 self.run(statement)
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001445
Georg Brandl9e7dbc82010-10-14 07:14:31 +00001446# Collect all command help into docstring, if not run with -OO
Georg Brandl0d089622010-07-30 16:00:46 +00001447
Georg Brandl9e7dbc82010-10-14 07:14:31 +00001448if __doc__ is not None:
1449 # unfortunately we can't guess this order from the class definition
1450 _help_order = [
1451 'help', 'where', 'down', 'up', 'break', 'tbreak', 'clear', 'disable',
1452 'enable', 'ignore', 'condition', 'commands', 'step', 'next', 'until',
1453 'jump', 'return', 'retval', 'run', 'continue', 'list', 'longlist',
Georg Brandlcbc79c72010-12-04 16:21:42 +00001454 'args', 'print', 'pp', 'whatis', 'source', 'display', 'undisplay',
1455 'interact', 'alias', 'unalias', 'debug', 'quit',
Georg Brandl9e7dbc82010-10-14 07:14:31 +00001456 ]
Georg Brandl0d089622010-07-30 16:00:46 +00001457
Georg Brandl9e7dbc82010-10-14 07:14:31 +00001458 for _command in _help_order:
1459 __doc__ += getattr(Pdb, 'do_' + _command).__doc__.strip() + '\n\n'
1460 __doc__ += Pdb.help_exec.__doc__
Georg Brandl0d089622010-07-30 16:00:46 +00001461
Georg Brandl9e7dbc82010-10-14 07:14:31 +00001462 del _help_order, _command
1463
Georg Brandl0d089622010-07-30 16:00:46 +00001464
Guido van Rossum35771131992-09-08 11:59:04 +00001465# Simplified interface
1466
Guido van Rossum5e38b6f1995-02-27 13:13:40 +00001467def run(statement, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +00001468 Pdb().run(statement, globals, locals)
Guido van Rossum5e38b6f1995-02-27 13:13:40 +00001469
1470def runeval(expression, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +00001471 return Pdb().runeval(expression, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001472
1473def runctx(statement, globals, locals):
Tim Peters2344fae2001-01-15 00:50:52 +00001474 # B/W compatibility
1475 run(statement, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001476
Raymond Hettinger2ef7e6c2004-10-24 00:32:24 +00001477def runcall(*args, **kwds):
1478 return Pdb().runcall(*args, **kwds)
Guido van Rossum4e160981992-09-02 20:43:20 +00001479
Guido van Rossumb6775db1994-08-01 11:34:53 +00001480def set_trace():
Johannes Gijsbers84a6c202004-11-07 11:35:30 +00001481 Pdb().set_trace(sys._getframe().f_back)
Guido van Rossum35771131992-09-08 11:59:04 +00001482
1483# Post-Mortem interface
1484
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001485def post_mortem(t=None):
1486 # handling the default
1487 if t is None:
1488 # sys.exc_info() returns (type, value, traceback) if an exception is
1489 # being handled, otherwise it returns None
1490 t = sys.exc_info()[2]
Georg Brandl0d089622010-07-30 16:00:46 +00001491 if t is None:
1492 raise ValueError("A valid traceback must be passed if no "
1493 "exception is being handled")
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001494
Tim Peters2344fae2001-01-15 00:50:52 +00001495 p = Pdb()
1496 p.reset()
Benjamin Peterson1a6e0d02008-10-25 15:49:17 +00001497 p.interaction(None, t)
Guido van Rossum35771131992-09-08 11:59:04 +00001498
1499def pm():
Tim Peters2344fae2001-01-15 00:50:52 +00001500 post_mortem(sys.last_traceback)
Guido van Rossum35771131992-09-08 11:59:04 +00001501
1502
1503# Main program for testing
1504
Guido van Rossum23efba41992-01-27 16:58:47 +00001505TESTCMD = 'import x; x.main()'
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001506
Guido van Rossum921c8241992-01-10 14:54:42 +00001507def test():
Tim Peters2344fae2001-01-15 00:50:52 +00001508 run(TESTCMD)
Guido van Rossume61fa0a1993-10-22 13:56:35 +00001509
1510# print help
1511def help():
Georg Brandl02053ee2010-07-18 10:11:03 +00001512 import pydoc
1513 pydoc.pager(__doc__)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001514
Georg Brandle0230912010-07-30 08:29:39 +00001515_usage = """\
1516usage: pdb.py [-c command] ... pyfile [arg] ...
1517
1518Debug the Python program given by pyfile.
1519
1520Initial commands are read from .pdbrc files in your home directory
1521and in the current directory, if they exist. Commands supplied with
1522-c are executed after commands from .pdbrc files.
1523
1524To let the script run until an exception occurs, use "-c continue".
Georg Brandl2dfec552010-07-30 08:43:32 +00001525To let the script run up to a given line X in the debugged file, use
1526"-c 'until X'"."""
Georg Brandle0230912010-07-30 08:29:39 +00001527
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001528def main():
Georg Brandle0230912010-07-30 08:29:39 +00001529 import getopt
1530
1531 opts, args = getopt.getopt(sys.argv[1:], 'hc:', ['--help', '--command='])
1532
1533 if not args:
1534 print(_usage)
Tim Peters2344fae2001-01-15 00:50:52 +00001535 sys.exit(2)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001536
Georg Brandle0230912010-07-30 08:29:39 +00001537 commands = []
1538 for opt, optarg in opts:
1539 if opt in ['-h', '--help']:
1540 print(_usage)
1541 sys.exit()
1542 elif opt in ['-c', '--command']:
1543 commands.append(optarg)
1544
1545 mainpyfile = args[0] # Get script filename
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001546 if not os.path.exists(mainpyfile):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001547 print('Error:', mainpyfile, 'does not exist')
Tim Peters2344fae2001-01-15 00:50:52 +00001548 sys.exit(1)
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001549
Georg Brandle0230912010-07-30 08:29:39 +00001550 sys.argv[:] = args # Hide "pdb.py" and pdb options from argument list
Guido van Rossumec577d51996-09-10 17:39:34 +00001551
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001552 # Replace pdb's dir with script's dir in front of module search path.
1553 sys.path[0] = os.path.dirname(mainpyfile)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001554
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001555 # Note on saving/restoring sys.argv: it's a good idea when sys.argv was
1556 # modified by the script being debugged. It's a bad idea when it was
Georg Brandl3078df02009-05-05 09:11:31 +00001557 # changed by the user from the command line. There is a "restart" command
1558 # which allows explicit specification of command line arguments.
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001559 pdb = Pdb()
Georg Brandle0230912010-07-30 08:29:39 +00001560 pdb.rcLines.extend(commands)
Georg Brandl1e30bd32010-07-30 07:21:26 +00001561 while True:
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001562 try:
1563 pdb._runscript(mainpyfile)
1564 if pdb._user_requested_quit:
1565 break
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001566 print("The program finished and will be restarted")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001567 except Restart:
1568 print("Restarting", mainpyfile, "with arguments:")
Georg Brandle0230912010-07-30 08:29:39 +00001569 print("\t" + " ".join(args))
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001570 except SystemExit:
1571 # In most cases SystemExit does not warrant a post-mortem session.
Georg Brandle0230912010-07-30 08:29:39 +00001572 print("The program exited via sys.exit(). Exit status:", end=' ')
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001573 print(sys.exc_info()[1])
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001574 except:
1575 traceback.print_exc()
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001576 print("Uncaught exception. Entering post mortem debugging")
1577 print("Running 'cont' or 'step' will restart the program")
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001578 t = sys.exc_info()[2]
Benjamin Peterson1a6e0d02008-10-25 15:49:17 +00001579 pdb.interaction(None, t)
Georg Brandl3078df02009-05-05 09:11:31 +00001580 print("Post mortem debugger finished. The " + mainpyfile +
1581 " will be restarted")
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001582
1583
1584# When invoked as main program, invoke the debugger on a script
Guido van Rossumd8faa362007-04-27 19:54:29 +00001585if __name__ == '__main__':
1586 import pdb
1587 pdb.main()