blob: afe69d276fa7a1ce338bd95483d93f15478d442e [file] [log] [blame]
Guido van Rossumf06ee5f1996-11-27 19:52:01 +00001#! /usr/bin/env python
Guido van Rossumf17361d1996-07-30 16:28:13 +00002
Guido van Rossum4b8c6ea2000-02-04 15:39:30 +00003"""A Python debugger."""
Guido van Rossum92df0c61992-01-14 18:30:15 +00004
Guido van Rossum23efba41992-01-27 16:58:47 +00005# (See pdb.doc for documentation.)
Guido van Rossum921c8241992-01-10 14:54:42 +00006
Guido van Rossum921c8241992-01-10 14:54:42 +00007import sys
8import linecache
Guido van Rossum23efba41992-01-27 16:58:47 +00009import cmd
10import bdb
Guido van Rossumef1b41b2002-09-10 21:57:14 +000011from repr import Repr
Guido van Rossumb5699c71998-07-20 23:13:54 +000012import os
Barry Warsaw2bee8fe1999-09-09 16:32:41 +000013import re
Barry Warsaw210bd202002-11-05 22:40:20 +000014import pprint
Johannes Gijsbers25b38c82004-10-12 18:12:09 +000015import traceback
Guido van Rossumef1b41b2002-09-10 21:57:14 +000016# Create a custom safe Repr instance and increase its maxstring.
17# The default of 30 truncates error messages too easily.
18_repr = Repr()
19_repr.maxstring = 200
20_saferepr = _repr.repr
21
Skip Montanaro352674d2001-02-07 23:14:30 +000022__all__ = ["run", "pm", "Pdb", "runeval", "runctx", "runcall", "set_trace",
23 "post_mortem", "help"]
24
Neal Norwitzce96f692006-03-17 06:49:51 +000025def raw_input(prompt):
26 sys.stdout.write(prompt)
27 sys.stdout.flush()
28 return sys.stdin.readline()
29
Barry Warsaw2bee8fe1999-09-09 16:32:41 +000030def find_function(funcname, filename):
Thomas Wouters89f507f2006-12-13 04:49:30 +000031 cre = re.compile(r'def\s+%s\s*[(]' % re.escape(funcname))
Tim Peters2344fae2001-01-15 00:50:52 +000032 try:
33 fp = open(filename)
34 except IOError:
35 return None
36 # consumer of this info expects the first line to be 1
37 lineno = 1
38 answer = None
39 while 1:
40 line = fp.readline()
41 if line == '':
42 break
43 if cre.match(line):
44 answer = funcname, filename, lineno
45 break
46 lineno = lineno + 1
47 fp.close()
48 return answer
Guido van Rossum921c8241992-01-10 14:54:42 +000049
50
Guido van Rossuma558e371994-11-10 22:27:35 +000051# Interaction prompt line will separate file and call info from code
52# text using value of line_prefix string. A newline and arrow may
53# be to your liking. You can set it once pdb is imported using the
54# command "pdb.line_prefix = '\n% '".
Tim Peters2344fae2001-01-15 00:50:52 +000055# line_prefix = ': ' # Use this to get the old situation back
56line_prefix = '\n-> ' # Probably a better default
Guido van Rossuma558e371994-11-10 22:27:35 +000057
Guido van Rossum23efba41992-01-27 16:58:47 +000058class Pdb(bdb.Bdb, cmd.Cmd):
Guido van Rossum2424f851998-09-11 22:50:09 +000059
Thomas Wouters477c8d52006-05-27 19:21:47 +000060 def __init__(self, completekey='tab', stdin=None, stdout=None):
Tim Peters2344fae2001-01-15 00:50:52 +000061 bdb.Bdb.__init__(self)
Thomas Wouters477c8d52006-05-27 19:21:47 +000062 cmd.Cmd.__init__(self, completekey, stdin, stdout)
63 if stdout:
64 self.use_rawinput = 0
Tim Peters2344fae2001-01-15 00:50:52 +000065 self.prompt = '(Pdb) '
66 self.aliases = {}
Johannes Gijsbers25b38c82004-10-12 18:12:09 +000067 self.mainpyfile = ''
68 self._wait_for_mainpyfile = 0
Tim Peters2344fae2001-01-15 00:50:52 +000069 # Try to load readline if it exists
70 try:
71 import readline
72 except ImportError:
73 pass
Guido van Rossum2424f851998-09-11 22:50:09 +000074
Tim Peters2344fae2001-01-15 00:50:52 +000075 # Read $HOME/.pdbrc and ./.pdbrc
76 self.rcLines = []
Raymond Hettinger54f02222002-06-01 14:18:47 +000077 if 'HOME' in os.environ:
Tim Peters2344fae2001-01-15 00:50:52 +000078 envHome = os.environ['HOME']
79 try:
80 rcFile = open(os.path.join(envHome, ".pdbrc"))
81 except IOError:
82 pass
83 else:
84 for line in rcFile.readlines():
85 self.rcLines.append(line)
86 rcFile.close()
87 try:
88 rcFile = open(".pdbrc")
89 except IOError:
90 pass
91 else:
92 for line in rcFile.readlines():
93 self.rcLines.append(line)
94 rcFile.close()
Guido van Rossum23efba41992-01-27 16:58:47 +000095
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000096 self.commands = {} # associates a command list to breakpoint numbers
97 self.commands_doprompt = {} # for each bp num, tells if the prompt must be disp. after execing the cmd list
98 self.commands_silent = {} # for each bp num, tells if the stack trace must be disp. after execing the cmd list
99 self.commands_defining = False # True while in the process of defining a command list
100 self.commands_bnum = None # The breakpoint number for which we are defining a list
101
Tim Peters2344fae2001-01-15 00:50:52 +0000102 def reset(self):
103 bdb.Bdb.reset(self)
104 self.forget()
Guido van Rossum23efba41992-01-27 16:58:47 +0000105
Tim Peters2344fae2001-01-15 00:50:52 +0000106 def forget(self):
107 self.lineno = None
108 self.stack = []
109 self.curindex = 0
110 self.curframe = None
Guido van Rossum2424f851998-09-11 22:50:09 +0000111
Tim Peters2344fae2001-01-15 00:50:52 +0000112 def setup(self, f, t):
113 self.forget()
114 self.stack, self.curindex = self.get_stack(f, t)
115 self.curframe = self.stack[self.curindex][0]
116 self.execRcLines()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000117
Tim Peters2344fae2001-01-15 00:50:52 +0000118 # Can be executed earlier than 'setup' if desired
119 def execRcLines(self):
120 if self.rcLines:
121 # Make local copy because of recursion
122 rcLines = self.rcLines
123 # executed only once
124 self.rcLines = []
125 for line in rcLines:
126 line = line[:-1]
Guido van Rossum08454592002-07-12 13:10:53 +0000127 if len(line) > 0 and line[0] != '#':
128 self.onecmd(line)
Guido van Rossum2424f851998-09-11 22:50:09 +0000129
Tim Peters280488b2002-08-23 18:19:30 +0000130 # Override Bdb methods
Michael W. Hudsondd32a912002-08-15 14:59:02 +0000131
132 def user_call(self, frame, argument_list):
133 """This method is called when there is the remote possibility
134 that we ever need to stop in this function."""
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000135 if self._wait_for_mainpyfile:
136 return
Michael W. Hudson01eb85c2003-01-31 17:48:29 +0000137 if self.stop_here(frame):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000138 print >>self.stdout, '--Call--'
Michael W. Hudson01eb85c2003-01-31 17:48:29 +0000139 self.interaction(frame, None)
Guido van Rossum2424f851998-09-11 22:50:09 +0000140
Tim Peters2344fae2001-01-15 00:50:52 +0000141 def user_line(self, frame):
142 """This function is called when we stop or break at this line."""
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000143 if self._wait_for_mainpyfile:
144 if (self.mainpyfile != self.canonic(frame.f_code.co_filename)
145 or frame.f_lineno<= 0):
146 return
147 self._wait_for_mainpyfile = 0
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000148 if self.bp_commands(frame):
149 self.interaction(frame, None)
150
151 def bp_commands(self,frame):
152 """ Call every command that was set for the current active breakpoint (if there is one)
153 Returns True if the normal interaction function must be called, False otherwise """
154 #self.currentbp is set in bdb.py in bdb.break_here if a breakpoint was hit
155 if getattr(self,"currentbp",False) and self.currentbp in self.commands:
156 currentbp = self.currentbp
157 self.currentbp = 0
158 lastcmd_back = self.lastcmd
159 self.setup(frame, None)
160 for line in self.commands[currentbp]:
161 self.onecmd(line)
162 self.lastcmd = lastcmd_back
163 if not self.commands_silent[currentbp]:
164 self.print_stack_entry(self.stack[self.curindex])
165 if self.commands_doprompt[currentbp]:
166 self.cmdloop()
167 self.forget()
168 return
169 return 1
Guido van Rossum9e1ee971997-07-11 13:43:53 +0000170
Tim Peters2344fae2001-01-15 00:50:52 +0000171 def user_return(self, frame, return_value):
172 """This function is called when a return trap is set here."""
173 frame.f_locals['__return__'] = return_value
Thomas Wouters477c8d52006-05-27 19:21:47 +0000174 print >>self.stdout, '--Return--'
Tim Peters2344fae2001-01-15 00:50:52 +0000175 self.interaction(frame, None)
Guido van Rossum2424f851998-09-11 22:50:09 +0000176
Tim Peters2344fae2001-01-15 00:50:52 +0000177 def user_exception(self, frame, (exc_type, exc_value, exc_traceback)):
178 """This function is called if an exception occurs,
179 but only if we are to stop at or just below this level."""
180 frame.f_locals['__exception__'] = exc_type, exc_value
181 if type(exc_type) == type(''):
182 exc_type_name = exc_type
183 else: exc_type_name = exc_type.__name__
Thomas Wouters477c8d52006-05-27 19:21:47 +0000184 print >>self.stdout, exc_type_name + ':', _saferepr(exc_value)
Tim Peters2344fae2001-01-15 00:50:52 +0000185 self.interaction(frame, exc_traceback)
Guido van Rossum2424f851998-09-11 22:50:09 +0000186
Tim Peters2344fae2001-01-15 00:50:52 +0000187 # General interaction function
188
189 def interaction(self, frame, traceback):
190 self.setup(frame, traceback)
191 self.print_stack_entry(self.stack[self.curindex])
192 self.cmdloop()
193 self.forget()
194
195 def default(self, line):
196 if line[:1] == '!': line = line[1:]
197 locals = self.curframe.f_locals
198 globals = self.curframe.f_globals
199 try:
200 code = compile(line + '\n', '<stdin>', 'single')
Georg Brandl7cae87c2006-09-06 06:51:57 +0000201 exec(code, globals, locals)
Tim Peters2344fae2001-01-15 00:50:52 +0000202 except:
203 t, v = sys.exc_info()[:2]
204 if type(t) == type(''):
205 exc_type_name = t
206 else: exc_type_name = t.__name__
Thomas Wouters477c8d52006-05-27 19:21:47 +0000207 print >>self.stdout, '***', exc_type_name + ':', v
Tim Peters2344fae2001-01-15 00:50:52 +0000208
209 def precmd(self, line):
210 """Handle alias expansion and ';;' separator."""
Guido van Rossum08454592002-07-12 13:10:53 +0000211 if not line.strip():
Tim Peters2344fae2001-01-15 00:50:52 +0000212 return line
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000213 args = line.split()
Raymond Hettinger54f02222002-06-01 14:18:47 +0000214 while args[0] in self.aliases:
Tim Peters2344fae2001-01-15 00:50:52 +0000215 line = self.aliases[args[0]]
216 ii = 1
217 for tmpArg in args[1:]:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000218 line = line.replace("%" + str(ii),
Tim Peters2344fae2001-01-15 00:50:52 +0000219 tmpArg)
220 ii = ii + 1
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000221 line = line.replace("%*", ' '.join(args[1:]))
222 args = line.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000223 # split into ';;' separated commands
224 # unless it's an alias command
225 if args[0] != 'alias':
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000226 marker = line.find(';;')
Tim Peters2344fae2001-01-15 00:50:52 +0000227 if marker >= 0:
228 # queue up everything after marker
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000229 next = line[marker+2:].lstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000230 self.cmdqueue.append(next)
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000231 line = line[:marker].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000232 return line
233
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000234 def onecmd(self, line):
235 """Interpret the argument as though it had been typed in response
236 to the prompt.
237
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000238 Checks whether this line is typed at the normal prompt or in
239 a breakpoint command list definition.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000240 """
241 if not self.commands_defining:
242 return cmd.Cmd.onecmd(self, line)
243 else:
244 return self.handle_command_def(line)
245
246 def handle_command_def(self,line):
247 """ Handles one command line during command list definition. """
248 cmd, arg, line = self.parseline(line)
249 if cmd == 'silent':
250 self.commands_silent[self.commands_bnum] = True
251 return # continue to handle other cmd def in the cmd list
252 elif cmd == 'end':
253 self.cmdqueue = []
254 return 1 # end of cmd list
255 cmdlist = self.commands[self.commands_bnum]
256 if (arg):
257 cmdlist.append(cmd+' '+arg)
258 else:
259 cmdlist.append(cmd)
260 # Determine if we must stop
261 try:
262 func = getattr(self, 'do_' + cmd)
263 except AttributeError:
264 func = self.default
265 if func.func_name in self.commands_resuming : # one of the resuming commands.
266 self.commands_doprompt[self.commands_bnum] = False
267 self.cmdqueue = []
268 return 1
269 return
270
Tim Peters2344fae2001-01-15 00:50:52 +0000271 # Command definitions, called by cmdloop()
272 # The argument is the remaining string on the command line
273 # Return true to exit from the command loop
274
275 do_h = cmd.Cmd.do_help
276
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000277 def do_commands(self, arg):
278 """Defines a list of commands associated to a breakpoint
279 Those commands will be executed whenever the breakpoint causes the program to stop execution."""
280 if not arg:
281 bnum = len(bdb.Breakpoint.bpbynumber)-1
282 else:
283 try:
284 bnum = int(arg)
285 except:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000286 print >>self.stdout, "Usage : commands [bnum]\n ...\n end"
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000287 return
288 self.commands_bnum = bnum
289 self.commands[bnum] = []
290 self.commands_doprompt[bnum] = True
291 self.commands_silent[bnum] = False
292 prompt_back = self.prompt
293 self.prompt = '(com) '
294 self.commands_defining = True
295 self.cmdloop()
296 self.commands_defining = False
297 self.prompt = prompt_back
298
Tim Peters2344fae2001-01-15 00:50:52 +0000299 def do_break(self, arg, temporary = 0):
300 # break [ ([filename:]lineno | function) [, "condition"] ]
301 if not arg:
302 if self.breaks: # There's at least one
Thomas Wouters477c8d52006-05-27 19:21:47 +0000303 print >>self.stdout, "Num Type Disp Enb Where"
Tim Peters2344fae2001-01-15 00:50:52 +0000304 for bp in bdb.Breakpoint.bpbynumber:
305 if bp:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000306 bp.bpprint(self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000307 return
308 # parse arguments; comma has lowest precedence
309 # and cannot occur in filename
310 filename = None
311 lineno = None
312 cond = None
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000313 comma = arg.find(',')
Tim Peters2344fae2001-01-15 00:50:52 +0000314 if comma > 0:
315 # parse stuff after comma: "condition"
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000316 cond = arg[comma+1:].lstrip()
317 arg = arg[:comma].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000318 # parse stuff before comma: [filename:]lineno | function
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000319 colon = arg.rfind(':')
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000320 funcname = None
Tim Peters2344fae2001-01-15 00:50:52 +0000321 if colon >= 0:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000322 filename = arg[:colon].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000323 f = self.lookupmodule(filename)
324 if not f:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000325 print >>self.stdout, '*** ', repr(filename),
326 print >>self.stdout, 'not found from sys.path'
Tim Peters2344fae2001-01-15 00:50:52 +0000327 return
328 else:
329 filename = f
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000330 arg = arg[colon+1:].lstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000331 try:
332 lineno = int(arg)
Guido van Rossumb940e112007-01-10 16:19:56 +0000333 except ValueError as msg:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000334 print >>self.stdout, '*** Bad lineno:', arg
Tim Peters2344fae2001-01-15 00:50:52 +0000335 return
336 else:
337 # no colon; can be lineno or function
338 try:
339 lineno = int(arg)
340 except ValueError:
341 try:
342 func = eval(arg,
343 self.curframe.f_globals,
344 self.curframe.f_locals)
345 except:
346 func = arg
347 try:
348 if hasattr(func, 'im_func'):
349 func = func.im_func
350 code = func.func_code
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000351 #use co_name to identify the bkpt (function names
352 #could be aliased, but co_name is invariant)
353 funcname = code.co_name
Tim Peters2344fae2001-01-15 00:50:52 +0000354 lineno = code.co_firstlineno
355 filename = code.co_filename
356 except:
357 # last thing to try
358 (ok, filename, ln) = self.lineinfo(arg)
359 if not ok:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000360 print >>self.stdout, '*** The specified object',
361 print >>self.stdout, repr(arg),
362 print >>self.stdout, 'is not a function'
363 print >>self.stdout, 'or was not found along sys.path.'
Tim Peters2344fae2001-01-15 00:50:52 +0000364 return
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000365 funcname = ok # ok contains a function name
Tim Peters2344fae2001-01-15 00:50:52 +0000366 lineno = int(ln)
367 if not filename:
368 filename = self.defaultFile()
369 # Check for reasonable breakpoint
370 line = self.checkline(filename, lineno)
371 if line:
372 # now set the break point
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000373 err = self.set_break(filename, line, temporary, cond, funcname)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000374 if err: print >>self.stdout, '***', err
Tim Peters2344fae2001-01-15 00:50:52 +0000375 else:
376 bp = self.get_breaks(filename, line)[-1]
Thomas Wouters477c8d52006-05-27 19:21:47 +0000377 print >>self.stdout, "Breakpoint %d at %s:%d" % (bp.number,
378 bp.file,
379 bp.line)
Tim Peters2344fae2001-01-15 00:50:52 +0000380
381 # To be overridden in derived debuggers
382 def defaultFile(self):
383 """Produce a reasonable default."""
384 filename = self.curframe.f_code.co_filename
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000385 if filename == '<string>' and self.mainpyfile:
386 filename = self.mainpyfile
Tim Peters2344fae2001-01-15 00:50:52 +0000387 return filename
388
389 do_b = do_break
390
391 def do_tbreak(self, arg):
392 self.do_break(arg, 1)
393
394 def lineinfo(self, identifier):
395 failed = (None, None, None)
396 # Input is identifier, may be in single quotes
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000397 idstring = identifier.split("'")
Tim Peters2344fae2001-01-15 00:50:52 +0000398 if len(idstring) == 1:
399 # not in single quotes
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000400 id = idstring[0].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000401 elif len(idstring) == 3:
402 # quoted
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000403 id = idstring[1].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000404 else:
405 return failed
406 if id == '': return failed
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000407 parts = id.split('.')
Tim Peters2344fae2001-01-15 00:50:52 +0000408 # Protection for derived debuggers
409 if parts[0] == 'self':
410 del parts[0]
411 if len(parts) == 0:
412 return failed
413 # Best first guess at file to look at
414 fname = self.defaultFile()
415 if len(parts) == 1:
416 item = parts[0]
417 else:
418 # More than one part.
419 # First is module, second is method/class
420 f = self.lookupmodule(parts[0])
421 if f:
422 fname = f
423 item = parts[1]
424 answer = find_function(item, fname)
425 return answer or failed
426
427 def checkline(self, filename, lineno):
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000428 """Check whether specified line seems to be executable.
Tim Peters2344fae2001-01-15 00:50:52 +0000429
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000430 Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
431 line or EOF). Warning: testing is not comprehensive.
432 """
Tim Peters2344fae2001-01-15 00:50:52 +0000433 line = linecache.getline(filename, lineno)
434 if not line:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000435 print >>self.stdout, 'End of file'
Tim Peters2344fae2001-01-15 00:50:52 +0000436 return 0
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000437 line = line.strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000438 # Don't allow setting breakpoint at a blank line
Guido van Rossum08454592002-07-12 13:10:53 +0000439 if (not line or (line[0] == '#') or
440 (line[:3] == '"""') or line[:3] == "'''"):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000441 print >>self.stdout, '*** Blank or comment'
Tim Peters2344fae2001-01-15 00:50:52 +0000442 return 0
Tim Peters2344fae2001-01-15 00:50:52 +0000443 return lineno
444
445 def do_enable(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000446 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000447 for i in args:
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000448 try:
449 i = int(i)
450 except ValueError:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000451 print >>self.stdout, 'Breakpoint index %r is not a number' % i
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000452 continue
453
454 if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000455 print >>self.stdout, 'No breakpoint numbered', i
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000456 continue
457
458 bp = bdb.Breakpoint.bpbynumber[i]
Tim Peters2344fae2001-01-15 00:50:52 +0000459 if bp:
460 bp.enable()
461
462 def do_disable(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000463 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000464 for i in args:
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000465 try:
466 i = int(i)
467 except ValueError:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000468 print >>self.stdout, 'Breakpoint index %r is not a number' % i
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000469 continue
Tim Petersf545baa2003-06-15 23:26:30 +0000470
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000471 if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000472 print >>self.stdout, 'No breakpoint numbered', i
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000473 continue
474
475 bp = bdb.Breakpoint.bpbynumber[i]
Tim Peters2344fae2001-01-15 00:50:52 +0000476 if bp:
477 bp.disable()
478
479 def do_condition(self, arg):
480 # arg is breakpoint number and condition
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000481 args = arg.split(' ', 1)
482 bpnum = int(args[0].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000483 try:
484 cond = args[1]
485 except:
486 cond = None
487 bp = bdb.Breakpoint.bpbynumber[bpnum]
488 if bp:
489 bp.cond = cond
490 if not cond:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000491 print >>self.stdout, 'Breakpoint', bpnum,
492 print >>self.stdout, 'is now unconditional.'
Tim Peters2344fae2001-01-15 00:50:52 +0000493
494 def do_ignore(self,arg):
495 """arg is bp number followed by ignore count."""
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000496 args = arg.split()
497 bpnum = int(args[0].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000498 try:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000499 count = int(args[1].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000500 except:
501 count = 0
502 bp = bdb.Breakpoint.bpbynumber[bpnum]
503 if bp:
504 bp.ignore = count
Guido van Rossum08454592002-07-12 13:10:53 +0000505 if count > 0:
Tim Peters2344fae2001-01-15 00:50:52 +0000506 reply = 'Will ignore next '
Guido van Rossum08454592002-07-12 13:10:53 +0000507 if count > 1:
Tim Peters2344fae2001-01-15 00:50:52 +0000508 reply = reply + '%d crossings' % count
509 else:
510 reply = reply + '1 crossing'
Thomas Wouters477c8d52006-05-27 19:21:47 +0000511 print >>self.stdout, reply + ' of breakpoint %d.' % bpnum
Tim Peters2344fae2001-01-15 00:50:52 +0000512 else:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000513 print >>self.stdout, 'Will stop next time breakpoint',
514 print >>self.stdout, bpnum, 'is reached.'
Tim Peters2344fae2001-01-15 00:50:52 +0000515
516 def do_clear(self, arg):
517 """Three possibilities, tried in this order:
518 clear -> clear all breaks, ask for confirmation
519 clear file:lineno -> clear all breaks at file:lineno
520 clear bpno bpno ... -> clear breakpoints by number"""
521 if not arg:
522 try:
523 reply = raw_input('Clear all breaks? ')
524 except EOFError:
525 reply = 'no'
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000526 reply = reply.strip().lower()
Tim Peters2344fae2001-01-15 00:50:52 +0000527 if reply in ('y', 'yes'):
528 self.clear_all_breaks()
529 return
530 if ':' in arg:
531 # Make sure it works for "clear C:\foo\bar.py:12"
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000532 i = arg.rfind(':')
Tim Peters2344fae2001-01-15 00:50:52 +0000533 filename = arg[:i]
534 arg = arg[i+1:]
535 try:
536 lineno = int(arg)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000537 except ValueError:
Tim Peters2344fae2001-01-15 00:50:52 +0000538 err = "Invalid line number (%s)" % arg
539 else:
540 err = self.clear_break(filename, lineno)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000541 if err: print >>self.stdout, '***', err
Tim Peters2344fae2001-01-15 00:50:52 +0000542 return
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000543 numberlist = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000544 for i in numberlist:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000545 try:
546 i = int(i)
547 except ValueError:
548 print >>self.stdout, 'Breakpoint index %r is not a number' % i
549 continue
550
Georg Brandl6d2b3462005-08-24 07:36:17 +0000551 if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000552 print >>self.stdout, 'No breakpoint numbered', i
Georg Brandl6d2b3462005-08-24 07:36:17 +0000553 continue
Tim Peters2344fae2001-01-15 00:50:52 +0000554 err = self.clear_bpbynumber(i)
555 if err:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000556 print >>self.stdout, '***', err
Tim Peters2344fae2001-01-15 00:50:52 +0000557 else:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000558 print >>self.stdout, 'Deleted breakpoint', i
Tim Peters2344fae2001-01-15 00:50:52 +0000559 do_cl = do_clear # 'c' is already an abbreviation for 'continue'
560
561 def do_where(self, arg):
562 self.print_stack_trace()
563 do_w = do_where
Guido van Rossum6bd68352001-01-20 17:57:37 +0000564 do_bt = do_where
Tim Peters2344fae2001-01-15 00:50:52 +0000565
566 def do_up(self, arg):
567 if self.curindex == 0:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000568 print >>self.stdout, '*** Oldest frame'
Tim Peters2344fae2001-01-15 00:50:52 +0000569 else:
570 self.curindex = self.curindex - 1
571 self.curframe = self.stack[self.curindex][0]
572 self.print_stack_entry(self.stack[self.curindex])
573 self.lineno = None
574 do_u = do_up
575
576 def do_down(self, arg):
577 if self.curindex + 1 == len(self.stack):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000578 print >>self.stdout, '*** Newest frame'
Tim Peters2344fae2001-01-15 00:50:52 +0000579 else:
580 self.curindex = self.curindex + 1
581 self.curframe = self.stack[self.curindex][0]
582 self.print_stack_entry(self.stack[self.curindex])
583 self.lineno = None
584 do_d = do_down
585
586 def do_step(self, arg):
587 self.set_step()
588 return 1
589 do_s = do_step
590
591 def do_next(self, arg):
592 self.set_next(self.curframe)
593 return 1
594 do_n = do_next
595
596 def do_return(self, arg):
597 self.set_return(self.curframe)
598 return 1
599 do_r = do_return
600
601 def do_continue(self, arg):
602 self.set_continue()
603 return 1
604 do_c = do_cont = do_continue
605
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000606 def do_jump(self, arg):
607 if self.curindex + 1 != len(self.stack):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000608 print >>self.stdout, "*** You can only jump within the bottom frame"
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000609 return
610 try:
611 arg = int(arg)
612 except ValueError:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000613 print >>self.stdout, "*** The 'jump' command requires a line number."
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000614 else:
615 try:
616 # Do the jump, fix up our copy of the stack, and display the
617 # new position
618 self.curframe.f_lineno = arg
619 self.stack[self.curindex] = self.stack[self.curindex][0], arg
620 self.print_stack_entry(self.stack[self.curindex])
Guido van Rossumb940e112007-01-10 16:19:56 +0000621 except ValueError as e:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000622 print >>self.stdout, '*** Jump failed:', e
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000623 do_j = do_jump
624
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000625 def do_debug(self, arg):
626 sys.settrace(None)
627 globals = self.curframe.f_globals
628 locals = self.curframe.f_locals
Guido van Rossumed538d82003-04-09 19:36:34 +0000629 p = Pdb()
630 p.prompt = "(%s) " % self.prompt.strip()
Thomas Wouters477c8d52006-05-27 19:21:47 +0000631 print >>self.stdout, "ENTERING RECURSIVE DEBUGGER"
Guido van Rossumed538d82003-04-09 19:36:34 +0000632 sys.call_tracing(p.run, (arg, globals, locals))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000633 print >>self.stdout, "LEAVING RECURSIVE DEBUGGER"
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000634 sys.settrace(self.trace_dispatch)
635 self.lastcmd = p.lastcmd
636
Tim Peters2344fae2001-01-15 00:50:52 +0000637 def do_quit(self, arg):
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000638 self._user_requested_quit = 1
Tim Peters2344fae2001-01-15 00:50:52 +0000639 self.set_quit()
640 return 1
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000641
Tim Peters2344fae2001-01-15 00:50:52 +0000642 do_q = do_quit
Guido van Rossumd1c08f32002-04-15 00:48:24 +0000643 do_exit = do_quit
Tim Peters2344fae2001-01-15 00:50:52 +0000644
Guido van Rossumeef26072003-01-13 21:13:55 +0000645 def do_EOF(self, arg):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000646 print >>self.stdout
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000647 self._user_requested_quit = 1
Guido van Rossumeef26072003-01-13 21:13:55 +0000648 self.set_quit()
649 return 1
650
Tim Peters2344fae2001-01-15 00:50:52 +0000651 def do_args(self, arg):
652 f = self.curframe
653 co = f.f_code
654 dict = f.f_locals
655 n = co.co_argcount
656 if co.co_flags & 4: n = n+1
657 if co.co_flags & 8: n = n+1
658 for i in range(n):
659 name = co.co_varnames[i]
Thomas Wouters477c8d52006-05-27 19:21:47 +0000660 print >>self.stdout, name, '=',
661 if name in dict: print >>self.stdout, dict[name]
662 else: print >>self.stdout, "*** undefined ***"
Tim Peters2344fae2001-01-15 00:50:52 +0000663 do_a = do_args
Guido van Rossum2424f851998-09-11 22:50:09 +0000664
Tim Peters2344fae2001-01-15 00:50:52 +0000665 def do_retval(self, arg):
Raymond Hettinger54f02222002-06-01 14:18:47 +0000666 if '__return__' in self.curframe.f_locals:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000667 print >>self.stdout, self.curframe.f_locals['__return__']
Tim Peters2344fae2001-01-15 00:50:52 +0000668 else:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000669 print >>self.stdout, '*** Not yet returned!'
Tim Peters2344fae2001-01-15 00:50:52 +0000670 do_rv = do_retval
Guido van Rossum2424f851998-09-11 22:50:09 +0000671
Barry Warsaw210bd202002-11-05 22:40:20 +0000672 def _getval(self, arg):
Tim Peters2344fae2001-01-15 00:50:52 +0000673 try:
Barry Warsaw210bd202002-11-05 22:40:20 +0000674 return eval(arg, self.curframe.f_globals,
675 self.curframe.f_locals)
Tim Peters2344fae2001-01-15 00:50:52 +0000676 except:
677 t, v = sys.exc_info()[:2]
Barry Warsaw210bd202002-11-05 22:40:20 +0000678 if isinstance(t, str):
Tim Peters2344fae2001-01-15 00:50:52 +0000679 exc_type_name = t
680 else: exc_type_name = t.__name__
Thomas Wouters477c8d52006-05-27 19:21:47 +0000681 print >>self.stdout, '***', exc_type_name + ':', repr(v)
Barry Warsaw210bd202002-11-05 22:40:20 +0000682 raise
Guido van Rossum2424f851998-09-11 22:50:09 +0000683
Barry Warsaw210bd202002-11-05 22:40:20 +0000684 def do_p(self, arg):
685 try:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000686 print >>self.stdout, repr(self._getval(arg))
Barry Warsaw210bd202002-11-05 22:40:20 +0000687 except:
688 pass
689
690 def do_pp(self, arg):
691 try:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000692 pprint.pprint(self._getval(arg), self.stdout)
Barry Warsaw210bd202002-11-05 22:40:20 +0000693 except:
694 pass
Guido van Rossum2424f851998-09-11 22:50:09 +0000695
Tim Peters2344fae2001-01-15 00:50:52 +0000696 def do_list(self, arg):
697 self.lastcmd = 'list'
698 last = None
699 if arg:
700 try:
701 x = eval(arg, {}, {})
702 if type(x) == type(()):
703 first, last = x
704 first = int(first)
705 last = int(last)
706 if last < first:
707 # Assume it's a count
708 last = first + last
709 else:
710 first = max(1, int(x) - 5)
711 except:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000712 print >>self.stdout, '*** Error in argument:', repr(arg)
Tim Peters2344fae2001-01-15 00:50:52 +0000713 return
714 elif self.lineno is None:
715 first = max(1, self.curframe.f_lineno - 5)
716 else:
717 first = self.lineno + 1
718 if last is None:
719 last = first + 10
720 filename = self.curframe.f_code.co_filename
721 breaklist = self.get_file_breaks(filename)
722 try:
723 for lineno in range(first, last+1):
724 line = linecache.getline(filename, lineno)
725 if not line:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000726 print >>self.stdout, '[EOF]'
Tim Peters2344fae2001-01-15 00:50:52 +0000727 break
728 else:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000729 s = repr(lineno).rjust(3)
Tim Peters2344fae2001-01-15 00:50:52 +0000730 if len(s) < 4: s = s + ' '
731 if lineno in breaklist: s = s + 'B'
732 else: s = s + ' '
733 if lineno == self.curframe.f_lineno:
734 s = s + '->'
Thomas Wouters477c8d52006-05-27 19:21:47 +0000735 print >>self.stdout, s + '\t' + line,
Tim Peters2344fae2001-01-15 00:50:52 +0000736 self.lineno = lineno
737 except KeyboardInterrupt:
738 pass
739 do_l = do_list
Guido van Rossum2424f851998-09-11 22:50:09 +0000740
Tim Peters2344fae2001-01-15 00:50:52 +0000741 def do_whatis(self, arg):
742 try:
743 value = eval(arg, self.curframe.f_globals,
744 self.curframe.f_locals)
745 except:
746 t, v = sys.exc_info()[:2]
747 if type(t) == type(''):
748 exc_type_name = t
749 else: exc_type_name = t.__name__
Thomas Wouters477c8d52006-05-27 19:21:47 +0000750 print >>self.stdout, '***', exc_type_name + ':', repr(v)
Tim Peters2344fae2001-01-15 00:50:52 +0000751 return
752 code = None
753 # Is it a function?
754 try: code = value.func_code
755 except: pass
756 if code:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000757 print >>self.stdout, 'Function', code.co_name
Tim Peters2344fae2001-01-15 00:50:52 +0000758 return
759 # Is it an instance method?
760 try: code = value.im_func.func_code
761 except: pass
762 if code:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000763 print >>self.stdout, 'Method', code.co_name
Tim Peters2344fae2001-01-15 00:50:52 +0000764 return
765 # None of the above...
Thomas Wouters477c8d52006-05-27 19:21:47 +0000766 print >>self.stdout, type(value)
Guido van Rossum8e2ec561993-07-29 09:37:38 +0000767
Tim Peters2344fae2001-01-15 00:50:52 +0000768 def do_alias(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000769 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000770 if len(args) == 0:
771 keys = self.aliases.keys()
772 keys.sort()
773 for alias in keys:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000774 print >>self.stdout, "%s = %s" % (alias, self.aliases[alias])
Tim Peters2344fae2001-01-15 00:50:52 +0000775 return
Guido van Rossum08454592002-07-12 13:10:53 +0000776 if args[0] in self.aliases and len(args) == 1:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000777 print >>self.stdout, "%s = %s" % (args[0], self.aliases[args[0]])
Tim Peters2344fae2001-01-15 00:50:52 +0000778 else:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000779 self.aliases[args[0]] = ' '.join(args[1:])
Guido van Rossum23efba41992-01-27 16:58:47 +0000780
Tim Peters2344fae2001-01-15 00:50:52 +0000781 def do_unalias(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000782 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000783 if len(args) == 0: return
Raymond Hettinger54f02222002-06-01 14:18:47 +0000784 if args[0] in self.aliases:
Tim Peters2344fae2001-01-15 00:50:52 +0000785 del self.aliases[args[0]]
Guido van Rossum00230781993-03-29 11:39:45 +0000786
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000787 #list of all the commands making the program resume execution.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000788 commands_resuming = ['do_continue', 'do_step', 'do_next', 'do_return',
789 'do_quit', 'do_jump']
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000790
Tim Peters2344fae2001-01-15 00:50:52 +0000791 # Print a traceback starting at the top stack frame.
792 # The most recently entered frame is printed last;
793 # this is different from dbx and gdb, but consistent with
794 # the Python interpreter's stack trace.
795 # It is also consistent with the up/down commands (which are
796 # compatible with dbx and gdb: up moves towards 'main()'
797 # and down moves towards the most recent stack frame).
Guido van Rossum2424f851998-09-11 22:50:09 +0000798
Tim Peters2344fae2001-01-15 00:50:52 +0000799 def print_stack_trace(self):
800 try:
801 for frame_lineno in self.stack:
802 self.print_stack_entry(frame_lineno)
803 except KeyboardInterrupt:
804 pass
Guido van Rossum2424f851998-09-11 22:50:09 +0000805
Tim Peters2344fae2001-01-15 00:50:52 +0000806 def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix):
807 frame, lineno = frame_lineno
808 if frame is self.curframe:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000809 print >>self.stdout, '>',
Tim Peters2344fae2001-01-15 00:50:52 +0000810 else:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000811 print >>self.stdout, ' ',
812 print >>self.stdout, self.format_stack_entry(frame_lineno,
813 prompt_prefix)
Guido van Rossum2424f851998-09-11 22:50:09 +0000814
Guido van Rossum921c8241992-01-10 14:54:42 +0000815
Tim Peters2344fae2001-01-15 00:50:52 +0000816 # Help methods (derived from pdb.doc)
Guido van Rossum921c8241992-01-10 14:54:42 +0000817
Tim Peters2344fae2001-01-15 00:50:52 +0000818 def help_help(self):
819 self.help_h()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000820
Tim Peters2344fae2001-01-15 00:50:52 +0000821 def help_h(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000822 print >>self.stdout, """h(elp)
Tim Peters2344fae2001-01-15 00:50:52 +0000823Without argument, print the list of available commands.
824With a command name as argument, print help about that command
825"help pdb" pipes the full documentation file to the $PAGER
826"help exec" gives help on the ! command"""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000827
Tim Peters2344fae2001-01-15 00:50:52 +0000828 def help_where(self):
829 self.help_w()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000830
Tim Peters2344fae2001-01-15 00:50:52 +0000831 def help_w(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000832 print >>self.stdout, """w(here)
Tim Peters2344fae2001-01-15 00:50:52 +0000833Print a stack trace, with the most recent frame at the bottom.
834An arrow indicates the "current frame", which determines the
Guido van Rossum6bd68352001-01-20 17:57:37 +0000835context of most commands. 'bt' is an alias for this command."""
836
837 help_bt = help_w
Guido van Rossumb6775db1994-08-01 11:34:53 +0000838
Tim Peters2344fae2001-01-15 00:50:52 +0000839 def help_down(self):
840 self.help_d()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000841
Tim Peters2344fae2001-01-15 00:50:52 +0000842 def help_d(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000843 print >>self.stdout, """d(own)
Tim Peters2344fae2001-01-15 00:50:52 +0000844Move the current frame one level down in the stack trace
Johannes Gijsbers34c41202004-08-14 15:19:28 +0000845(to a newer frame)."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000846
Tim Peters2344fae2001-01-15 00:50:52 +0000847 def help_up(self):
848 self.help_u()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000849
Tim Peters2344fae2001-01-15 00:50:52 +0000850 def help_u(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000851 print >>self.stdout, """u(p)
Tim Peters2344fae2001-01-15 00:50:52 +0000852Move the current frame one level up in the stack trace
Johannes Gijsbers34c41202004-08-14 15:19:28 +0000853(to an older frame)."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000854
Tim Peters2344fae2001-01-15 00:50:52 +0000855 def help_break(self):
856 self.help_b()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000857
Tim Peters2344fae2001-01-15 00:50:52 +0000858 def help_b(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000859 print >>self.stdout, """b(reak) ([file:]lineno | function) [, condition]
Tim Peters2344fae2001-01-15 00:50:52 +0000860With a line number argument, set a break there in the current
861file. With a function name, set a break at first executable line
862of that function. Without argument, list all breaks. If a second
863argument is present, it is a string specifying an expression
864which must evaluate to true before the breakpoint is honored.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000865
Tim Peters2344fae2001-01-15 00:50:52 +0000866The line number may be prefixed with a filename and a colon,
867to specify a breakpoint in another file (probably one that
868hasn't been loaded yet). The file is searched for on sys.path;
869the .py suffix may be omitted."""
Guido van Rossumb5699c71998-07-20 23:13:54 +0000870
Tim Peters2344fae2001-01-15 00:50:52 +0000871 def help_clear(self):
872 self.help_cl()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000873
Tim Peters2344fae2001-01-15 00:50:52 +0000874 def help_cl(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000875 print >>self.stdout, "cl(ear) filename:lineno"
876 print >>self.stdout, """cl(ear) [bpnumber [bpnumber...]]
Tim Peters2344fae2001-01-15 00:50:52 +0000877With a space separated list of breakpoint numbers, clear
878those breakpoints. Without argument, clear all breaks (but
879first ask confirmation). With a filename:lineno argument,
880clear all breaks at that line in that file.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000881
Tim Peters2344fae2001-01-15 00:50:52 +0000882Note that the argument is different from previous versions of
883the debugger (in python distributions 1.5.1 and before) where
884a linenumber was used instead of either filename:lineno or
885breakpoint numbers."""
Guido van Rossumb5699c71998-07-20 23:13:54 +0000886
Tim Peters2344fae2001-01-15 00:50:52 +0000887 def help_tbreak(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000888 print >>self.stdout, """tbreak same arguments as break, but breakpoint is
Tim Peters2344fae2001-01-15 00:50:52 +0000889removed when first hit."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000890
Tim Peters2344fae2001-01-15 00:50:52 +0000891 def help_enable(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000892 print >>self.stdout, """enable bpnumber [bpnumber ...]
Tim Peters2344fae2001-01-15 00:50:52 +0000893Enables the breakpoints given as a space separated list of
894bp numbers."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000895
Tim Peters2344fae2001-01-15 00:50:52 +0000896 def help_disable(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000897 print >>self.stdout, """disable bpnumber [bpnumber ...]
Tim Peters2344fae2001-01-15 00:50:52 +0000898Disables the breakpoints given as a space separated list of
899bp numbers."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000900
Tim Peters2344fae2001-01-15 00:50:52 +0000901 def help_ignore(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000902 print >>self.stdout, """ignore bpnumber count
Tim Peters2344fae2001-01-15 00:50:52 +0000903Sets the ignore count for the given breakpoint number. A breakpoint
904becomes active when the ignore count is zero. When non-zero, the
905count is decremented each time the breakpoint is reached and the
906breakpoint is not disabled and any associated condition evaluates
907to true."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000908
Tim Peters2344fae2001-01-15 00:50:52 +0000909 def help_condition(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000910 print >>self.stdout, """condition bpnumber str_condition
Tim Peters2344fae2001-01-15 00:50:52 +0000911str_condition is a string specifying an expression which
912must evaluate to true before the breakpoint is honored.
913If str_condition is absent, any existing condition is removed;
914i.e., the breakpoint is made unconditional."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000915
Tim Peters2344fae2001-01-15 00:50:52 +0000916 def help_step(self):
917 self.help_s()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000918
Tim Peters2344fae2001-01-15 00:50:52 +0000919 def help_s(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000920 print >>self.stdout, """s(tep)
Tim Peters2344fae2001-01-15 00:50:52 +0000921Execute the current line, stop at the first possible occasion
922(either in a function that is called or in the current function)."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000923
Tim Peters2344fae2001-01-15 00:50:52 +0000924 def help_next(self):
925 self.help_n()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000926
Tim Peters2344fae2001-01-15 00:50:52 +0000927 def help_n(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000928 print >>self.stdout, """n(ext)
Tim Peters2344fae2001-01-15 00:50:52 +0000929Continue execution until the next line in the current function
930is reached or it returns."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000931
Tim Peters2344fae2001-01-15 00:50:52 +0000932 def help_return(self):
933 self.help_r()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000934
Tim Peters2344fae2001-01-15 00:50:52 +0000935 def help_r(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000936 print >>self.stdout, """r(eturn)
Tim Peters2344fae2001-01-15 00:50:52 +0000937Continue execution until the current function returns."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000938
Tim Peters2344fae2001-01-15 00:50:52 +0000939 def help_continue(self):
940 self.help_c()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000941
Tim Peters2344fae2001-01-15 00:50:52 +0000942 def help_cont(self):
943 self.help_c()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000944
Tim Peters2344fae2001-01-15 00:50:52 +0000945 def help_c(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000946 print >>self.stdout, """c(ont(inue))
Tim Peters2344fae2001-01-15 00:50:52 +0000947Continue execution, only stop when a breakpoint is encountered."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000948
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000949 def help_jump(self):
950 self.help_j()
951
952 def help_j(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000953 print >>self.stdout, """j(ump) lineno
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000954Set the next line that will be executed."""
955
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000956 def help_debug(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000957 print >>self.stdout, """debug code
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000958Enter a recursive debugger that steps through the code argument
959(which is an arbitrary expression or statement to be executed
960in the current environment)."""
961
Tim Peters2344fae2001-01-15 00:50:52 +0000962 def help_list(self):
963 self.help_l()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000964
Tim Peters2344fae2001-01-15 00:50:52 +0000965 def help_l(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000966 print >>self.stdout, """l(ist) [first [,last]]
Tim Peters2344fae2001-01-15 00:50:52 +0000967List source code for the current file.
968Without arguments, list 11 lines around the current line
969or continue the previous listing.
970With one argument, list 11 lines starting at that line.
971With two arguments, list the given range;
972if the second argument is less than the first, it is a count."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000973
Tim Peters2344fae2001-01-15 00:50:52 +0000974 def help_args(self):
975 self.help_a()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000976
Tim Peters2344fae2001-01-15 00:50:52 +0000977 def help_a(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000978 print >>self.stdout, """a(rgs)
Tim Peters2344fae2001-01-15 00:50:52 +0000979Print the arguments of the current function."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000980
Tim Peters2344fae2001-01-15 00:50:52 +0000981 def help_p(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000982 print >>self.stdout, """p expression
Tim Peters2344fae2001-01-15 00:50:52 +0000983Print the value of the expression."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000984
Barry Warsaw210bd202002-11-05 22:40:20 +0000985 def help_pp(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000986 print >>self.stdout, """pp expression
Barry Warsaw210bd202002-11-05 22:40:20 +0000987Pretty-print the value of the expression."""
988
Tim Peters2344fae2001-01-15 00:50:52 +0000989 def help_exec(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000990 print >>self.stdout, """(!) statement
Tim Peters2344fae2001-01-15 00:50:52 +0000991Execute the (one-line) statement in the context of
992the current stack frame.
993The exclamation point can be omitted unless the first word
994of the statement resembles a debugger command.
995To assign to a global variable you must always prefix the
996command with a 'global' command, e.g.:
997(Pdb) global list_options; list_options = ['-l']
998(Pdb)"""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000999
Tim Peters2344fae2001-01-15 00:50:52 +00001000 def help_quit(self):
1001 self.help_q()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001002
Tim Peters2344fae2001-01-15 00:50:52 +00001003 def help_q(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001004 print >>self.stdout, """q(uit) or exit - Quit from the debugger.
Tim Peters2344fae2001-01-15 00:50:52 +00001005The program being executed is aborted."""
Guido van Rossumb6775db1994-08-01 11:34:53 +00001006
Guido van Rossumd1c08f32002-04-15 00:48:24 +00001007 help_exit = help_q
1008
Tim Peters2344fae2001-01-15 00:50:52 +00001009 def help_whatis(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001010 print >>self.stdout, """whatis arg
Tim Peters2344fae2001-01-15 00:50:52 +00001011Prints the type of the argument."""
Guido van Rossumb6775db1994-08-01 11:34:53 +00001012
Tim Peters2344fae2001-01-15 00:50:52 +00001013 def help_EOF(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001014 print >>self.stdout, """EOF
Tim Peters2344fae2001-01-15 00:50:52 +00001015Handles the receipt of EOF as a command."""
Guido van Rossum2424f851998-09-11 22:50:09 +00001016
Tim Peters2344fae2001-01-15 00:50:52 +00001017 def help_alias(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001018 print >>self.stdout, """alias [name [command [parameter parameter ...] ]]
Tim Peters2344fae2001-01-15 00:50:52 +00001019Creates an alias called 'name' the executes 'command'. The command
1020must *not* be enclosed in quotes. Replaceable parameters are
1021indicated by %1, %2, and so on, while %* is replaced by all the
1022parameters. If no command is given, the current alias for name
1023is shown. If no name is given, all aliases are listed.
Guido van Rossum2424f851998-09-11 22:50:09 +00001024
Tim Peters2344fae2001-01-15 00:50:52 +00001025Aliases may be nested and can contain anything that can be
1026legally typed at the pdb prompt. Note! You *can* override
1027internal pdb commands with aliases! Those internal commands
1028are then hidden until the alias is removed. Aliasing is recursively
1029applied to the first word of the command line; all other words
1030in the line are left alone.
Guido van Rossum2424f851998-09-11 22:50:09 +00001031
Tim Peters2344fae2001-01-15 00:50:52 +00001032Some useful aliases (especially when placed in the .pdbrc file) are:
Guido van Rossum2424f851998-09-11 22:50:09 +00001033
Tim Peters2344fae2001-01-15 00:50:52 +00001034#Print instance variables (usage "pi classInst")
1035alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
Guido van Rossum2424f851998-09-11 22:50:09 +00001036
Tim Peters2344fae2001-01-15 00:50:52 +00001037#Print instance variables in self
1038alias ps pi self
1039"""
Guido van Rossum2424f851998-09-11 22:50:09 +00001040
Tim Peters2344fae2001-01-15 00:50:52 +00001041 def help_unalias(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001042 print >>self.stdout, """unalias name
Tim Peters2344fae2001-01-15 00:50:52 +00001043Deletes the specified alias."""
Guido van Rossum2424f851998-09-11 22:50:09 +00001044
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001045 def help_commands(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001046 print >>self.stdout, """commands [bpnumber]
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001047(com) ...
1048(com) end
1049(Pdb)
1050
1051Specify a list of commands for breakpoint number bpnumber. The
1052commands themselves appear on the following lines. Type a line
1053containing just 'end' to terminate the commands.
1054
1055To remove all commands from a breakpoint, type commands and
1056follow it immediately with end; that is, give no commands.
1057
1058With no bpnumber argument, commands refers to the last
1059breakpoint set.
1060
1061You can use breakpoint commands to start your program up again.
1062Simply use the continue command, or step, or any other
1063command that resumes execution.
1064
1065Specifying any command resuming execution (currently continue,
1066step, next, return, jump, quit and their abbreviations) terminates
1067the command list (as if that command was immediately followed by end).
1068This is because any time you resume execution
1069(even with a simple next or step), you may encounter
1070another breakpoint--which could have its own command list, leading to
1071ambiguities about which list to execute.
1072
1073 If you use the 'silent' command in the command list, the
1074usual message about stopping at a breakpoint is not printed. This may
1075be desirable for breakpoints that are to print a specific message and
1076then continue. If none of the other commands print anything, you
1077see no sign that the breakpoint was reached.
1078"""
1079
Tim Peters2344fae2001-01-15 00:50:52 +00001080 def help_pdb(self):
1081 help()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001082
Tim Peters2344fae2001-01-15 00:50:52 +00001083 def lookupmodule(self, filename):
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001084 """Helper function for break/clear parsing -- may be overridden.
1085
1086 lookupmodule() translates (possibly incomplete) file or module name
1087 into an absolute file name.
1088 """
1089 if os.path.isabs(filename) and os.path.exists(filename):
Tim Peterse718f612004-10-12 21:51:32 +00001090 return filename
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001091 f = os.path.join(sys.path[0], filename)
1092 if os.path.exists(f) and self.canonic(f) == self.mainpyfile:
1093 return f
Tim Peters2344fae2001-01-15 00:50:52 +00001094 root, ext = os.path.splitext(filename)
1095 if ext == '':
1096 filename = filename + '.py'
1097 if os.path.isabs(filename):
1098 return filename
1099 for dirname in sys.path:
1100 while os.path.islink(dirname):
1101 dirname = os.readlink(dirname)
1102 fullname = os.path.join(dirname, filename)
1103 if os.path.exists(fullname):
1104 return fullname
1105 return None
Guido van Rossumb5699c71998-07-20 23:13:54 +00001106
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001107 def _runscript(self, filename):
1108 # Start with fresh empty copy of globals and locals and tell the script
1109 # that it's being run as __main__ to avoid scripts being able to access
1110 # the pdb.py namespace.
Tim Peterse718f612004-10-12 21:51:32 +00001111 globals_ = {"__name__" : "__main__"}
1112 locals_ = globals_
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001113
1114 # When bdb sets tracing, a number of call and line events happens
1115 # BEFORE debugger even reaches user's code (and the exact sequence of
1116 # events depends on python version). So we take special measures to
1117 # avoid stopping before we reach the main script (see user_line and
1118 # user_call for details).
1119 self._wait_for_mainpyfile = 1
1120 self.mainpyfile = self.canonic(filename)
1121 self._user_requested_quit = 0
1122 statement = 'execfile( "%s")' % filename
1123 self.run(statement, globals=globals_, locals=locals_)
1124
Guido van Rossum35771131992-09-08 11:59:04 +00001125# Simplified interface
1126
Guido van Rossum5e38b6f1995-02-27 13:13:40 +00001127def run(statement, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +00001128 Pdb().run(statement, globals, locals)
Guido van Rossum5e38b6f1995-02-27 13:13:40 +00001129
1130def runeval(expression, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +00001131 return Pdb().runeval(expression, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001132
1133def runctx(statement, globals, locals):
Tim Peters2344fae2001-01-15 00:50:52 +00001134 # B/W compatibility
1135 run(statement, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001136
Raymond Hettinger2ef7e6c2004-10-24 00:32:24 +00001137def runcall(*args, **kwds):
1138 return Pdb().runcall(*args, **kwds)
Guido van Rossum4e160981992-09-02 20:43:20 +00001139
Guido van Rossumb6775db1994-08-01 11:34:53 +00001140def set_trace():
Johannes Gijsbers84a6c202004-11-07 11:35:30 +00001141 Pdb().set_trace(sys._getframe().f_back)
Guido van Rossum35771131992-09-08 11:59:04 +00001142
1143# Post-Mortem interface
1144
1145def post_mortem(t):
Tim Peters2344fae2001-01-15 00:50:52 +00001146 p = Pdb()
1147 p.reset()
1148 while t.tb_next is not None:
1149 t = t.tb_next
1150 p.interaction(t.tb_frame, t)
Guido van Rossum35771131992-09-08 11:59:04 +00001151
1152def pm():
Tim Peters2344fae2001-01-15 00:50:52 +00001153 post_mortem(sys.last_traceback)
Guido van Rossum35771131992-09-08 11:59:04 +00001154
1155
1156# Main program for testing
1157
Guido van Rossum23efba41992-01-27 16:58:47 +00001158TESTCMD = 'import x; x.main()'
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001159
Guido van Rossum921c8241992-01-10 14:54:42 +00001160def test():
Tim Peters2344fae2001-01-15 00:50:52 +00001161 run(TESTCMD)
Guido van Rossume61fa0a1993-10-22 13:56:35 +00001162
1163# print help
1164def help():
Tim Peters2344fae2001-01-15 00:50:52 +00001165 for dirname in sys.path:
1166 fullname = os.path.join(dirname, 'pdb.doc')
1167 if os.path.exists(fullname):
1168 sts = os.system('${PAGER-more} '+fullname)
1169 if sts: print '*** Pager exit status:', sts
1170 break
1171 else:
1172 print 'Sorry, can\'t find the help file "pdb.doc"',
1173 print 'along the Python search path'
Guido van Rossumf17361d1996-07-30 16:28:13 +00001174
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001175def main():
Tim Peters2344fae2001-01-15 00:50:52 +00001176 if not sys.argv[1:]:
1177 print "usage: pdb.py scriptfile [arg] ..."
1178 sys.exit(2)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001179
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001180 mainpyfile = sys.argv[1] # Get script filename
1181 if not os.path.exists(mainpyfile):
1182 print 'Error:', mainpyfile, 'does not exist'
Tim Peters2344fae2001-01-15 00:50:52 +00001183 sys.exit(1)
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001184
Tim Peters2344fae2001-01-15 00:50:52 +00001185 del sys.argv[0] # Hide "pdb.py" from argument list
Guido van Rossumec577d51996-09-10 17:39:34 +00001186
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001187 # Replace pdb's dir with script's dir in front of module search path.
1188 sys.path[0] = os.path.dirname(mainpyfile)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001189
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001190 # Note on saving/restoring sys.argv: it's a good idea when sys.argv was
1191 # modified by the script being debugged. It's a bad idea when it was
1192 # changed by the user from the command line. The best approach would be to
1193 # have a "restart" command which would allow explicit specification of
1194 # command line arguments.
1195 pdb = Pdb()
1196 while 1:
1197 try:
1198 pdb._runscript(mainpyfile)
1199 if pdb._user_requested_quit:
1200 break
Tim Peterse718f612004-10-12 21:51:32 +00001201 print "The program finished and will be restarted"
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001202 except SystemExit:
1203 # In most cases SystemExit does not warrant a post-mortem session.
1204 print "The program exited via sys.exit(). Exit status: ",
1205 print sys.exc_info()[1]
1206 except:
1207 traceback.print_exc()
1208 print "Uncaught exception. Entering post mortem debugging"
1209 print "Running 'cont' or 'step' will restart the program"
1210 t = sys.exc_info()[2]
1211 while t.tb_next is not None:
1212 t = t.tb_next
1213 pdb.interaction(t.tb_frame,t)
1214 print "Post mortem debugger finished. The "+mainpyfile+" will be restarted"
1215
1216
1217# When invoked as main program, invoke the debugger on a script
1218if __name__=='__main__':
1219 main()