blob: a159d4ccd75468dbad89270a2bbb2459521c71da [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
Guido van Rossum921c8241992-01-10 14:54:42 +000069import sys
70import linecache
Guido van Rossum23efba41992-01-27 16:58:47 +000071import cmd
72import bdb
Georg Brandl0a9c3e92010-07-30 18:46:38 +000073import dis
Guido van Rossumb5699c71998-07-20 23:13:54 +000074import os
Barry Warsaw2bee8fe1999-09-09 16:32:41 +000075import re
Barry Warsaw210bd202002-11-05 22:40:20 +000076import pprint
Johannes Gijsbers25b38c82004-10-12 18:12:09 +000077import traceback
Georg Brandle59ca2a2010-07-30 17:04:28 +000078import inspect
Guido van Rossumd8faa362007-04-27 19:54:29 +000079
80
81class Restart(Exception):
82 """Causes a debugger to be restarted for the debugged python program."""
83 pass
84
Skip Montanaro352674d2001-02-07 23:14:30 +000085__all__ = ["run", "pm", "Pdb", "runeval", "runctx", "runcall", "set_trace",
86 "post_mortem", "help"]
87
Barry Warsaw2bee8fe1999-09-09 16:32:41 +000088def find_function(funcname, filename):
Thomas Wouters89f507f2006-12-13 04:49:30 +000089 cre = re.compile(r'def\s+%s\s*[(]' % re.escape(funcname))
Tim Peters2344fae2001-01-15 00:50:52 +000090 try:
91 fp = open(filename)
92 except IOError:
93 return None
94 # consumer of this info expects the first line to be 1
95 lineno = 1
96 answer = None
97 while 1:
98 line = fp.readline()
99 if line == '':
100 break
101 if cre.match(line):
102 answer = funcname, filename, lineno
103 break
104 lineno = lineno + 1
105 fp.close()
106 return answer
Guido van Rossum921c8241992-01-10 14:54:42 +0000107
Georg Brandl5ed2b5a2010-07-30 18:08:12 +0000108def getsourcelines(obj):
109 lines, lineno = inspect.findsource(obj)
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000110 if inspect.isframe(obj) and obj.f_globals is obj.f_locals:
Georg Brandl5ed2b5a2010-07-30 18:08:12 +0000111 # must be a module frame: do not try to cut a block out of it
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000112 return lines, 1
Georg Brandl5ed2b5a2010-07-30 18:08:12 +0000113 elif inspect.ismodule(obj):
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000114 return lines, 1
Georg Brandl5ed2b5a2010-07-30 18:08:12 +0000115 return inspect.getblock(lines[lineno:]), lineno+1
Guido van Rossum921c8241992-01-10 14:54:42 +0000116
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000117def lasti2lineno(code, lasti):
118 linestarts = list(dis.findlinestarts(code))
119 linestarts.reverse()
120 for i, lineno in linestarts:
121 if lasti >= i:
122 return lineno
123 return 0
124
125
Guido van Rossuma558e371994-11-10 22:27:35 +0000126# Interaction prompt line will separate file and call info from code
127# text using value of line_prefix string. A newline and arrow may
128# be to your liking. You can set it once pdb is imported using the
129# command "pdb.line_prefix = '\n% '".
Tim Peters2344fae2001-01-15 00:50:52 +0000130# line_prefix = ': ' # Use this to get the old situation back
131line_prefix = '\n-> ' # Probably a better default
Guido van Rossuma558e371994-11-10 22:27:35 +0000132
Guido van Rossum23efba41992-01-27 16:58:47 +0000133class Pdb(bdb.Bdb, cmd.Cmd):
Guido van Rossum2424f851998-09-11 22:50:09 +0000134
Georg Brandl243ad662009-05-05 09:00:19 +0000135 def __init__(self, completekey='tab', stdin=None, stdout=None, skip=None):
136 bdb.Bdb.__init__(self, skip=skip)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000137 cmd.Cmd.__init__(self, completekey, stdin, stdout)
138 if stdout:
139 self.use_rawinput = 0
Tim Peters2344fae2001-01-15 00:50:52 +0000140 self.prompt = '(Pdb) '
141 self.aliases = {}
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000142 self.mainpyfile = ''
143 self._wait_for_mainpyfile = 0
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000144 self.tb_lineno = {}
Tim Peters2344fae2001-01-15 00:50:52 +0000145 # Try to load readline if it exists
146 try:
147 import readline
148 except ImportError:
149 pass
Guido van Rossum2424f851998-09-11 22:50:09 +0000150
Tim Peters2344fae2001-01-15 00:50:52 +0000151 # Read $HOME/.pdbrc and ./.pdbrc
152 self.rcLines = []
Raymond Hettinger54f02222002-06-01 14:18:47 +0000153 if 'HOME' in os.environ:
Tim Peters2344fae2001-01-15 00:50:52 +0000154 envHome = os.environ['HOME']
155 try:
Florent Xicluna7dde7922010-09-03 19:52:03 +0000156 with open(os.path.join(envHome, ".pdbrc")) as rcFile:
157 self.rcLines.extend(rcFile)
Tim Peters2344fae2001-01-15 00:50:52 +0000158 except IOError:
159 pass
Tim Peters2344fae2001-01-15 00:50:52 +0000160 try:
Florent Xicluna7dde7922010-09-03 19:52:03 +0000161 with open(".pdbrc") as rcFile:
162 self.rcLines.extend(rcFile)
Tim Peters2344fae2001-01-15 00:50:52 +0000163 except IOError:
164 pass
Guido van Rossum23efba41992-01-27 16:58:47 +0000165
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000166 self.commands = {} # associates a command list to breakpoint numbers
Benjamin Petersond23f8222009-04-05 19:13:16 +0000167 self.commands_doprompt = {} # for each bp num, tells if the prompt
168 # must be disp. after execing the cmd list
169 self.commands_silent = {} # for each bp num, tells if the stack trace
170 # must be disp. after execing the cmd list
171 self.commands_defining = False # True while in the process of defining
172 # a command list
173 self.commands_bnum = None # The breakpoint number for which we are
174 # defining a list
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000175
Tim Peters2344fae2001-01-15 00:50:52 +0000176 def reset(self):
177 bdb.Bdb.reset(self)
178 self.forget()
Guido van Rossum23efba41992-01-27 16:58:47 +0000179
Tim Peters2344fae2001-01-15 00:50:52 +0000180 def forget(self):
181 self.lineno = None
182 self.stack = []
183 self.curindex = 0
184 self.curframe = None
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000185 self.tb_lineno.clear()
Guido van Rossum2424f851998-09-11 22:50:09 +0000186
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000187 def setup(self, f, tb):
Tim Peters2344fae2001-01-15 00:50:52 +0000188 self.forget()
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000189 self.stack, self.curindex = self.get_stack(f, tb)
190 while tb:
191 # when setting up post-mortem debugging with a traceback, save all
192 # the original line numbers to be displayed along the current line
193 # numbers (which can be different, e.g. due to finally clauses)
194 lineno = lasti2lineno(tb.tb_frame.f_code, tb.tb_lasti)
195 self.tb_lineno[tb.tb_frame] = lineno
196 tb = tb.tb_next
Tim Peters2344fae2001-01-15 00:50:52 +0000197 self.curframe = self.stack[self.curindex][0]
Benjamin Petersond23f8222009-04-05 19:13:16 +0000198 # The f_locals dictionary is updated from the actual frame
199 # locals whenever the .f_locals accessor is called, so we
200 # cache it here to ensure that modifications are not overwritten.
201 self.curframe_locals = self.curframe.f_locals
Georg Brandle0230912010-07-30 08:29:39 +0000202 return self.execRcLines()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000203
Tim Peters2344fae2001-01-15 00:50:52 +0000204 # Can be executed earlier than 'setup' if desired
205 def execRcLines(self):
Georg Brandle0230912010-07-30 08:29:39 +0000206 if not self.rcLines:
207 return
208 # local copy because of recursion
209 rcLines = self.rcLines
210 rcLines.reverse()
211 # execute every line only once
212 self.rcLines = []
213 while rcLines:
214 line = rcLines.pop().strip()
215 if line and line[0] != '#':
216 if self.onecmd(line):
217 # if onecmd returns True, the command wants to exit
218 # from the interaction, save leftover rc lines
219 # to execute before next interaction
220 self.rcLines += reversed(rcLines)
221 return True
Guido van Rossum2424f851998-09-11 22:50:09 +0000222
Tim Peters280488b2002-08-23 18:19:30 +0000223 # Override Bdb methods
Michael W. Hudsondd32a912002-08-15 14:59:02 +0000224
225 def user_call(self, frame, argument_list):
226 """This method is called when there is the remote possibility
227 that we ever need to stop in this function."""
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000228 if self._wait_for_mainpyfile:
229 return
Michael W. Hudson01eb85c2003-01-31 17:48:29 +0000230 if self.stop_here(frame):
Georg Brandl0d089622010-07-30 16:00:46 +0000231 self.message('--Call--')
Michael W. Hudson01eb85c2003-01-31 17:48:29 +0000232 self.interaction(frame, None)
Guido van Rossum2424f851998-09-11 22:50:09 +0000233
Tim Peters2344fae2001-01-15 00:50:52 +0000234 def user_line(self, frame):
235 """This function is called when we stop or break at this line."""
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000236 if self._wait_for_mainpyfile:
237 if (self.mainpyfile != self.canonic(frame.f_code.co_filename)
238 or frame.f_lineno<= 0):
239 return
240 self._wait_for_mainpyfile = 0
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000241 if self.bp_commands(frame):
242 self.interaction(frame, None)
243
Georg Brandle0230912010-07-30 08:29:39 +0000244 def bp_commands(self, frame):
Georg Brandl3078df02009-05-05 09:11:31 +0000245 """Call every command that was set for the current active breakpoint
246 (if there is one).
247
248 Returns True if the normal interaction function must be called,
249 False otherwise."""
250 # self.currentbp is set in bdb in Bdb.break_here if a breakpoint was hit
251 if getattr(self, "currentbp", False) and \
252 self.currentbp in self.commands:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000253 currentbp = self.currentbp
254 self.currentbp = 0
255 lastcmd_back = self.lastcmd
256 self.setup(frame, None)
257 for line in self.commands[currentbp]:
258 self.onecmd(line)
259 self.lastcmd = lastcmd_back
260 if not self.commands_silent[currentbp]:
261 self.print_stack_entry(self.stack[self.curindex])
262 if self.commands_doprompt[currentbp]:
263 self.cmdloop()
264 self.forget()
265 return
266 return 1
Guido van Rossum9e1ee971997-07-11 13:43:53 +0000267
Tim Peters2344fae2001-01-15 00:50:52 +0000268 def user_return(self, frame, return_value):
269 """This function is called when a return trap is set here."""
Georg Brandl34cc0f52010-07-30 09:43:00 +0000270 if self._wait_for_mainpyfile:
271 return
Tim Peters2344fae2001-01-15 00:50:52 +0000272 frame.f_locals['__return__'] = return_value
Georg Brandl0d089622010-07-30 16:00:46 +0000273 self.message('--Return--')
Tim Peters2344fae2001-01-15 00:50:52 +0000274 self.interaction(frame, None)
Guido van Rossum2424f851998-09-11 22:50:09 +0000275
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000276 def user_exception(self, frame, exc_info):
Tim Peters2344fae2001-01-15 00:50:52 +0000277 """This function is called if an exception occurs,
278 but only if we are to stop at or just below this level."""
Georg Brandl34cc0f52010-07-30 09:43:00 +0000279 if self._wait_for_mainpyfile:
280 return
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000281 exc_type, exc_value, exc_traceback = exc_info
Tim Peters2344fae2001-01-15 00:50:52 +0000282 frame.f_locals['__exception__'] = exc_type, exc_value
Georg Brandl0d089622010-07-30 16:00:46 +0000283 self.message(traceback.format_exception_only(exc_type,
284 exc_value)[-1].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000285 self.interaction(frame, exc_traceback)
Guido van Rossum2424f851998-09-11 22:50:09 +0000286
Tim Peters2344fae2001-01-15 00:50:52 +0000287 # General interaction function
288
289 def interaction(self, frame, traceback):
Georg Brandle0230912010-07-30 08:29:39 +0000290 if self.setup(frame, traceback):
291 # no interaction desired at this time (happens if .pdbrc contains
292 # a command like "continue")
293 self.forget()
294 return
Tim Peters2344fae2001-01-15 00:50:52 +0000295 self.print_stack_entry(self.stack[self.curindex])
296 self.cmdloop()
297 self.forget()
298
Benjamin Petersond23f8222009-04-05 19:13:16 +0000299 def displayhook(self, obj):
300 """Custom displayhook for the exec in default(), which prevents
301 assignment of the _ variable in the builtins.
302 """
Georg Brandl9fa2e022009-09-16 16:40:45 +0000303 # reproduce the behavior of the standard displayhook, not printing None
304 if obj is not None:
Georg Brandl0d089622010-07-30 16:00:46 +0000305 self.message(repr(obj))
Benjamin Petersond23f8222009-04-05 19:13:16 +0000306
Tim Peters2344fae2001-01-15 00:50:52 +0000307 def default(self, line):
308 if line[:1] == '!': line = line[1:]
Benjamin Petersond23f8222009-04-05 19:13:16 +0000309 locals = self.curframe_locals
Tim Peters2344fae2001-01-15 00:50:52 +0000310 globals = self.curframe.f_globals
311 try:
312 code = compile(line + '\n', '<stdin>', 'single')
Christian Heimes679db4a2008-01-18 09:56:22 +0000313 save_stdout = sys.stdout
314 save_stdin = sys.stdin
Benjamin Petersond23f8222009-04-05 19:13:16 +0000315 save_displayhook = sys.displayhook
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000316 try:
317 sys.stdin = self.stdin
318 sys.stdout = self.stdout
Benjamin Petersond23f8222009-04-05 19:13:16 +0000319 sys.displayhook = self.displayhook
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000320 exec(code, globals, locals)
321 finally:
322 sys.stdout = save_stdout
323 sys.stdin = save_stdin
Benjamin Petersond23f8222009-04-05 19:13:16 +0000324 sys.displayhook = save_displayhook
Tim Peters2344fae2001-01-15 00:50:52 +0000325 except:
Georg Brandl0d089622010-07-30 16:00:46 +0000326 exc_info = sys.exc_info()[:2]
327 self.error(traceback.format_exception_only(*exc_info)[-1].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000328
329 def precmd(self, line):
330 """Handle alias expansion and ';;' separator."""
Guido van Rossum08454592002-07-12 13:10:53 +0000331 if not line.strip():
Tim Peters2344fae2001-01-15 00:50:52 +0000332 return line
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000333 args = line.split()
Raymond Hettinger54f02222002-06-01 14:18:47 +0000334 while args[0] in self.aliases:
Tim Peters2344fae2001-01-15 00:50:52 +0000335 line = self.aliases[args[0]]
336 ii = 1
337 for tmpArg in args[1:]:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000338 line = line.replace("%" + str(ii),
Tim Peters2344fae2001-01-15 00:50:52 +0000339 tmpArg)
340 ii = ii + 1
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000341 line = line.replace("%*", ' '.join(args[1:]))
342 args = line.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000343 # split into ';;' separated commands
344 # unless it's an alias command
345 if args[0] != 'alias':
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000346 marker = line.find(';;')
Tim Peters2344fae2001-01-15 00:50:52 +0000347 if marker >= 0:
348 # queue up everything after marker
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000349 next = line[marker+2:].lstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000350 self.cmdqueue.append(next)
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000351 line = line[:marker].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000352 return line
353
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000354 def onecmd(self, line):
355 """Interpret the argument as though it had been typed in response
356 to the prompt.
357
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000358 Checks whether this line is typed at the normal prompt or in
359 a breakpoint command list definition.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000360 """
361 if not self.commands_defining:
362 return cmd.Cmd.onecmd(self, line)
363 else:
364 return self.handle_command_def(line)
365
Georg Brandlb90ffd82010-07-30 22:20:16 +0000366 def handle_command_def(self, line):
Georg Brandl44f8bf92010-07-30 08:54:49 +0000367 """Handles one command line during command list definition."""
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000368 cmd, arg, line = self.parseline(line)
Georg Brandl44f8bf92010-07-30 08:54:49 +0000369 if not cmd:
370 return
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000371 if cmd == 'silent':
372 self.commands_silent[self.commands_bnum] = True
373 return # continue to handle other cmd def in the cmd list
374 elif cmd == 'end':
375 self.cmdqueue = []
376 return 1 # end of cmd list
377 cmdlist = self.commands[self.commands_bnum]
Georg Brandl44f8bf92010-07-30 08:54:49 +0000378 if arg:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000379 cmdlist.append(cmd+' '+arg)
380 else:
381 cmdlist.append(cmd)
382 # Determine if we must stop
383 try:
384 func = getattr(self, 'do_' + cmd)
385 except AttributeError:
386 func = self.default
Georg Brandl3078df02009-05-05 09:11:31 +0000387 # one of the resuming commands
388 if func.__name__ in self.commands_resuming:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000389 self.commands_doprompt[self.commands_bnum] = False
390 self.cmdqueue = []
391 return 1
392 return
393
Georg Brandl0d089622010-07-30 16:00:46 +0000394 # interface abstraction functions
395
396 def message(self, msg):
397 print(msg, file=self.stdout)
398
399 def error(self, msg):
400 print('***', msg, file=self.stdout)
401
Tim Peters2344fae2001-01-15 00:50:52 +0000402 # Command definitions, called by cmdloop()
403 # The argument is the remaining string on the command line
404 # Return true to exit from the command loop
405
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000406 def do_commands(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000407 """commands [bpnumber]
408 (com) ...
409 (com) end
410 (Pdb)
Georg Brandl3078df02009-05-05 09:11:31 +0000411
Georg Brandl0d089622010-07-30 16:00:46 +0000412 Specify a list of commands for breakpoint number bpnumber.
413 The commands themselves are entered on the following lines.
414 Type a line containing just 'end' to terminate the commands.
415 The commands are executed when the breakpoint is hit.
416
417 To remove all commands from a breakpoint, type commands and
418 follow it immediately with end; that is, give no commands.
419
420 With no bpnumber argument, commands refers to the last
421 breakpoint set.
422
423 You can use breakpoint commands to start your program up
424 again. Simply use the continue command, or step, or any other
425 command that resumes execution.
426
427 Specifying any command resuming execution (currently continue,
428 step, next, return, jump, quit and their abbreviations)
429 terminates the command list (as if that command was
430 immediately followed by end). This is because any time you
431 resume execution (even with a simple next or step), you may
432 encounter another breakpoint -- which could have its own
433 command list, leading to ambiguities about which list to
434 execute.
435
436 If you use the 'silent' command in the command list, the usual
437 message about stopping at a breakpoint is not printed. This
438 may be desirable for breakpoints that are to print a specific
439 message and then continue. If none of the other commands
440 print anything, you will see no sign that the breakpoint was
441 reached.
442 """
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000443 if not arg:
Georg Brandl7410dd12010-07-30 12:01:20 +0000444 bnum = len(bdb.Breakpoint.bpbynumber) - 1
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000445 else:
446 try:
447 bnum = int(arg)
448 except:
Georg Brandl0d089622010-07-30 16:00:46 +0000449 self.error("Usage: commands [bnum]\n ...\n end")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000450 return
451 self.commands_bnum = bnum
Georg Brandlb90ffd82010-07-30 22:20:16 +0000452 # Save old definitions for the case of a keyboard interrupt.
453 if bnum in self.commands:
454 old_command_defs = (self.commands[bnum],
455 self.commands_doprompt[bnum],
456 self.commands_silent[bnum])
457 else:
458 old_command_defs = None
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000459 self.commands[bnum] = []
460 self.commands_doprompt[bnum] = True
461 self.commands_silent[bnum] = False
Georg Brandlb90ffd82010-07-30 22:20:16 +0000462
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000463 prompt_back = self.prompt
464 self.prompt = '(com) '
465 self.commands_defining = True
Georg Brandl44f8bf92010-07-30 08:54:49 +0000466 try:
467 self.cmdloop()
Georg Brandlb90ffd82010-07-30 22:20:16 +0000468 except KeyboardInterrupt:
469 # Restore old definitions.
470 if old_command_defs:
471 self.commands[bnum] = old_command_defs[0]
472 self.commands_doprompt[bnum] = old_command_defs[1]
473 self.commands_silent[bnum] = old_command_defs[2]
474 else:
475 del self.commands[bnum]
476 del self.commands_doprompt[bnum]
477 del self.commands_silent[bnum]
478 self.error('command definition aborted, old commands restored')
Georg Brandl44f8bf92010-07-30 08:54:49 +0000479 finally:
480 self.commands_defining = False
481 self.prompt = prompt_back
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000482
Tim Peters2344fae2001-01-15 00:50:52 +0000483 def do_break(self, arg, temporary = 0):
Georg Brandl0d089622010-07-30 16:00:46 +0000484 """b(reak) [ ([filename:]lineno | function) [, condition] ]
485 Without argument, list all breaks.
486
487 With a line number argument, set a break at this line in the
488 current file. With a function name, set a break at the first
489 executable line of that function. If a second argument is
490 present, it is a string specifying an expression which must
491 evaluate to true before the breakpoint is honored.
492
493 The line number may be prefixed with a filename and a colon,
494 to specify a breakpoint in another file (probably one that
495 hasn't been loaded yet). The file is searched for on
496 sys.path; the .py suffix may be omitted.
497 """
Tim Peters2344fae2001-01-15 00:50:52 +0000498 if not arg:
499 if self.breaks: # There's at least one
Georg Brandl0d089622010-07-30 16:00:46 +0000500 self.message("Num Type Disp Enb Where")
Tim Peters2344fae2001-01-15 00:50:52 +0000501 for bp in bdb.Breakpoint.bpbynumber:
502 if bp:
Georg Brandl0d089622010-07-30 16:00:46 +0000503 self.message(bp.bpformat())
Tim Peters2344fae2001-01-15 00:50:52 +0000504 return
505 # parse arguments; comma has lowest precedence
506 # and cannot occur in filename
507 filename = None
508 lineno = None
509 cond = None
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000510 comma = arg.find(',')
Tim Peters2344fae2001-01-15 00:50:52 +0000511 if comma > 0:
512 # parse stuff after comma: "condition"
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000513 cond = arg[comma+1:].lstrip()
514 arg = arg[:comma].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000515 # parse stuff before comma: [filename:]lineno | function
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000516 colon = arg.rfind(':')
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000517 funcname = None
Tim Peters2344fae2001-01-15 00:50:52 +0000518 if colon >= 0:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000519 filename = arg[:colon].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000520 f = self.lookupmodule(filename)
521 if not f:
Georg Brandl0d089622010-07-30 16:00:46 +0000522 self.error('%r not found from sys.path' % filename)
Tim Peters2344fae2001-01-15 00:50:52 +0000523 return
524 else:
525 filename = f
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000526 arg = arg[colon+1:].lstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000527 try:
528 lineno = int(arg)
Georg Brandlf93390a2010-10-14 07:17:44 +0000529 except ValueError:
Georg Brandl0d089622010-07-30 16:00:46 +0000530 self.error('Bad lineno: %s' % arg)
Tim Peters2344fae2001-01-15 00:50:52 +0000531 return
532 else:
533 # no colon; can be lineno or function
534 try:
535 lineno = int(arg)
536 except ValueError:
537 try:
538 func = eval(arg,
539 self.curframe.f_globals,
Benjamin Petersond23f8222009-04-05 19:13:16 +0000540 self.curframe_locals)
Tim Peters2344fae2001-01-15 00:50:52 +0000541 except:
542 func = arg
543 try:
Christian Heimesff737952007-11-27 10:40:20 +0000544 if hasattr(func, '__func__'):
545 func = func.__func__
Neal Norwitz221085d2007-02-25 20:55:47 +0000546 code = func.__code__
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000547 #use co_name to identify the bkpt (function names
548 #could be aliased, but co_name is invariant)
549 funcname = code.co_name
Tim Peters2344fae2001-01-15 00:50:52 +0000550 lineno = code.co_firstlineno
551 filename = code.co_filename
552 except:
553 # last thing to try
554 (ok, filename, ln) = self.lineinfo(arg)
555 if not ok:
Georg Brandl0d089622010-07-30 16:00:46 +0000556 self.error('The specified object %r is not a function '
557 'or was not found along sys.path.' % arg)
Tim Peters2344fae2001-01-15 00:50:52 +0000558 return
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000559 funcname = ok # ok contains a function name
Tim Peters2344fae2001-01-15 00:50:52 +0000560 lineno = int(ln)
561 if not filename:
562 filename = self.defaultFile()
563 # Check for reasonable breakpoint
564 line = self.checkline(filename, lineno)
565 if line:
566 # now set the break point
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000567 err = self.set_break(filename, line, temporary, cond, funcname)
Georg Brandl0d089622010-07-30 16:00:46 +0000568 if err:
569 self.error(err, file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000570 else:
571 bp = self.get_breaks(filename, line)[-1]
Georg Brandl0d089622010-07-30 16:00:46 +0000572 self.message("Breakpoint %d at %s:%d" %
573 (bp.number, bp.file, bp.line))
Tim Peters2344fae2001-01-15 00:50:52 +0000574
575 # To be overridden in derived debuggers
576 def defaultFile(self):
577 """Produce a reasonable default."""
578 filename = self.curframe.f_code.co_filename
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000579 if filename == '<string>' and self.mainpyfile:
580 filename = self.mainpyfile
Tim Peters2344fae2001-01-15 00:50:52 +0000581 return filename
582
583 do_b = do_break
584
585 def do_tbreak(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000586 """tbreak [ ([filename:]lineno | function) [, condition] ]
587 Same arguments as break, but sets a temporary breakpoint: it
588 is automatically deleted when first hit.
589 """
Tim Peters2344fae2001-01-15 00:50:52 +0000590 self.do_break(arg, 1)
591
592 def lineinfo(self, identifier):
593 failed = (None, None, None)
594 # Input is identifier, may be in single quotes
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000595 idstring = identifier.split("'")
Tim Peters2344fae2001-01-15 00:50:52 +0000596 if len(idstring) == 1:
597 # not in single quotes
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000598 id = idstring[0].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000599 elif len(idstring) == 3:
600 # quoted
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000601 id = idstring[1].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000602 else:
603 return failed
604 if id == '': return failed
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000605 parts = id.split('.')
Tim Peters2344fae2001-01-15 00:50:52 +0000606 # Protection for derived debuggers
607 if parts[0] == 'self':
608 del parts[0]
609 if len(parts) == 0:
610 return failed
611 # Best first guess at file to look at
612 fname = self.defaultFile()
613 if len(parts) == 1:
614 item = parts[0]
615 else:
616 # More than one part.
617 # First is module, second is method/class
618 f = self.lookupmodule(parts[0])
619 if f:
620 fname = f
621 item = parts[1]
622 answer = find_function(item, fname)
623 return answer or failed
624
625 def checkline(self, filename, lineno):
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000626 """Check whether specified line seems to be executable.
Tim Peters2344fae2001-01-15 00:50:52 +0000627
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000628 Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
629 line or EOF). Warning: testing is not comprehensive.
630 """
Georg Brandl1e30bd32010-07-30 07:21:26 +0000631 # this method should be callable before starting debugging, so default
632 # to "no globals" if there is no current frame
633 globs = self.curframe.f_globals if hasattr(self, 'curframe') else None
634 line = linecache.getline(filename, lineno, globs)
Tim Peters2344fae2001-01-15 00:50:52 +0000635 if not line:
Georg Brandl0d089622010-07-30 16:00:46 +0000636 self.message('End of file')
Tim Peters2344fae2001-01-15 00:50:52 +0000637 return 0
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000638 line = line.strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000639 # Don't allow setting breakpoint at a blank line
Guido van Rossum08454592002-07-12 13:10:53 +0000640 if (not line or (line[0] == '#') or
641 (line[:3] == '"""') or line[:3] == "'''"):
Georg Brandl0d089622010-07-30 16:00:46 +0000642 self.error('Blank or comment')
Tim Peters2344fae2001-01-15 00:50:52 +0000643 return 0
Tim Peters2344fae2001-01-15 00:50:52 +0000644 return lineno
645
646 def do_enable(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000647 """enable bpnumber [bpnumber ...]
648 Enables the breakpoints given as a space separated list of
649 breakpoint numbers.
650 """
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000651 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000652 for i in args:
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000653 try:
Georg Brandl7410dd12010-07-30 12:01:20 +0000654 bp = self.get_bpbynumber(i)
655 except ValueError as err:
Georg Brandl0d089622010-07-30 16:00:46 +0000656 self.error(err)
Georg Brandl7410dd12010-07-30 12:01:20 +0000657 else:
Tim Peters2344fae2001-01-15 00:50:52 +0000658 bp.enable()
Georg Brandl0d089622010-07-30 16:00:46 +0000659 self.message('Enabled %s' % bp)
Tim Peters2344fae2001-01-15 00:50:52 +0000660
661 def do_disable(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000662 """disable bpnumber [bpnumber ...]
663 Disables the breakpoints given as a space separated list of
664 breakpoint numbers. Disabling a breakpoint means it cannot
665 cause the program to stop execution, but unlike clearing a
666 breakpoint, it remains in the list of breakpoints and can be
667 (re-)enabled.
668 """
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000669 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000670 for i in args:
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000671 try:
Georg Brandl7410dd12010-07-30 12:01:20 +0000672 bp = self.get_bpbynumber(i)
673 except ValueError as err:
Georg Brandl0d089622010-07-30 16:00:46 +0000674 self.error(err)
Georg Brandl7410dd12010-07-30 12:01:20 +0000675 else:
Tim Peters2344fae2001-01-15 00:50:52 +0000676 bp.disable()
Georg Brandl0d089622010-07-30 16:00:46 +0000677 self.message('Disabled %s' % bp)
Tim Peters2344fae2001-01-15 00:50:52 +0000678
679 def do_condition(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000680 """condition bpnumber [condition]
681 Set a new condition for the breakpoint, an expression which
682 must evaluate to true before the breakpoint is honored. If
683 condition is absent, any existing condition is removed; i.e.,
684 the breakpoint is made unconditional.
685 """
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000686 args = arg.split(' ', 1)
Thomas Woutersb2137042007-02-01 18:02:27 +0000687 try:
Tim Peters2344fae2001-01-15 00:50:52 +0000688 cond = args[1]
Georg Brandl7410dd12010-07-30 12:01:20 +0000689 except IndexError:
Tim Peters2344fae2001-01-15 00:50:52 +0000690 cond = None
Guido van Rossumd8faa362007-04-27 19:54:29 +0000691 try:
Georg Brandl7410dd12010-07-30 12:01:20 +0000692 bp = self.get_bpbynumber(args[0].strip())
693 except ValueError as err:
Georg Brandl0d089622010-07-30 16:00:46 +0000694 self.error(err)
Georg Brandl7410dd12010-07-30 12:01:20 +0000695 else:
Tim Peters2344fae2001-01-15 00:50:52 +0000696 bp.cond = cond
697 if not cond:
Georg Brandl0d089622010-07-30 16:00:46 +0000698 self.message('Breakpoint %d is now unconditional.' % bp.number)
Georg Brandl7410dd12010-07-30 12:01:20 +0000699 else:
Georg Brandl0d089622010-07-30 16:00:46 +0000700 self.message('New condition set for breakpoint %d.' % bp.number)
Tim Peters2344fae2001-01-15 00:50:52 +0000701
Georg Brandl7410dd12010-07-30 12:01:20 +0000702 def do_ignore(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000703 """ignore bpnumber [count]
704 Set the ignore count for the given breakpoint number. If
705 count is omitted, the ignore count is set to 0. A breakpoint
706 becomes active when the ignore count is zero. When non-zero,
707 the count is decremented each time the breakpoint is reached
708 and the breakpoint is not disabled and any associated
709 condition evaluates to true.
710 """
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000711 args = arg.split()
Thomas Woutersb2137042007-02-01 18:02:27 +0000712 try:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000713 count = int(args[1].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000714 except:
715 count = 0
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.ignore = count
Guido van Rossum08454592002-07-12 13:10:53 +0000722 if count > 0:
Guido van Rossum08454592002-07-12 13:10:53 +0000723 if count > 1:
Georg Brandl0d089622010-07-30 16:00:46 +0000724 countstr = '%d crossings' % count
Tim Peters2344fae2001-01-15 00:50:52 +0000725 else:
Georg Brandl0d089622010-07-30 16:00:46 +0000726 countstr = '1 crossing'
727 self.message('Will ignore next %s of breakpoint %d.' %
728 (countstr, bp.number))
Tim Peters2344fae2001-01-15 00:50:52 +0000729 else:
Georg Brandl0d089622010-07-30 16:00:46 +0000730 self.message('Will stop next time breakpoint %d is reached.'
731 % bp.number)
Tim Peters2344fae2001-01-15 00:50:52 +0000732
733 def do_clear(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000734 """cl(ear) filename:lineno\ncl(ear) [bpnumber [bpnumber...]]
735 With a space separated list of breakpoint numbers, clear
736 those breakpoints. Without argument, clear all breaks (but
737 first ask confirmation). With a filename:lineno argument,
738 clear all breaks at that line in that file.
739 """
Tim Peters2344fae2001-01-15 00:50:52 +0000740 if not arg:
741 try:
Guido van Rossumc5b6ab02007-05-27 09:19:52 +0000742 reply = input('Clear all breaks? ')
Tim Peters2344fae2001-01-15 00:50:52 +0000743 except EOFError:
744 reply = 'no'
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000745 reply = reply.strip().lower()
Tim Peters2344fae2001-01-15 00:50:52 +0000746 if reply in ('y', 'yes'):
Georg Brandl7410dd12010-07-30 12:01:20 +0000747 bplist = [bp for bp in bdb.Breakpoint.bpbynumber if bp]
Tim Peters2344fae2001-01-15 00:50:52 +0000748 self.clear_all_breaks()
Georg Brandl7410dd12010-07-30 12:01:20 +0000749 for bp in bplist:
Georg Brandl0d089622010-07-30 16:00:46 +0000750 self.message('Deleted %s' % bp)
Tim Peters2344fae2001-01-15 00:50:52 +0000751 return
752 if ':' in arg:
753 # Make sure it works for "clear C:\foo\bar.py:12"
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000754 i = arg.rfind(':')
Tim Peters2344fae2001-01-15 00:50:52 +0000755 filename = arg[:i]
756 arg = arg[i+1:]
757 try:
758 lineno = int(arg)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000759 except ValueError:
Tim Peters2344fae2001-01-15 00:50:52 +0000760 err = "Invalid line number (%s)" % arg
761 else:
Georg Brandl7410dd12010-07-30 12:01:20 +0000762 bplist = self.get_breaks(filename, lineno)
Tim Peters2344fae2001-01-15 00:50:52 +0000763 err = self.clear_break(filename, lineno)
Georg Brandl7410dd12010-07-30 12:01:20 +0000764 if err:
Georg Brandl0d089622010-07-30 16:00:46 +0000765 self.error(err)
Georg Brandl7410dd12010-07-30 12:01:20 +0000766 else:
767 for bp in bplist:
Georg Brandl0d089622010-07-30 16:00:46 +0000768 self.message('Deleted %s' % bp)
Tim Peters2344fae2001-01-15 00:50:52 +0000769 return
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000770 numberlist = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000771 for i in numberlist:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000772 try:
Georg Brandl7410dd12010-07-30 12:01:20 +0000773 bp = self.get_bpbynumber(i)
774 except ValueError as err:
Georg Brandl0d089622010-07-30 16:00:46 +0000775 self.error(err)
Tim Peters2344fae2001-01-15 00:50:52 +0000776 else:
Georg Brandl7410dd12010-07-30 12:01:20 +0000777 self.clear_break(bp.file, bp.line)
Georg Brandl0d089622010-07-30 16:00:46 +0000778 self.message('Deleted %s' % bp)
Tim Peters2344fae2001-01-15 00:50:52 +0000779 do_cl = do_clear # 'c' is already an abbreviation for 'continue'
780
781 def do_where(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000782 """w(here)
783 Print a stack trace, with the most recent frame at the bottom.
784 An arrow indicates the "current frame", which determines the
785 context of most commands. 'bt' is an alias for this command.
786 """
Tim Peters2344fae2001-01-15 00:50:52 +0000787 self.print_stack_trace()
788 do_w = do_where
Guido van Rossum6bd68352001-01-20 17:57:37 +0000789 do_bt = do_where
Tim Peters2344fae2001-01-15 00:50:52 +0000790
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000791 def _select_frame(self, number):
792 assert 0 <= number < len(self.stack)
793 self.curindex = number
794 self.curframe = self.stack[self.curindex][0]
795 self.curframe_locals = self.curframe.f_locals
796 self.print_stack_entry(self.stack[self.curindex])
797 self.lineno = None
798
Tim Peters2344fae2001-01-15 00:50:52 +0000799 def do_up(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000800 """u(p) [count]
801 Move the current frame count (default one) levels up in the
802 stack trace (to an older frame).
803 """
Tim Peters2344fae2001-01-15 00:50:52 +0000804 if self.curindex == 0:
Georg Brandl0d089622010-07-30 16:00:46 +0000805 self.error('Oldest frame')
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000806 return
807 try:
808 count = int(arg or 1)
809 except ValueError:
Georg Brandl0d089622010-07-30 16:00:46 +0000810 self.error('Invalid frame count (%s)' % arg)
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000811 return
812 if count < 0:
813 newframe = 0
Tim Peters2344fae2001-01-15 00:50:52 +0000814 else:
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000815 newframe = max(0, self.curindex - count)
816 self._select_frame(newframe)
Tim Peters2344fae2001-01-15 00:50:52 +0000817 do_u = do_up
818
819 def do_down(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000820 """d(own) [count]
821 Move the current frame count (default one) levels down in the
822 stack trace (to a newer frame).
823 """
Tim Peters2344fae2001-01-15 00:50:52 +0000824 if self.curindex + 1 == len(self.stack):
Georg Brandl0d089622010-07-30 16:00:46 +0000825 self.error('Newest frame')
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000826 return
827 try:
828 count = int(arg or 1)
829 except ValueError:
Georg Brandl0d089622010-07-30 16:00:46 +0000830 self.error('Invalid frame count (%s)' % arg)
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000831 return
832 if count < 0:
833 newframe = len(self.stack) - 1
Tim Peters2344fae2001-01-15 00:50:52 +0000834 else:
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000835 newframe = min(len(self.stack) - 1, self.curindex + count)
836 self._select_frame(newframe)
Tim Peters2344fae2001-01-15 00:50:52 +0000837 do_d = do_down
838
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000839 def do_until(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000840 """unt(il) [lineno]
841 Without argument, continue execution until the line with a
842 number greater than the current one is reached. With a line
843 number, continue execution until a line with a number greater
844 or equal to that is reached. In both cases, also stop when
845 the current frame returns.
846 """
Georg Brandl2dfec552010-07-30 08:43:32 +0000847 if arg:
848 try:
849 lineno = int(arg)
850 except ValueError:
Georg Brandl0d089622010-07-30 16:00:46 +0000851 self.error('Error in argument: %r' % arg)
Georg Brandl2dfec552010-07-30 08:43:32 +0000852 return
853 if lineno <= self.curframe.f_lineno:
Georg Brandl0d089622010-07-30 16:00:46 +0000854 self.error('"until" line number is smaller than current '
855 'line number')
Georg Brandl2dfec552010-07-30 08:43:32 +0000856 return
857 else:
858 lineno = None
859 self.set_until(self.curframe, lineno)
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000860 return 1
861 do_unt = do_until
862
Tim Peters2344fae2001-01-15 00:50:52 +0000863 def do_step(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000864 """s(tep)
865 Execute the current line, stop at the first possible occasion
866 (either in a function that is called or in the current
867 function).
868 """
Tim Peters2344fae2001-01-15 00:50:52 +0000869 self.set_step()
870 return 1
871 do_s = do_step
872
873 def do_next(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000874 """n(ext)
875 Continue execution until the next line in the current function
876 is reached or it returns.
877 """
Tim Peters2344fae2001-01-15 00:50:52 +0000878 self.set_next(self.curframe)
879 return 1
880 do_n = do_next
881
Guido van Rossumd8faa362007-04-27 19:54:29 +0000882 def do_run(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000883 """run [args...]
884 Restart the debugged python program. If a string is supplied
885 it is splitted with "shlex", and the result is used as the new
886 sys.argv. History, breakpoints, actions and debugger options
887 are preserved. "restart" is an alias for "run".
888 """
Guido van Rossumd8faa362007-04-27 19:54:29 +0000889 if arg:
890 import shlex
891 argv0 = sys.argv[0:1]
892 sys.argv = shlex.split(arg)
893 sys.argv[:0] = argv0
Georg Brandl0d089622010-07-30 16:00:46 +0000894 # this is caught in the main debugger loop
Guido van Rossumd8faa362007-04-27 19:54:29 +0000895 raise Restart
896
897 do_restart = do_run
898
Tim Peters2344fae2001-01-15 00:50:52 +0000899 def do_return(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000900 """r(eturn)
901 Continue execution until the current function returns.
902 """
Tim Peters2344fae2001-01-15 00:50:52 +0000903 self.set_return(self.curframe)
904 return 1
905 do_r = do_return
906
907 def do_continue(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000908 """c(ont(inue))
909 Continue execution, only stop when a breakpoint is encountered.
910 """
Tim Peters2344fae2001-01-15 00:50:52 +0000911 self.set_continue()
912 return 1
913 do_c = do_cont = do_continue
914
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000915 def do_jump(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000916 """j(ump) lineno
917 Set the next line that will be executed. Only available in
918 the bottom-most frame. This lets you jump back and execute
919 code again, or jump forward to skip code that you don't want
920 to run.
921
922 It should be noted that not all jumps are allowed -- for
923 instance it is not possible to jump into the middle of a
924 for loop or out of a finally clause.
925 """
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000926 if self.curindex + 1 != len(self.stack):
Georg Brandl0d089622010-07-30 16:00:46 +0000927 self.error('You can only jump within the bottom frame')
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000928 return
929 try:
930 arg = int(arg)
931 except ValueError:
Georg Brandl0d089622010-07-30 16:00:46 +0000932 self.error("The 'jump' command requires a line number")
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000933 else:
934 try:
935 # Do the jump, fix up our copy of the stack, and display the
936 # new position
937 self.curframe.f_lineno = arg
938 self.stack[self.curindex] = self.stack[self.curindex][0], arg
939 self.print_stack_entry(self.stack[self.curindex])
Guido van Rossumb940e112007-01-10 16:19:56 +0000940 except ValueError as e:
Georg Brandl0d089622010-07-30 16:00:46 +0000941 self.error('Jump failed: %s' % e)
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000942 do_j = do_jump
943
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000944 def do_debug(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000945 """debug code
946 Enter a recursive debugger that steps through the code
947 argument (which is an arbitrary expression or statement to be
948 executed in the current environment).
949 """
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000950 sys.settrace(None)
951 globals = self.curframe.f_globals
Benjamin Petersond23f8222009-04-05 19:13:16 +0000952 locals = self.curframe_locals
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000953 p = Pdb(self.completekey, self.stdin, self.stdout)
Guido van Rossumed538d82003-04-09 19:36:34 +0000954 p.prompt = "(%s) " % self.prompt.strip()
Georg Brandl0d089622010-07-30 16:00:46 +0000955 self.message("ENTERING RECURSIVE DEBUGGER")
Guido van Rossumed538d82003-04-09 19:36:34 +0000956 sys.call_tracing(p.run, (arg, globals, locals))
Georg Brandl0d089622010-07-30 16:00:46 +0000957 self.message("LEAVING RECURSIVE DEBUGGER")
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000958 sys.settrace(self.trace_dispatch)
959 self.lastcmd = p.lastcmd
960
Tim Peters2344fae2001-01-15 00:50:52 +0000961 def do_quit(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000962 """q(uit)\nexit
963 Quit from the debugger. The program being executed is aborted.
964 """
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000965 self._user_requested_quit = 1
Tim Peters2344fae2001-01-15 00:50:52 +0000966 self.set_quit()
967 return 1
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000968
Tim Peters2344fae2001-01-15 00:50:52 +0000969 do_q = do_quit
Guido van Rossumd1c08f32002-04-15 00:48:24 +0000970 do_exit = do_quit
Tim Peters2344fae2001-01-15 00:50:52 +0000971
Guido van Rossumeef26072003-01-13 21:13:55 +0000972 def do_EOF(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000973 """EOF
974 Handles the receipt of EOF as a command.
975 """
976 self.message('')
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000977 self._user_requested_quit = 1
Guido van Rossumeef26072003-01-13 21:13:55 +0000978 self.set_quit()
979 return 1
980
Tim Peters2344fae2001-01-15 00:50:52 +0000981 def do_args(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000982 """a(rgs)
983 Print the argument list of the current function.
984 """
Benjamin Petersond23f8222009-04-05 19:13:16 +0000985 co = self.curframe.f_code
986 dict = self.curframe_locals
Tim Peters2344fae2001-01-15 00:50:52 +0000987 n = co.co_argcount
988 if co.co_flags & 4: n = n+1
989 if co.co_flags & 8: n = n+1
990 for i in range(n):
991 name = co.co_varnames[i]
Georg Brandl0d089622010-07-30 16:00:46 +0000992 if name in dict:
993 self.message('%s = %r' % (name, dict[name]))
994 else:
995 self.message('%s = *** undefined ***' % (name,))
Tim Peters2344fae2001-01-15 00:50:52 +0000996 do_a = do_args
Guido van Rossum2424f851998-09-11 22:50:09 +0000997
Tim Peters2344fae2001-01-15 00:50:52 +0000998 def do_retval(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000999 """retval
1000 Print the return value for the last return of a function.
1001 """
Benjamin Petersond23f8222009-04-05 19:13:16 +00001002 if '__return__' in self.curframe_locals:
Georg Brandl0d089622010-07-30 16:00:46 +00001003 self.message(repr(self.curframe_locals['__return__']))
Tim Peters2344fae2001-01-15 00:50:52 +00001004 else:
Georg Brandl0d089622010-07-30 16:00:46 +00001005 self.error('Not yet returned!')
Tim Peters2344fae2001-01-15 00:50:52 +00001006 do_rv = do_retval
Guido van Rossum2424f851998-09-11 22:50:09 +00001007
Barry Warsaw210bd202002-11-05 22:40:20 +00001008 def _getval(self, arg):
Tim Peters2344fae2001-01-15 00:50:52 +00001009 try:
Benjamin Petersond23f8222009-04-05 19:13:16 +00001010 return eval(arg, self.curframe.f_globals, self.curframe_locals)
Tim Peters2344fae2001-01-15 00:50:52 +00001011 except:
Georg Brandl0d089622010-07-30 16:00:46 +00001012 exc_info = sys.exc_info()[:2]
1013 self.error(traceback.format_exception_only(*exc_info)[-1].strip())
Barry Warsaw210bd202002-11-05 22:40:20 +00001014 raise
Guido van Rossum2424f851998-09-11 22:50:09 +00001015
Barry Warsaw210bd202002-11-05 22:40:20 +00001016 def do_p(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001017 """p(rint) expression
1018 Print the value of the expression.
1019 """
Barry Warsaw210bd202002-11-05 22:40:20 +00001020 try:
Georg Brandl0d089622010-07-30 16:00:46 +00001021 self.message(repr(self._getval(arg)))
Barry Warsaw210bd202002-11-05 22:40:20 +00001022 except:
1023 pass
Georg Brandlc9879242007-09-04 07:07:56 +00001024 # make "print" an alias of "p" since print isn't a Python statement anymore
1025 do_print = do_p
Barry Warsaw210bd202002-11-05 22:40:20 +00001026
1027 def do_pp(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001028 """pp expression
1029 Pretty-print the value of the expression.
1030 """
Barry Warsaw210bd202002-11-05 22:40:20 +00001031 try:
Georg Brandl0d089622010-07-30 16:00:46 +00001032 self.message(pprint.pformat(self._getval(arg)))
Barry Warsaw210bd202002-11-05 22:40:20 +00001033 except:
1034 pass
Guido van Rossum2424f851998-09-11 22:50:09 +00001035
Tim Peters2344fae2001-01-15 00:50:52 +00001036 def do_list(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001037 """l(ist) [first [,last] | .]
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001038
1039 List source code for the current file. Without arguments,
1040 list 11 lines around the current line or continue the previous
1041 listing. With . as argument, list 11 lines around the current
1042 line. With one argument, list 11 lines starting at that line.
1043 With two arguments, list the given range; if the second
1044 argument is less than the first, it is a count.
1045
1046 The current line in the current frame is indicated by "->".
1047 If an exception is being debugged, the line where the
1048 exception was originally raised or propagated is indicated by
1049 ">>", if it differs from the current line.
Georg Brandl0d089622010-07-30 16:00:46 +00001050 """
Tim Peters2344fae2001-01-15 00:50:52 +00001051 self.lastcmd = 'list'
1052 last = None
Georg Brandla91a94b2010-07-30 07:14:01 +00001053 if arg and arg != '.':
Tim Peters2344fae2001-01-15 00:50:52 +00001054 try:
Georg Brandl0d089622010-07-30 16:00:46 +00001055 if ',' in arg:
1056 first, last = arg.split(',')
1057 first = int(first.strip())
1058 last = int(last.strip())
Tim Peters2344fae2001-01-15 00:50:52 +00001059 if last < first:
Georg Brandl0d089622010-07-30 16:00:46 +00001060 # assume it's a count
Tim Peters2344fae2001-01-15 00:50:52 +00001061 last = first + last
1062 else:
Georg Brandl0d089622010-07-30 16:00:46 +00001063 first = int(arg.strip())
1064 first = max(1, first - 5)
1065 except ValueError:
1066 self.error('Error in argument: %r' % arg)
Tim Peters2344fae2001-01-15 00:50:52 +00001067 return
Georg Brandla91a94b2010-07-30 07:14:01 +00001068 elif self.lineno is None or arg == '.':
Tim Peters2344fae2001-01-15 00:50:52 +00001069 first = max(1, self.curframe.f_lineno - 5)
1070 else:
1071 first = self.lineno + 1
1072 if last is None:
1073 last = first + 10
1074 filename = self.curframe.f_code.co_filename
1075 breaklist = self.get_file_breaks(filename)
1076 try:
Georg Brandle59ca2a2010-07-30 17:04:28 +00001077 lines = linecache.getlines(filename, self.curframe.f_globals)
1078 self._print_lines(lines[first-1:last], first, breaklist,
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001079 self.curframe)
Georg Brandle59ca2a2010-07-30 17:04:28 +00001080 self.lineno = min(last, len(lines))
1081 if len(lines) < last:
1082 self.message('[EOF]')
Tim Peters2344fae2001-01-15 00:50:52 +00001083 except KeyboardInterrupt:
1084 pass
1085 do_l = do_list
Guido van Rossum2424f851998-09-11 22:50:09 +00001086
Georg Brandle59ca2a2010-07-30 17:04:28 +00001087 def do_longlist(self, arg):
1088 """longlist | ll
1089 List the whole source code for the current function or frame.
1090 """
1091 filename = self.curframe.f_code.co_filename
1092 breaklist = self.get_file_breaks(filename)
1093 try:
Georg Brandl5ed2b5a2010-07-30 18:08:12 +00001094 lines, lineno = getsourcelines(self.curframe)
Georg Brandle59ca2a2010-07-30 17:04:28 +00001095 except IOError as err:
1096 self.error(err)
1097 return
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001098 self._print_lines(lines, lineno, breaklist, self.curframe)
Georg Brandle59ca2a2010-07-30 17:04:28 +00001099 do_ll = do_longlist
1100
1101 def do_source(self, arg):
1102 """source expression
1103 Try to get source code for the given object and display it.
1104 """
1105 try:
1106 obj = self._getval(arg)
1107 except:
1108 return
1109 try:
Georg Brandl5ed2b5a2010-07-30 18:08:12 +00001110 lines, lineno = getsourcelines(obj)
Georg Brandle59ca2a2010-07-30 17:04:28 +00001111 except (IOError, TypeError) as err:
1112 self.error(err)
1113 return
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001114 self._print_lines(lines, lineno)
Georg Brandle59ca2a2010-07-30 17:04:28 +00001115
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001116 def _print_lines(self, lines, start, breaks=(), frame=None):
Georg Brandle59ca2a2010-07-30 17:04:28 +00001117 """Print a range of lines."""
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001118 if frame:
1119 current_lineno = frame.f_lineno
1120 exc_lineno = self.tb_lineno.get(frame, -1)
1121 else:
1122 current_lineno = exc_lineno = -1
Georg Brandle59ca2a2010-07-30 17:04:28 +00001123 for lineno, line in enumerate(lines, start):
1124 s = str(lineno).rjust(3)
1125 if len(s) < 4:
1126 s += ' '
1127 if lineno in breaks:
1128 s += 'B'
1129 else:
1130 s += ' '
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001131 if lineno == current_lineno:
Georg Brandle59ca2a2010-07-30 17:04:28 +00001132 s += '->'
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001133 elif lineno == exc_lineno:
Georg Brandle59ca2a2010-07-30 17:04:28 +00001134 s += '>>'
1135 self.message(s + '\t' + line.rstrip())
1136
Tim Peters2344fae2001-01-15 00:50:52 +00001137 def do_whatis(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001138 """whatis arg
1139 Print the type of the argument.
1140 """
Tim Peters2344fae2001-01-15 00:50:52 +00001141 try:
Georg Brandl0d089622010-07-30 16:00:46 +00001142 value = self._getval(arg)
Tim Peters2344fae2001-01-15 00:50:52 +00001143 except:
Georg Brandl0d089622010-07-30 16:00:46 +00001144 # _getval() already printed the error
Tim Peters2344fae2001-01-15 00:50:52 +00001145 return
1146 code = None
1147 # Is it a function?
Georg Brandl0d089622010-07-30 16:00:46 +00001148 try:
1149 code = value.__code__
1150 except Exception:
1151 pass
Tim Peters2344fae2001-01-15 00:50:52 +00001152 if code:
Georg Brandl0d089622010-07-30 16:00:46 +00001153 self.message('Function %s' % code.co_name)
Tim Peters2344fae2001-01-15 00:50:52 +00001154 return
1155 # Is it an instance method?
Georg Brandl0d089622010-07-30 16:00:46 +00001156 try:
1157 code = value.__func__.__code__
1158 except Exception:
1159 pass
Tim Peters2344fae2001-01-15 00:50:52 +00001160 if code:
Georg Brandl0d089622010-07-30 16:00:46 +00001161 self.message('Method %s' % code.co_name)
1162 return
1163 # Is it a class?
1164 if value.__class__ is type:
1165 self.message('Class %s.%s' % (value.__module__, value.__name__))
Tim Peters2344fae2001-01-15 00:50:52 +00001166 return
1167 # None of the above...
Georg Brandl0d089622010-07-30 16:00:46 +00001168 self.message(type(value))
Guido van Rossum8e2ec561993-07-29 09:37:38 +00001169
Tim Peters2344fae2001-01-15 00:50:52 +00001170 def do_alias(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001171 """alias [name [command [parameter parameter ...] ]]
1172 Create an alias called 'name' that executes 'command'. The
1173 command must *not* be enclosed in quotes. Replaceable
1174 parameters can be indicated by %1, %2, and so on, while %* is
1175 replaced by all the parameters. If no command is given, the
1176 current alias for name is shown. If no name is given, all
1177 aliases are listed.
1178
1179 Aliases may be nested and can contain anything that can be
1180 legally typed at the pdb prompt. Note! You *can* override
1181 internal pdb commands with aliases! Those internal commands
1182 are then hidden until the alias is removed. Aliasing is
1183 recursively applied to the first word of the command line; all
1184 other words in the line are left alone.
1185
1186 As an example, here are two useful aliases (especially when
1187 placed in the .pdbrc file):
1188
1189 # Print instance variables (usage "pi classInst")
1190 alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
1191 # Print instance variables in self
1192 alias ps pi self
1193 """
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +00001194 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +00001195 if len(args) == 0:
Benjamin Petersonbe74a372009-09-11 21:17:13 +00001196 keys = sorted(self.aliases.keys())
Tim Peters2344fae2001-01-15 00:50:52 +00001197 for alias in keys:
Georg Brandl0d089622010-07-30 16:00:46 +00001198 self.message("%s = %s" % (alias, self.aliases[alias]))
Tim Peters2344fae2001-01-15 00:50:52 +00001199 return
Guido van Rossum08454592002-07-12 13:10:53 +00001200 if args[0] in self.aliases and len(args) == 1:
Georg Brandl0d089622010-07-30 16:00:46 +00001201 self.message("%s = %s" % (args[0], self.aliases[args[0]]))
Tim Peters2344fae2001-01-15 00:50:52 +00001202 else:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +00001203 self.aliases[args[0]] = ' '.join(args[1:])
Guido van Rossum23efba41992-01-27 16:58:47 +00001204
Tim Peters2344fae2001-01-15 00:50:52 +00001205 def do_unalias(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001206 """unalias name
1207 Delete the specified alias.
1208 """
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +00001209 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +00001210 if len(args) == 0: return
Raymond Hettinger54f02222002-06-01 14:18:47 +00001211 if args[0] in self.aliases:
Tim Peters2344fae2001-01-15 00:50:52 +00001212 del self.aliases[args[0]]
Guido van Rossum00230781993-03-29 11:39:45 +00001213
Georg Brandl0d089622010-07-30 16:00:46 +00001214 # List of all the commands making the program resume execution.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001215 commands_resuming = ['do_continue', 'do_step', 'do_next', 'do_return',
1216 'do_quit', 'do_jump']
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001217
Tim Peters2344fae2001-01-15 00:50:52 +00001218 # Print a traceback starting at the top stack frame.
1219 # The most recently entered frame is printed last;
1220 # this is different from dbx and gdb, but consistent with
1221 # the Python interpreter's stack trace.
1222 # It is also consistent with the up/down commands (which are
1223 # compatible with dbx and gdb: up moves towards 'main()'
1224 # and down moves towards the most recent stack frame).
Guido van Rossum2424f851998-09-11 22:50:09 +00001225
Tim Peters2344fae2001-01-15 00:50:52 +00001226 def print_stack_trace(self):
1227 try:
1228 for frame_lineno in self.stack:
1229 self.print_stack_entry(frame_lineno)
1230 except KeyboardInterrupt:
1231 pass
Guido van Rossum2424f851998-09-11 22:50:09 +00001232
Tim Peters2344fae2001-01-15 00:50:52 +00001233 def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix):
1234 frame, lineno = frame_lineno
1235 if frame is self.curframe:
Georg Brandl0d089622010-07-30 16:00:46 +00001236 prefix = '> '
Tim Peters2344fae2001-01-15 00:50:52 +00001237 else:
Georg Brandl0d089622010-07-30 16:00:46 +00001238 prefix = ' '
1239 self.message(prefix +
1240 self.format_stack_entry(frame_lineno, prompt_prefix))
Guido van Rossum2424f851998-09-11 22:50:09 +00001241
Georg Brandl0d089622010-07-30 16:00:46 +00001242 # Provide help
Guido van Rossum921c8241992-01-10 14:54:42 +00001243
Georg Brandl0d089622010-07-30 16:00:46 +00001244 def do_help(self, arg):
1245 """h(elp)
1246 Without argument, print the list of available commands.
1247 With a command name as argument, print help about that command.
1248 "help pdb" shows the full pdb documentation.
1249 "help exec" gives help on the ! command.
1250 """
1251 if not arg:
1252 return cmd.Cmd.do_help(self, arg)
1253 try:
1254 try:
1255 topic = getattr(self, 'help_' + arg)
1256 return topic()
1257 except AttributeError:
1258 command = getattr(self, 'do_' + arg)
1259 except AttributeError:
1260 self.error('No help for %r' % arg)
1261 else:
Georg Brandl9e7dbc82010-10-14 07:14:31 +00001262 if sys.flags.optimize >= 2:
1263 self.error('No help for %r; please do not run Python with -OO '
1264 'if you need command help' % arg)
1265 return
Georg Brandl0d089622010-07-30 16:00:46 +00001266 self.message(command.__doc__.rstrip())
Guido van Rossum921c8241992-01-10 14:54:42 +00001267
Georg Brandl0d089622010-07-30 16:00:46 +00001268 do_h = do_help
Barry Warsaw210bd202002-11-05 22:40:20 +00001269
Tim Peters2344fae2001-01-15 00:50:52 +00001270 def help_exec(self):
Georg Brandl0d089622010-07-30 16:00:46 +00001271 """(!) statement
1272 Execute the (one-line) statement in the context of the current
1273 stack frame. The exclamation point can be omitted unless the
1274 first word of the statement resembles a debugger command. To
1275 assign to a global variable you must always prefix the command
1276 with a 'global' command, e.g.:
1277 (Pdb) global list_options; list_options = ['-l']
1278 (Pdb)
1279 """
Georg Brandl9e7dbc82010-10-14 07:14:31 +00001280 self.message((self.help_exec.__doc__ or '').strip())
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001281
Tim Peters2344fae2001-01-15 00:50:52 +00001282 def help_pdb(self):
1283 help()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001284
Georg Brandl0d089622010-07-30 16:00:46 +00001285 # other helper functions
1286
Tim Peters2344fae2001-01-15 00:50:52 +00001287 def lookupmodule(self, filename):
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001288 """Helper function for break/clear parsing -- may be overridden.
1289
1290 lookupmodule() translates (possibly incomplete) file or module name
1291 into an absolute file name.
1292 """
1293 if os.path.isabs(filename) and os.path.exists(filename):
Tim Peterse718f612004-10-12 21:51:32 +00001294 return filename
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001295 f = os.path.join(sys.path[0], filename)
1296 if os.path.exists(f) and self.canonic(f) == self.mainpyfile:
1297 return f
Tim Peters2344fae2001-01-15 00:50:52 +00001298 root, ext = os.path.splitext(filename)
1299 if ext == '':
1300 filename = filename + '.py'
1301 if os.path.isabs(filename):
1302 return filename
1303 for dirname in sys.path:
1304 while os.path.islink(dirname):
1305 dirname = os.readlink(dirname)
1306 fullname = os.path.join(dirname, filename)
1307 if os.path.exists(fullname):
1308 return fullname
1309 return None
Guido van Rossumb5699c71998-07-20 23:13:54 +00001310
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001311 def _runscript(self, filename):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001312 # The script has to run in __main__ namespace (or imports from
1313 # __main__ will break).
1314 #
1315 # So we clear up the __main__ and set several special variables
1316 # (this gets rid of pdb's globals and cleans old variables on restarts).
1317 import __main__
1318 __main__.__dict__.clear()
1319 __main__.__dict__.update({"__name__" : "__main__",
1320 "__file__" : filename,
1321 "__builtins__": __builtins__,
1322 })
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001323
1324 # When bdb sets tracing, a number of call and line events happens
1325 # BEFORE debugger even reaches user's code (and the exact sequence of
1326 # events depends on python version). So we take special measures to
1327 # avoid stopping before we reach the main script (see user_line and
1328 # user_call for details).
1329 self._wait_for_mainpyfile = 1
1330 self.mainpyfile = self.canonic(filename)
1331 self._user_requested_quit = 0
Georg Brandld07ac642009-08-13 07:50:57 +00001332 with open(filename, "rb") as fp:
1333 statement = "exec(compile(%r, %r, 'exec'))" % \
1334 (fp.read(), self.mainpyfile)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001335 self.run(statement)
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001336
Georg Brandl9e7dbc82010-10-14 07:14:31 +00001337# Collect all command help into docstring, if not run with -OO
Georg Brandl0d089622010-07-30 16:00:46 +00001338
Georg Brandl9e7dbc82010-10-14 07:14:31 +00001339if __doc__ is not None:
1340 # unfortunately we can't guess this order from the class definition
1341 _help_order = [
1342 'help', 'where', 'down', 'up', 'break', 'tbreak', 'clear', 'disable',
1343 'enable', 'ignore', 'condition', 'commands', 'step', 'next', 'until',
1344 'jump', 'return', 'retval', 'run', 'continue', 'list', 'longlist',
1345 'args', 'print', 'pp', 'whatis', 'source', 'alias', 'unalias',
1346 'debug', 'quit',
1347 ]
Georg Brandl0d089622010-07-30 16:00:46 +00001348
Georg Brandl9e7dbc82010-10-14 07:14:31 +00001349 for _command in _help_order:
1350 __doc__ += getattr(Pdb, 'do_' + _command).__doc__.strip() + '\n\n'
1351 __doc__ += Pdb.help_exec.__doc__
Georg Brandl0d089622010-07-30 16:00:46 +00001352
Georg Brandl9e7dbc82010-10-14 07:14:31 +00001353 del _help_order, _command
1354
Georg Brandl0d089622010-07-30 16:00:46 +00001355
Guido van Rossum35771131992-09-08 11:59:04 +00001356# Simplified interface
1357
Guido van Rossum5e38b6f1995-02-27 13:13:40 +00001358def run(statement, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +00001359 Pdb().run(statement, globals, locals)
Guido van Rossum5e38b6f1995-02-27 13:13:40 +00001360
1361def runeval(expression, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +00001362 return Pdb().runeval(expression, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001363
1364def runctx(statement, globals, locals):
Tim Peters2344fae2001-01-15 00:50:52 +00001365 # B/W compatibility
1366 run(statement, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001367
Raymond Hettinger2ef7e6c2004-10-24 00:32:24 +00001368def runcall(*args, **kwds):
1369 return Pdb().runcall(*args, **kwds)
Guido van Rossum4e160981992-09-02 20:43:20 +00001370
Guido van Rossumb6775db1994-08-01 11:34:53 +00001371def set_trace():
Johannes Gijsbers84a6c202004-11-07 11:35:30 +00001372 Pdb().set_trace(sys._getframe().f_back)
Guido van Rossum35771131992-09-08 11:59:04 +00001373
1374# Post-Mortem interface
1375
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001376def post_mortem(t=None):
1377 # handling the default
1378 if t is None:
1379 # sys.exc_info() returns (type, value, traceback) if an exception is
1380 # being handled, otherwise it returns None
1381 t = sys.exc_info()[2]
Georg Brandl0d089622010-07-30 16:00:46 +00001382 if t is None:
1383 raise ValueError("A valid traceback must be passed if no "
1384 "exception is being handled")
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001385
Tim Peters2344fae2001-01-15 00:50:52 +00001386 p = Pdb()
1387 p.reset()
Benjamin Peterson1a6e0d02008-10-25 15:49:17 +00001388 p.interaction(None, t)
Guido van Rossum35771131992-09-08 11:59:04 +00001389
1390def pm():
Tim Peters2344fae2001-01-15 00:50:52 +00001391 post_mortem(sys.last_traceback)
Guido van Rossum35771131992-09-08 11:59:04 +00001392
1393
1394# Main program for testing
1395
Guido van Rossum23efba41992-01-27 16:58:47 +00001396TESTCMD = 'import x; x.main()'
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001397
Guido van Rossum921c8241992-01-10 14:54:42 +00001398def test():
Tim Peters2344fae2001-01-15 00:50:52 +00001399 run(TESTCMD)
Guido van Rossume61fa0a1993-10-22 13:56:35 +00001400
1401# print help
1402def help():
Georg Brandl02053ee2010-07-18 10:11:03 +00001403 import pydoc
1404 pydoc.pager(__doc__)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001405
Georg Brandle0230912010-07-30 08:29:39 +00001406_usage = """\
1407usage: pdb.py [-c command] ... pyfile [arg] ...
1408
1409Debug the Python program given by pyfile.
1410
1411Initial commands are read from .pdbrc files in your home directory
1412and in the current directory, if they exist. Commands supplied with
1413-c are executed after commands from .pdbrc files.
1414
1415To let the script run until an exception occurs, use "-c continue".
Georg Brandl2dfec552010-07-30 08:43:32 +00001416To let the script run up to a given line X in the debugged file, use
1417"-c 'until X'"."""
Georg Brandle0230912010-07-30 08:29:39 +00001418
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001419def main():
Georg Brandle0230912010-07-30 08:29:39 +00001420 import getopt
1421
1422 opts, args = getopt.getopt(sys.argv[1:], 'hc:', ['--help', '--command='])
1423
1424 if not args:
1425 print(_usage)
Tim Peters2344fae2001-01-15 00:50:52 +00001426 sys.exit(2)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001427
Georg Brandle0230912010-07-30 08:29:39 +00001428 commands = []
1429 for opt, optarg in opts:
1430 if opt in ['-h', '--help']:
1431 print(_usage)
1432 sys.exit()
1433 elif opt in ['-c', '--command']:
1434 commands.append(optarg)
1435
1436 mainpyfile = args[0] # Get script filename
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001437 if not os.path.exists(mainpyfile):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001438 print('Error:', mainpyfile, 'does not exist')
Tim Peters2344fae2001-01-15 00:50:52 +00001439 sys.exit(1)
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001440
Georg Brandle0230912010-07-30 08:29:39 +00001441 sys.argv[:] = args # Hide "pdb.py" and pdb options from argument list
Guido van Rossumec577d51996-09-10 17:39:34 +00001442
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001443 # Replace pdb's dir with script's dir in front of module search path.
1444 sys.path[0] = os.path.dirname(mainpyfile)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001445
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001446 # Note on saving/restoring sys.argv: it's a good idea when sys.argv was
1447 # modified by the script being debugged. It's a bad idea when it was
Georg Brandl3078df02009-05-05 09:11:31 +00001448 # changed by the user from the command line. There is a "restart" command
1449 # which allows explicit specification of command line arguments.
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001450 pdb = Pdb()
Georg Brandle0230912010-07-30 08:29:39 +00001451 pdb.rcLines.extend(commands)
Georg Brandl1e30bd32010-07-30 07:21:26 +00001452 while True:
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001453 try:
1454 pdb._runscript(mainpyfile)
1455 if pdb._user_requested_quit:
1456 break
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001457 print("The program finished and will be restarted")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001458 except Restart:
1459 print("Restarting", mainpyfile, "with arguments:")
Georg Brandle0230912010-07-30 08:29:39 +00001460 print("\t" + " ".join(args))
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001461 except SystemExit:
1462 # In most cases SystemExit does not warrant a post-mortem session.
Georg Brandle0230912010-07-30 08:29:39 +00001463 print("The program exited via sys.exit(). Exit status:", end=' ')
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001464 print(sys.exc_info()[1])
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001465 except:
1466 traceback.print_exc()
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001467 print("Uncaught exception. Entering post mortem debugging")
1468 print("Running 'cont' or 'step' will restart the program")
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001469 t = sys.exc_info()[2]
Benjamin Peterson1a6e0d02008-10-25 15:49:17 +00001470 pdb.interaction(None, t)
Georg Brandl3078df02009-05-05 09:11:31 +00001471 print("Post mortem debugger finished. The " + mainpyfile +
1472 " will be restarted")
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001473
1474
1475# When invoked as main program, invoke the debugger on a script
Guido van Rossumd8faa362007-04-27 19:54:29 +00001476if __name__ == '__main__':
1477 import pdb
1478 pdb.main()