blob: 94f61f7e70f4e32b000a63fa771b470c1d705284 [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):
Tim Peters2344fae2001-01-15 00:50:52 +000031 cre = re.compile(r'def\s+%s\s*[(]' % funcname)
32 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')
201 exec code in globals, locals
202 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
238 Checks wether this line is typed in the normal prompt or in a breakpoint command list definition
239 """
240 if not self.commands_defining:
241 return cmd.Cmd.onecmd(self, line)
242 else:
243 return self.handle_command_def(line)
244
245 def handle_command_def(self,line):
246 """ Handles one command line during command list definition. """
247 cmd, arg, line = self.parseline(line)
248 if cmd == 'silent':
249 self.commands_silent[self.commands_bnum] = True
250 return # continue to handle other cmd def in the cmd list
251 elif cmd == 'end':
252 self.cmdqueue = []
253 return 1 # end of cmd list
254 cmdlist = self.commands[self.commands_bnum]
255 if (arg):
256 cmdlist.append(cmd+' '+arg)
257 else:
258 cmdlist.append(cmd)
259 # Determine if we must stop
260 try:
261 func = getattr(self, 'do_' + cmd)
262 except AttributeError:
263 func = self.default
264 if func.func_name in self.commands_resuming : # one of the resuming commands.
265 self.commands_doprompt[self.commands_bnum] = False
266 self.cmdqueue = []
267 return 1
268 return
269
Tim Peters2344fae2001-01-15 00:50:52 +0000270 # Command definitions, called by cmdloop()
271 # The argument is the remaining string on the command line
272 # Return true to exit from the command loop
273
274 do_h = cmd.Cmd.do_help
275
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000276 def do_commands(self, arg):
277 """Defines a list of commands associated to a breakpoint
278 Those commands will be executed whenever the breakpoint causes the program to stop execution."""
279 if not arg:
280 bnum = len(bdb.Breakpoint.bpbynumber)-1
281 else:
282 try:
283 bnum = int(arg)
284 except:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000285 print >>self.stdout, "Usage : commands [bnum]\n ...\n end"
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000286 return
287 self.commands_bnum = bnum
288 self.commands[bnum] = []
289 self.commands_doprompt[bnum] = True
290 self.commands_silent[bnum] = False
291 prompt_back = self.prompt
292 self.prompt = '(com) '
293 self.commands_defining = True
294 self.cmdloop()
295 self.commands_defining = False
296 self.prompt = prompt_back
297
Tim Peters2344fae2001-01-15 00:50:52 +0000298 def do_break(self, arg, temporary = 0):
299 # break [ ([filename:]lineno | function) [, "condition"] ]
300 if not arg:
301 if self.breaks: # There's at least one
Thomas Wouters477c8d52006-05-27 19:21:47 +0000302 print >>self.stdout, "Num Type Disp Enb Where"
Tim Peters2344fae2001-01-15 00:50:52 +0000303 for bp in bdb.Breakpoint.bpbynumber:
304 if bp:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000305 bp.bpprint(self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000306 return
307 # parse arguments; comma has lowest precedence
308 # and cannot occur in filename
309 filename = None
310 lineno = None
311 cond = None
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000312 comma = arg.find(',')
Tim Peters2344fae2001-01-15 00:50:52 +0000313 if comma > 0:
314 # parse stuff after comma: "condition"
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000315 cond = arg[comma+1:].lstrip()
316 arg = arg[:comma].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000317 # parse stuff before comma: [filename:]lineno | function
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000318 colon = arg.rfind(':')
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000319 funcname = None
Tim Peters2344fae2001-01-15 00:50:52 +0000320 if colon >= 0:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000321 filename = arg[:colon].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000322 f = self.lookupmodule(filename)
323 if not f:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000324 print >>self.stdout, '*** ', repr(filename),
325 print >>self.stdout, 'not found from sys.path'
Tim Peters2344fae2001-01-15 00:50:52 +0000326 return
327 else:
328 filename = f
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000329 arg = arg[colon+1:].lstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000330 try:
331 lineno = int(arg)
332 except ValueError, msg:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000333 print >>self.stdout, '*** Bad lineno:', arg
Tim Peters2344fae2001-01-15 00:50:52 +0000334 return
335 else:
336 # no colon; can be lineno or function
337 try:
338 lineno = int(arg)
339 except ValueError:
340 try:
341 func = eval(arg,
342 self.curframe.f_globals,
343 self.curframe.f_locals)
344 except:
345 func = arg
346 try:
347 if hasattr(func, 'im_func'):
348 func = func.im_func
349 code = func.func_code
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000350 #use co_name to identify the bkpt (function names
351 #could be aliased, but co_name is invariant)
352 funcname = code.co_name
Tim Peters2344fae2001-01-15 00:50:52 +0000353 lineno = code.co_firstlineno
354 filename = code.co_filename
355 except:
356 # last thing to try
357 (ok, filename, ln) = self.lineinfo(arg)
358 if not ok:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000359 print >>self.stdout, '*** The specified object',
360 print >>self.stdout, repr(arg),
361 print >>self.stdout, 'is not a function'
362 print >>self.stdout, 'or was not found along sys.path.'
Tim Peters2344fae2001-01-15 00:50:52 +0000363 return
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000364 funcname = ok # ok contains a function name
Tim Peters2344fae2001-01-15 00:50:52 +0000365 lineno = int(ln)
366 if not filename:
367 filename = self.defaultFile()
368 # Check for reasonable breakpoint
369 line = self.checkline(filename, lineno)
370 if line:
371 # now set the break point
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000372 err = self.set_break(filename, line, temporary, cond, funcname)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000373 if err: print >>self.stdout, '***', err
Tim Peters2344fae2001-01-15 00:50:52 +0000374 else:
375 bp = self.get_breaks(filename, line)[-1]
Thomas Wouters477c8d52006-05-27 19:21:47 +0000376 print >>self.stdout, "Breakpoint %d at %s:%d" % (bp.number,
377 bp.file,
378 bp.line)
Tim Peters2344fae2001-01-15 00:50:52 +0000379
380 # To be overridden in derived debuggers
381 def defaultFile(self):
382 """Produce a reasonable default."""
383 filename = self.curframe.f_code.co_filename
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000384 if filename == '<string>' and self.mainpyfile:
385 filename = self.mainpyfile
Tim Peters2344fae2001-01-15 00:50:52 +0000386 return filename
387
388 do_b = do_break
389
390 def do_tbreak(self, arg):
391 self.do_break(arg, 1)
392
393 def lineinfo(self, identifier):
394 failed = (None, None, None)
395 # Input is identifier, may be in single quotes
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000396 idstring = identifier.split("'")
Tim Peters2344fae2001-01-15 00:50:52 +0000397 if len(idstring) == 1:
398 # not in single quotes
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000399 id = idstring[0].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000400 elif len(idstring) == 3:
401 # quoted
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000402 id = idstring[1].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000403 else:
404 return failed
405 if id == '': return failed
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000406 parts = id.split('.')
Tim Peters2344fae2001-01-15 00:50:52 +0000407 # Protection for derived debuggers
408 if parts[0] == 'self':
409 del parts[0]
410 if len(parts) == 0:
411 return failed
412 # Best first guess at file to look at
413 fname = self.defaultFile()
414 if len(parts) == 1:
415 item = parts[0]
416 else:
417 # More than one part.
418 # First is module, second is method/class
419 f = self.lookupmodule(parts[0])
420 if f:
421 fname = f
422 item = parts[1]
423 answer = find_function(item, fname)
424 return answer or failed
425
426 def checkline(self, filename, lineno):
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000427 """Check whether specified line seems to be executable.
Tim Peters2344fae2001-01-15 00:50:52 +0000428
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000429 Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
430 line or EOF). Warning: testing is not comprehensive.
431 """
Tim Peters2344fae2001-01-15 00:50:52 +0000432 line = linecache.getline(filename, lineno)
433 if not line:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000434 print >>self.stdout, 'End of file'
Tim Peters2344fae2001-01-15 00:50:52 +0000435 return 0
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000436 line = line.strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000437 # Don't allow setting breakpoint at a blank line
Guido van Rossum08454592002-07-12 13:10:53 +0000438 if (not line or (line[0] == '#') or
439 (line[:3] == '"""') or line[:3] == "'''"):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000440 print >>self.stdout, '*** Blank or comment'
Tim Peters2344fae2001-01-15 00:50:52 +0000441 return 0
Tim Peters2344fae2001-01-15 00:50:52 +0000442 return lineno
443
444 def do_enable(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000445 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000446 for i in args:
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000447 try:
448 i = int(i)
449 except ValueError:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000450 print >>self.stdout, 'Breakpoint index %r is not a number' % i
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000451 continue
452
453 if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000454 print >>self.stdout, 'No breakpoint numbered', i
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000455 continue
456
457 bp = bdb.Breakpoint.bpbynumber[i]
Tim Peters2344fae2001-01-15 00:50:52 +0000458 if bp:
459 bp.enable()
460
461 def do_disable(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000462 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000463 for i in args:
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000464 try:
465 i = int(i)
466 except ValueError:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000467 print >>self.stdout, 'Breakpoint index %r is not a number' % i
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000468 continue
Tim Petersf545baa2003-06-15 23:26:30 +0000469
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000470 if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000471 print >>self.stdout, 'No breakpoint numbered', i
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000472 continue
473
474 bp = bdb.Breakpoint.bpbynumber[i]
Tim Peters2344fae2001-01-15 00:50:52 +0000475 if bp:
476 bp.disable()
477
478 def do_condition(self, arg):
479 # arg is breakpoint number and condition
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000480 args = arg.split(' ', 1)
481 bpnum = int(args[0].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000482 try:
483 cond = args[1]
484 except:
485 cond = None
486 bp = bdb.Breakpoint.bpbynumber[bpnum]
487 if bp:
488 bp.cond = cond
489 if not cond:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000490 print >>self.stdout, 'Breakpoint', bpnum,
491 print >>self.stdout, 'is now unconditional.'
Tim Peters2344fae2001-01-15 00:50:52 +0000492
493 def do_ignore(self,arg):
494 """arg is bp number followed by ignore count."""
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000495 args = arg.split()
496 bpnum = int(args[0].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000497 try:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000498 count = int(args[1].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000499 except:
500 count = 0
501 bp = bdb.Breakpoint.bpbynumber[bpnum]
502 if bp:
503 bp.ignore = count
Guido van Rossum08454592002-07-12 13:10:53 +0000504 if count > 0:
Tim Peters2344fae2001-01-15 00:50:52 +0000505 reply = 'Will ignore next '
Guido van Rossum08454592002-07-12 13:10:53 +0000506 if count > 1:
Tim Peters2344fae2001-01-15 00:50:52 +0000507 reply = reply + '%d crossings' % count
508 else:
509 reply = reply + '1 crossing'
Thomas Wouters477c8d52006-05-27 19:21:47 +0000510 print >>self.stdout, reply + ' of breakpoint %d.' % bpnum
Tim Peters2344fae2001-01-15 00:50:52 +0000511 else:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000512 print >>self.stdout, 'Will stop next time breakpoint',
513 print >>self.stdout, bpnum, 'is reached.'
Tim Peters2344fae2001-01-15 00:50:52 +0000514
515 def do_clear(self, arg):
516 """Three possibilities, tried in this order:
517 clear -> clear all breaks, ask for confirmation
518 clear file:lineno -> clear all breaks at file:lineno
519 clear bpno bpno ... -> clear breakpoints by number"""
520 if not arg:
521 try:
522 reply = raw_input('Clear all breaks? ')
523 except EOFError:
524 reply = 'no'
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000525 reply = reply.strip().lower()
Tim Peters2344fae2001-01-15 00:50:52 +0000526 if reply in ('y', 'yes'):
527 self.clear_all_breaks()
528 return
529 if ':' in arg:
530 # Make sure it works for "clear C:\foo\bar.py:12"
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000531 i = arg.rfind(':')
Tim Peters2344fae2001-01-15 00:50:52 +0000532 filename = arg[:i]
533 arg = arg[i+1:]
534 try:
535 lineno = int(arg)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000536 except ValueError:
Tim Peters2344fae2001-01-15 00:50:52 +0000537 err = "Invalid line number (%s)" % arg
538 else:
539 err = self.clear_break(filename, lineno)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000540 if err: print >>self.stdout, '***', err
Tim Peters2344fae2001-01-15 00:50:52 +0000541 return
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000542 numberlist = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000543 for i in numberlist:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000544 try:
545 i = int(i)
546 except ValueError:
547 print >>self.stdout, 'Breakpoint index %r is not a number' % i
548 continue
549
Georg Brandl6d2b3462005-08-24 07:36:17 +0000550 if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000551 print >>self.stdout, 'No breakpoint numbered', i
Georg Brandl6d2b3462005-08-24 07:36:17 +0000552 continue
Tim Peters2344fae2001-01-15 00:50:52 +0000553 err = self.clear_bpbynumber(i)
554 if err:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000555 print >>self.stdout, '***', err
Tim Peters2344fae2001-01-15 00:50:52 +0000556 else:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000557 print >>self.stdout, 'Deleted breakpoint', i
Tim Peters2344fae2001-01-15 00:50:52 +0000558 do_cl = do_clear # 'c' is already an abbreviation for 'continue'
559
560 def do_where(self, arg):
561 self.print_stack_trace()
562 do_w = do_where
Guido van Rossum6bd68352001-01-20 17:57:37 +0000563 do_bt = do_where
Tim Peters2344fae2001-01-15 00:50:52 +0000564
565 def do_up(self, arg):
566 if self.curindex == 0:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000567 print >>self.stdout, '*** Oldest frame'
Tim Peters2344fae2001-01-15 00:50:52 +0000568 else:
569 self.curindex = self.curindex - 1
570 self.curframe = self.stack[self.curindex][0]
571 self.print_stack_entry(self.stack[self.curindex])
572 self.lineno = None
573 do_u = do_up
574
575 def do_down(self, arg):
576 if self.curindex + 1 == len(self.stack):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000577 print >>self.stdout, '*** Newest frame'
Tim Peters2344fae2001-01-15 00:50:52 +0000578 else:
579 self.curindex = self.curindex + 1
580 self.curframe = self.stack[self.curindex][0]
581 self.print_stack_entry(self.stack[self.curindex])
582 self.lineno = None
583 do_d = do_down
584
585 def do_step(self, arg):
586 self.set_step()
587 return 1
588 do_s = do_step
589
590 def do_next(self, arg):
591 self.set_next(self.curframe)
592 return 1
593 do_n = do_next
594
595 def do_return(self, arg):
596 self.set_return(self.curframe)
597 return 1
598 do_r = do_return
599
600 def do_continue(self, arg):
601 self.set_continue()
602 return 1
603 do_c = do_cont = do_continue
604
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000605 def do_jump(self, arg):
606 if self.curindex + 1 != len(self.stack):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000607 print >>self.stdout, "*** You can only jump within the bottom frame"
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000608 return
609 try:
610 arg = int(arg)
611 except ValueError:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000612 print >>self.stdout, "*** The 'jump' command requires a line number."
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000613 else:
614 try:
615 # Do the jump, fix up our copy of the stack, and display the
616 # new position
617 self.curframe.f_lineno = arg
618 self.stack[self.curindex] = self.stack[self.curindex][0], arg
619 self.print_stack_entry(self.stack[self.curindex])
620 except ValueError, e:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000621 print >>self.stdout, '*** Jump failed:', e
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000622 do_j = do_jump
623
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000624 def do_debug(self, arg):
625 sys.settrace(None)
626 globals = self.curframe.f_globals
627 locals = self.curframe.f_locals
Guido van Rossumed538d82003-04-09 19:36:34 +0000628 p = Pdb()
629 p.prompt = "(%s) " % self.prompt.strip()
Thomas Wouters477c8d52006-05-27 19:21:47 +0000630 print >>self.stdout, "ENTERING RECURSIVE DEBUGGER"
Guido van Rossumed538d82003-04-09 19:36:34 +0000631 sys.call_tracing(p.run, (arg, globals, locals))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000632 print >>self.stdout, "LEAVING RECURSIVE DEBUGGER"
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000633 sys.settrace(self.trace_dispatch)
634 self.lastcmd = p.lastcmd
635
Tim Peters2344fae2001-01-15 00:50:52 +0000636 def do_quit(self, arg):
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000637 self._user_requested_quit = 1
Tim Peters2344fae2001-01-15 00:50:52 +0000638 self.set_quit()
639 return 1
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000640
Tim Peters2344fae2001-01-15 00:50:52 +0000641 do_q = do_quit
Guido van Rossumd1c08f32002-04-15 00:48:24 +0000642 do_exit = do_quit
Tim Peters2344fae2001-01-15 00:50:52 +0000643
Guido van Rossumeef26072003-01-13 21:13:55 +0000644 def do_EOF(self, arg):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000645 print >>self.stdout
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000646 self._user_requested_quit = 1
Guido van Rossumeef26072003-01-13 21:13:55 +0000647 self.set_quit()
648 return 1
649
Tim Peters2344fae2001-01-15 00:50:52 +0000650 def do_args(self, arg):
651 f = self.curframe
652 co = f.f_code
653 dict = f.f_locals
654 n = co.co_argcount
655 if co.co_flags & 4: n = n+1
656 if co.co_flags & 8: n = n+1
657 for i in range(n):
658 name = co.co_varnames[i]
Thomas Wouters477c8d52006-05-27 19:21:47 +0000659 print >>self.stdout, name, '=',
660 if name in dict: print >>self.stdout, dict[name]
661 else: print >>self.stdout, "*** undefined ***"
Tim Peters2344fae2001-01-15 00:50:52 +0000662 do_a = do_args
Guido van Rossum2424f851998-09-11 22:50:09 +0000663
Tim Peters2344fae2001-01-15 00:50:52 +0000664 def do_retval(self, arg):
Raymond Hettinger54f02222002-06-01 14:18:47 +0000665 if '__return__' in self.curframe.f_locals:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000666 print >>self.stdout, self.curframe.f_locals['__return__']
Tim Peters2344fae2001-01-15 00:50:52 +0000667 else:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000668 print >>self.stdout, '*** Not yet returned!'
Tim Peters2344fae2001-01-15 00:50:52 +0000669 do_rv = do_retval
Guido van Rossum2424f851998-09-11 22:50:09 +0000670
Barry Warsaw210bd202002-11-05 22:40:20 +0000671 def _getval(self, arg):
Tim Peters2344fae2001-01-15 00:50:52 +0000672 try:
Barry Warsaw210bd202002-11-05 22:40:20 +0000673 return eval(arg, self.curframe.f_globals,
674 self.curframe.f_locals)
Tim Peters2344fae2001-01-15 00:50:52 +0000675 except:
676 t, v = sys.exc_info()[:2]
Barry Warsaw210bd202002-11-05 22:40:20 +0000677 if isinstance(t, str):
Tim Peters2344fae2001-01-15 00:50:52 +0000678 exc_type_name = t
679 else: exc_type_name = t.__name__
Thomas Wouters477c8d52006-05-27 19:21:47 +0000680 print >>self.stdout, '***', exc_type_name + ':', repr(v)
Barry Warsaw210bd202002-11-05 22:40:20 +0000681 raise
Guido van Rossum2424f851998-09-11 22:50:09 +0000682
Barry Warsaw210bd202002-11-05 22:40:20 +0000683 def do_p(self, arg):
684 try:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000685 print >>self.stdout, repr(self._getval(arg))
Barry Warsaw210bd202002-11-05 22:40:20 +0000686 except:
687 pass
688
689 def do_pp(self, arg):
690 try:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000691 pprint.pprint(self._getval(arg), self.stdout)
Barry Warsaw210bd202002-11-05 22:40:20 +0000692 except:
693 pass
Guido van Rossum2424f851998-09-11 22:50:09 +0000694
Tim Peters2344fae2001-01-15 00:50:52 +0000695 def do_list(self, arg):
696 self.lastcmd = 'list'
697 last = None
698 if arg:
699 try:
700 x = eval(arg, {}, {})
701 if type(x) == type(()):
702 first, last = x
703 first = int(first)
704 last = int(last)
705 if last < first:
706 # Assume it's a count
707 last = first + last
708 else:
709 first = max(1, int(x) - 5)
710 except:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000711 print >>self.stdout, '*** Error in argument:', repr(arg)
Tim Peters2344fae2001-01-15 00:50:52 +0000712 return
713 elif self.lineno is None:
714 first = max(1, self.curframe.f_lineno - 5)
715 else:
716 first = self.lineno + 1
717 if last is None:
718 last = first + 10
719 filename = self.curframe.f_code.co_filename
720 breaklist = self.get_file_breaks(filename)
721 try:
722 for lineno in range(first, last+1):
723 line = linecache.getline(filename, lineno)
724 if not line:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000725 print >>self.stdout, '[EOF]'
Tim Peters2344fae2001-01-15 00:50:52 +0000726 break
727 else:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000728 s = repr(lineno).rjust(3)
Tim Peters2344fae2001-01-15 00:50:52 +0000729 if len(s) < 4: s = s + ' '
730 if lineno in breaklist: s = s + 'B'
731 else: s = s + ' '
732 if lineno == self.curframe.f_lineno:
733 s = s + '->'
Thomas Wouters477c8d52006-05-27 19:21:47 +0000734 print >>self.stdout, s + '\t' + line,
Tim Peters2344fae2001-01-15 00:50:52 +0000735 self.lineno = lineno
736 except KeyboardInterrupt:
737 pass
738 do_l = do_list
Guido van Rossum2424f851998-09-11 22:50:09 +0000739
Tim Peters2344fae2001-01-15 00:50:52 +0000740 def do_whatis(self, arg):
741 try:
742 value = eval(arg, self.curframe.f_globals,
743 self.curframe.f_locals)
744 except:
745 t, v = sys.exc_info()[:2]
746 if type(t) == type(''):
747 exc_type_name = t
748 else: exc_type_name = t.__name__
Thomas Wouters477c8d52006-05-27 19:21:47 +0000749 print >>self.stdout, '***', exc_type_name + ':', repr(v)
Tim Peters2344fae2001-01-15 00:50:52 +0000750 return
751 code = None
752 # Is it a function?
753 try: code = value.func_code
754 except: pass
755 if code:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000756 print >>self.stdout, 'Function', code.co_name
Tim Peters2344fae2001-01-15 00:50:52 +0000757 return
758 # Is it an instance method?
759 try: code = value.im_func.func_code
760 except: pass
761 if code:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000762 print >>self.stdout, 'Method', code.co_name
Tim Peters2344fae2001-01-15 00:50:52 +0000763 return
764 # None of the above...
Thomas Wouters477c8d52006-05-27 19:21:47 +0000765 print >>self.stdout, type(value)
Guido van Rossum8e2ec561993-07-29 09:37:38 +0000766
Tim Peters2344fae2001-01-15 00:50:52 +0000767 def do_alias(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000768 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000769 if len(args) == 0:
770 keys = self.aliases.keys()
771 keys.sort()
772 for alias in keys:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000773 print >>self.stdout, "%s = %s" % (alias, self.aliases[alias])
Tim Peters2344fae2001-01-15 00:50:52 +0000774 return
Guido van Rossum08454592002-07-12 13:10:53 +0000775 if args[0] in self.aliases and len(args) == 1:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000776 print >>self.stdout, "%s = %s" % (args[0], self.aliases[args[0]])
Tim Peters2344fae2001-01-15 00:50:52 +0000777 else:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000778 self.aliases[args[0]] = ' '.join(args[1:])
Guido van Rossum23efba41992-01-27 16:58:47 +0000779
Tim Peters2344fae2001-01-15 00:50:52 +0000780 def do_unalias(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000781 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000782 if len(args) == 0: return
Raymond Hettinger54f02222002-06-01 14:18:47 +0000783 if args[0] in self.aliases:
Tim Peters2344fae2001-01-15 00:50:52 +0000784 del self.aliases[args[0]]
Guido van Rossum00230781993-03-29 11:39:45 +0000785
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000786 #list of all the commands making the program resume execution.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000787 commands_resuming = ['do_continue', 'do_step', 'do_next', 'do_return',
788 'do_quit', 'do_jump']
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000789
Tim Peters2344fae2001-01-15 00:50:52 +0000790 # Print a traceback starting at the top stack frame.
791 # The most recently entered frame is printed last;
792 # this is different from dbx and gdb, but consistent with
793 # the Python interpreter's stack trace.
794 # It is also consistent with the up/down commands (which are
795 # compatible with dbx and gdb: up moves towards 'main()'
796 # and down moves towards the most recent stack frame).
Guido van Rossum2424f851998-09-11 22:50:09 +0000797
Tim Peters2344fae2001-01-15 00:50:52 +0000798 def print_stack_trace(self):
799 try:
800 for frame_lineno in self.stack:
801 self.print_stack_entry(frame_lineno)
802 except KeyboardInterrupt:
803 pass
Guido van Rossum2424f851998-09-11 22:50:09 +0000804
Tim Peters2344fae2001-01-15 00:50:52 +0000805 def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix):
806 frame, lineno = frame_lineno
807 if frame is self.curframe:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000808 print >>self.stdout, '>',
Tim Peters2344fae2001-01-15 00:50:52 +0000809 else:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000810 print >>self.stdout, ' ',
811 print >>self.stdout, self.format_stack_entry(frame_lineno,
812 prompt_prefix)
Guido van Rossum2424f851998-09-11 22:50:09 +0000813
Guido van Rossum921c8241992-01-10 14:54:42 +0000814
Tim Peters2344fae2001-01-15 00:50:52 +0000815 # Help methods (derived from pdb.doc)
Guido van Rossum921c8241992-01-10 14:54:42 +0000816
Tim Peters2344fae2001-01-15 00:50:52 +0000817 def help_help(self):
818 self.help_h()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000819
Tim Peters2344fae2001-01-15 00:50:52 +0000820 def help_h(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000821 print >>self.stdout, """h(elp)
Tim Peters2344fae2001-01-15 00:50:52 +0000822Without argument, print the list of available commands.
823With a command name as argument, print help about that command
824"help pdb" pipes the full documentation file to the $PAGER
825"help exec" gives help on the ! command"""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000826
Tim Peters2344fae2001-01-15 00:50:52 +0000827 def help_where(self):
828 self.help_w()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000829
Tim Peters2344fae2001-01-15 00:50:52 +0000830 def help_w(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000831 print >>self.stdout, """w(here)
Tim Peters2344fae2001-01-15 00:50:52 +0000832Print a stack trace, with the most recent frame at the bottom.
833An arrow indicates the "current frame", which determines the
Guido van Rossum6bd68352001-01-20 17:57:37 +0000834context of most commands. 'bt' is an alias for this command."""
835
836 help_bt = help_w
Guido van Rossumb6775db1994-08-01 11:34:53 +0000837
Tim Peters2344fae2001-01-15 00:50:52 +0000838 def help_down(self):
839 self.help_d()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000840
Tim Peters2344fae2001-01-15 00:50:52 +0000841 def help_d(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000842 print >>self.stdout, """d(own)
Tim Peters2344fae2001-01-15 00:50:52 +0000843Move the current frame one level down in the stack trace
Johannes Gijsbers34c41202004-08-14 15:19:28 +0000844(to a newer frame)."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000845
Tim Peters2344fae2001-01-15 00:50:52 +0000846 def help_up(self):
847 self.help_u()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000848
Tim Peters2344fae2001-01-15 00:50:52 +0000849 def help_u(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000850 print >>self.stdout, """u(p)
Tim Peters2344fae2001-01-15 00:50:52 +0000851Move the current frame one level up in the stack trace
Johannes Gijsbers34c41202004-08-14 15:19:28 +0000852(to an older frame)."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000853
Tim Peters2344fae2001-01-15 00:50:52 +0000854 def help_break(self):
855 self.help_b()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000856
Tim Peters2344fae2001-01-15 00:50:52 +0000857 def help_b(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000858 print >>self.stdout, """b(reak) ([file:]lineno | function) [, condition]
Tim Peters2344fae2001-01-15 00:50:52 +0000859With a line number argument, set a break there in the current
860file. With a function name, set a break at first executable line
861of that function. Without argument, list all breaks. If a second
862argument is present, it is a string specifying an expression
863which must evaluate to true before the breakpoint is honored.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000864
Tim Peters2344fae2001-01-15 00:50:52 +0000865The line number may be prefixed with a filename and a colon,
866to specify a breakpoint in another file (probably one that
867hasn't been loaded yet). The file is searched for on sys.path;
868the .py suffix may be omitted."""
Guido van Rossumb5699c71998-07-20 23:13:54 +0000869
Tim Peters2344fae2001-01-15 00:50:52 +0000870 def help_clear(self):
871 self.help_cl()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000872
Tim Peters2344fae2001-01-15 00:50:52 +0000873 def help_cl(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000874 print >>self.stdout, "cl(ear) filename:lineno"
875 print >>self.stdout, """cl(ear) [bpnumber [bpnumber...]]
Tim Peters2344fae2001-01-15 00:50:52 +0000876With a space separated list of breakpoint numbers, clear
877those breakpoints. Without argument, clear all breaks (but
878first ask confirmation). With a filename:lineno argument,
879clear all breaks at that line in that file.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000880
Tim Peters2344fae2001-01-15 00:50:52 +0000881Note that the argument is different from previous versions of
882the debugger (in python distributions 1.5.1 and before) where
883a linenumber was used instead of either filename:lineno or
884breakpoint numbers."""
Guido van Rossumb5699c71998-07-20 23:13:54 +0000885
Tim Peters2344fae2001-01-15 00:50:52 +0000886 def help_tbreak(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000887 print >>self.stdout, """tbreak same arguments as break, but breakpoint is
Tim Peters2344fae2001-01-15 00:50:52 +0000888removed when first hit."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000889
Tim Peters2344fae2001-01-15 00:50:52 +0000890 def help_enable(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000891 print >>self.stdout, """enable bpnumber [bpnumber ...]
Tim Peters2344fae2001-01-15 00:50:52 +0000892Enables the breakpoints given as a space separated list of
893bp numbers."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000894
Tim Peters2344fae2001-01-15 00:50:52 +0000895 def help_disable(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000896 print >>self.stdout, """disable bpnumber [bpnumber ...]
Tim Peters2344fae2001-01-15 00:50:52 +0000897Disables the breakpoints given as a space separated list of
898bp numbers."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000899
Tim Peters2344fae2001-01-15 00:50:52 +0000900 def help_ignore(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000901 print >>self.stdout, """ignore bpnumber count
Tim Peters2344fae2001-01-15 00:50:52 +0000902Sets the ignore count for the given breakpoint number. A breakpoint
903becomes active when the ignore count is zero. When non-zero, the
904count is decremented each time the breakpoint is reached and the
905breakpoint is not disabled and any associated condition evaluates
906to true."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000907
Tim Peters2344fae2001-01-15 00:50:52 +0000908 def help_condition(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000909 print >>self.stdout, """condition bpnumber str_condition
Tim Peters2344fae2001-01-15 00:50:52 +0000910str_condition is a string specifying an expression which
911must evaluate to true before the breakpoint is honored.
912If str_condition is absent, any existing condition is removed;
913i.e., the breakpoint is made unconditional."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000914
Tim Peters2344fae2001-01-15 00:50:52 +0000915 def help_step(self):
916 self.help_s()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000917
Tim Peters2344fae2001-01-15 00:50:52 +0000918 def help_s(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000919 print >>self.stdout, """s(tep)
Tim Peters2344fae2001-01-15 00:50:52 +0000920Execute the current line, stop at the first possible occasion
921(either in a function that is called or in the current function)."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000922
Tim Peters2344fae2001-01-15 00:50:52 +0000923 def help_next(self):
924 self.help_n()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000925
Tim Peters2344fae2001-01-15 00:50:52 +0000926 def help_n(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000927 print >>self.stdout, """n(ext)
Tim Peters2344fae2001-01-15 00:50:52 +0000928Continue execution until the next line in the current function
929is reached or it returns."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000930
Tim Peters2344fae2001-01-15 00:50:52 +0000931 def help_return(self):
932 self.help_r()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000933
Tim Peters2344fae2001-01-15 00:50:52 +0000934 def help_r(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000935 print >>self.stdout, """r(eturn)
Tim Peters2344fae2001-01-15 00:50:52 +0000936Continue execution until the current function returns."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000937
Tim Peters2344fae2001-01-15 00:50:52 +0000938 def help_continue(self):
939 self.help_c()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000940
Tim Peters2344fae2001-01-15 00:50:52 +0000941 def help_cont(self):
942 self.help_c()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000943
Tim Peters2344fae2001-01-15 00:50:52 +0000944 def help_c(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000945 print >>self.stdout, """c(ont(inue))
Tim Peters2344fae2001-01-15 00:50:52 +0000946Continue execution, only stop when a breakpoint is encountered."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000947
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000948 def help_jump(self):
949 self.help_j()
950
951 def help_j(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000952 print >>self.stdout, """j(ump) lineno
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000953Set the next line that will be executed."""
954
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000955 def help_debug(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000956 print >>self.stdout, """debug code
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000957Enter a recursive debugger that steps through the code argument
958(which is an arbitrary expression or statement to be executed
959in the current environment)."""
960
Tim Peters2344fae2001-01-15 00:50:52 +0000961 def help_list(self):
962 self.help_l()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000963
Tim Peters2344fae2001-01-15 00:50:52 +0000964 def help_l(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000965 print >>self.stdout, """l(ist) [first [,last]]
Tim Peters2344fae2001-01-15 00:50:52 +0000966List source code for the current file.
967Without arguments, list 11 lines around the current line
968or continue the previous listing.
969With one argument, list 11 lines starting at that line.
970With two arguments, list the given range;
971if the second argument is less than the first, it is a count."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000972
Tim Peters2344fae2001-01-15 00:50:52 +0000973 def help_args(self):
974 self.help_a()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000975
Tim Peters2344fae2001-01-15 00:50:52 +0000976 def help_a(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000977 print >>self.stdout, """a(rgs)
Tim Peters2344fae2001-01-15 00:50:52 +0000978Print the arguments of the current function."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000979
Tim Peters2344fae2001-01-15 00:50:52 +0000980 def help_p(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000981 print >>self.stdout, """p expression
Tim Peters2344fae2001-01-15 00:50:52 +0000982Print the value of the expression."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000983
Barry Warsaw210bd202002-11-05 22:40:20 +0000984 def help_pp(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000985 print >>self.stdout, """pp expression
Barry Warsaw210bd202002-11-05 22:40:20 +0000986Pretty-print the value of the expression."""
987
Tim Peters2344fae2001-01-15 00:50:52 +0000988 def help_exec(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000989 print >>self.stdout, """(!) statement
Tim Peters2344fae2001-01-15 00:50:52 +0000990Execute the (one-line) statement in the context of
991the current stack frame.
992The exclamation point can be omitted unless the first word
993of the statement resembles a debugger command.
994To assign to a global variable you must always prefix the
995command with a 'global' command, e.g.:
996(Pdb) global list_options; list_options = ['-l']
997(Pdb)"""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000998
Tim Peters2344fae2001-01-15 00:50:52 +0000999 def help_quit(self):
1000 self.help_q()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001001
Tim Peters2344fae2001-01-15 00:50:52 +00001002 def help_q(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001003 print >>self.stdout, """q(uit) or exit - Quit from the debugger.
Tim Peters2344fae2001-01-15 00:50:52 +00001004The program being executed is aborted."""
Guido van Rossumb6775db1994-08-01 11:34:53 +00001005
Guido van Rossumd1c08f32002-04-15 00:48:24 +00001006 help_exit = help_q
1007
Tim Peters2344fae2001-01-15 00:50:52 +00001008 def help_whatis(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001009 print >>self.stdout, """whatis arg
Tim Peters2344fae2001-01-15 00:50:52 +00001010Prints the type of the argument."""
Guido van Rossumb6775db1994-08-01 11:34:53 +00001011
Tim Peters2344fae2001-01-15 00:50:52 +00001012 def help_EOF(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001013 print >>self.stdout, """EOF
Tim Peters2344fae2001-01-15 00:50:52 +00001014Handles the receipt of EOF as a command."""
Guido van Rossum2424f851998-09-11 22:50:09 +00001015
Tim Peters2344fae2001-01-15 00:50:52 +00001016 def help_alias(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001017 print >>self.stdout, """alias [name [command [parameter parameter ...] ]]
Tim Peters2344fae2001-01-15 00:50:52 +00001018Creates an alias called 'name' the executes 'command'. The command
1019must *not* be enclosed in quotes. Replaceable parameters are
1020indicated by %1, %2, and so on, while %* is replaced by all the
1021parameters. If no command is given, the current alias for name
1022is shown. If no name is given, all aliases are listed.
Guido van Rossum2424f851998-09-11 22:50:09 +00001023
Tim Peters2344fae2001-01-15 00:50:52 +00001024Aliases may be nested and can contain anything that can be
1025legally typed at the pdb prompt. Note! You *can* override
1026internal pdb commands with aliases! Those internal commands
1027are then hidden until the alias is removed. Aliasing is recursively
1028applied to the first word of the command line; all other words
1029in the line are left alone.
Guido van Rossum2424f851998-09-11 22:50:09 +00001030
Tim Peters2344fae2001-01-15 00:50:52 +00001031Some useful aliases (especially when placed in the .pdbrc file) are:
Guido van Rossum2424f851998-09-11 22:50:09 +00001032
Tim Peters2344fae2001-01-15 00:50:52 +00001033#Print instance variables (usage "pi classInst")
1034alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
Guido van Rossum2424f851998-09-11 22:50:09 +00001035
Tim Peters2344fae2001-01-15 00:50:52 +00001036#Print instance variables in self
1037alias ps pi self
1038"""
Guido van Rossum2424f851998-09-11 22:50:09 +00001039
Tim Peters2344fae2001-01-15 00:50:52 +00001040 def help_unalias(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001041 print >>self.stdout, """unalias name
Tim Peters2344fae2001-01-15 00:50:52 +00001042Deletes the specified alias."""
Guido van Rossum2424f851998-09-11 22:50:09 +00001043
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001044 def help_commands(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001045 print >>self.stdout, """commands [bpnumber]
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001046(com) ...
1047(com) end
1048(Pdb)
1049
1050Specify a list of commands for breakpoint number bpnumber. The
1051commands themselves appear on the following lines. Type a line
1052containing just 'end' to terminate the commands.
1053
1054To remove all commands from a breakpoint, type commands and
1055follow it immediately with end; that is, give no commands.
1056
1057With no bpnumber argument, commands refers to the last
1058breakpoint set.
1059
1060You can use breakpoint commands to start your program up again.
1061Simply use the continue command, or step, or any other
1062command that resumes execution.
1063
1064Specifying any command resuming execution (currently continue,
1065step, next, return, jump, quit and their abbreviations) terminates
1066the command list (as if that command was immediately followed by end).
1067This is because any time you resume execution
1068(even with a simple next or step), you may encounter
1069another breakpoint--which could have its own command list, leading to
1070ambiguities about which list to execute.
1071
1072 If you use the 'silent' command in the command list, the
1073usual message about stopping at a breakpoint is not printed. This may
1074be desirable for breakpoints that are to print a specific message and
1075then continue. If none of the other commands print anything, you
1076see no sign that the breakpoint was reached.
1077"""
1078
Tim Peters2344fae2001-01-15 00:50:52 +00001079 def help_pdb(self):
1080 help()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001081
Tim Peters2344fae2001-01-15 00:50:52 +00001082 def lookupmodule(self, filename):
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001083 """Helper function for break/clear parsing -- may be overridden.
1084
1085 lookupmodule() translates (possibly incomplete) file or module name
1086 into an absolute file name.
1087 """
1088 if os.path.isabs(filename) and os.path.exists(filename):
Tim Peterse718f612004-10-12 21:51:32 +00001089 return filename
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001090 f = os.path.join(sys.path[0], filename)
1091 if os.path.exists(f) and self.canonic(f) == self.mainpyfile:
1092 return f
Tim Peters2344fae2001-01-15 00:50:52 +00001093 root, ext = os.path.splitext(filename)
1094 if ext == '':
1095 filename = filename + '.py'
1096 if os.path.isabs(filename):
1097 return filename
1098 for dirname in sys.path:
1099 while os.path.islink(dirname):
1100 dirname = os.readlink(dirname)
1101 fullname = os.path.join(dirname, filename)
1102 if os.path.exists(fullname):
1103 return fullname
1104 return None
Guido van Rossumb5699c71998-07-20 23:13:54 +00001105
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001106 def _runscript(self, filename):
1107 # Start with fresh empty copy of globals and locals and tell the script
1108 # that it's being run as __main__ to avoid scripts being able to access
1109 # the pdb.py namespace.
Tim Peterse718f612004-10-12 21:51:32 +00001110 globals_ = {"__name__" : "__main__"}
1111 locals_ = globals_
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001112
1113 # When bdb sets tracing, a number of call and line events happens
1114 # BEFORE debugger even reaches user's code (and the exact sequence of
1115 # events depends on python version). So we take special measures to
1116 # avoid stopping before we reach the main script (see user_line and
1117 # user_call for details).
1118 self._wait_for_mainpyfile = 1
1119 self.mainpyfile = self.canonic(filename)
1120 self._user_requested_quit = 0
1121 statement = 'execfile( "%s")' % filename
1122 self.run(statement, globals=globals_, locals=locals_)
1123
Guido van Rossum35771131992-09-08 11:59:04 +00001124# Simplified interface
1125
Guido van Rossum5e38b6f1995-02-27 13:13:40 +00001126def run(statement, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +00001127 Pdb().run(statement, globals, locals)
Guido van Rossum5e38b6f1995-02-27 13:13:40 +00001128
1129def runeval(expression, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +00001130 return Pdb().runeval(expression, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001131
1132def runctx(statement, globals, locals):
Tim Peters2344fae2001-01-15 00:50:52 +00001133 # B/W compatibility
1134 run(statement, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001135
Raymond Hettinger2ef7e6c2004-10-24 00:32:24 +00001136def runcall(*args, **kwds):
1137 return Pdb().runcall(*args, **kwds)
Guido van Rossum4e160981992-09-02 20:43:20 +00001138
Guido van Rossumb6775db1994-08-01 11:34:53 +00001139def set_trace():
Johannes Gijsbers84a6c202004-11-07 11:35:30 +00001140 Pdb().set_trace(sys._getframe().f_back)
Guido van Rossum35771131992-09-08 11:59:04 +00001141
1142# Post-Mortem interface
1143
1144def post_mortem(t):
Tim Peters2344fae2001-01-15 00:50:52 +00001145 p = Pdb()
1146 p.reset()
1147 while t.tb_next is not None:
1148 t = t.tb_next
1149 p.interaction(t.tb_frame, t)
Guido van Rossum35771131992-09-08 11:59:04 +00001150
1151def pm():
Tim Peters2344fae2001-01-15 00:50:52 +00001152 post_mortem(sys.last_traceback)
Guido van Rossum35771131992-09-08 11:59:04 +00001153
1154
1155# Main program for testing
1156
Guido van Rossum23efba41992-01-27 16:58:47 +00001157TESTCMD = 'import x; x.main()'
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001158
Guido van Rossum921c8241992-01-10 14:54:42 +00001159def test():
Tim Peters2344fae2001-01-15 00:50:52 +00001160 run(TESTCMD)
Guido van Rossume61fa0a1993-10-22 13:56:35 +00001161
1162# print help
1163def help():
Tim Peters2344fae2001-01-15 00:50:52 +00001164 for dirname in sys.path:
1165 fullname = os.path.join(dirname, 'pdb.doc')
1166 if os.path.exists(fullname):
1167 sts = os.system('${PAGER-more} '+fullname)
1168 if sts: print '*** Pager exit status:', sts
1169 break
1170 else:
1171 print 'Sorry, can\'t find the help file "pdb.doc"',
1172 print 'along the Python search path'
Guido van Rossumf17361d1996-07-30 16:28:13 +00001173
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001174def main():
Tim Peters2344fae2001-01-15 00:50:52 +00001175 if not sys.argv[1:]:
1176 print "usage: pdb.py scriptfile [arg] ..."
1177 sys.exit(2)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001178
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001179 mainpyfile = sys.argv[1] # Get script filename
1180 if not os.path.exists(mainpyfile):
1181 print 'Error:', mainpyfile, 'does not exist'
Tim Peters2344fae2001-01-15 00:50:52 +00001182 sys.exit(1)
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001183
Tim Peters2344fae2001-01-15 00:50:52 +00001184 del sys.argv[0] # Hide "pdb.py" from argument list
Guido van Rossumec577d51996-09-10 17:39:34 +00001185
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001186 # Replace pdb's dir with script's dir in front of module search path.
1187 sys.path[0] = os.path.dirname(mainpyfile)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001188
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001189 # Note on saving/restoring sys.argv: it's a good idea when sys.argv was
1190 # modified by the script being debugged. It's a bad idea when it was
1191 # changed by the user from the command line. The best approach would be to
1192 # have a "restart" command which would allow explicit specification of
1193 # command line arguments.
1194 pdb = Pdb()
1195 while 1:
1196 try:
1197 pdb._runscript(mainpyfile)
1198 if pdb._user_requested_quit:
1199 break
Tim Peterse718f612004-10-12 21:51:32 +00001200 print "The program finished and will be restarted"
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001201 except SystemExit:
1202 # In most cases SystemExit does not warrant a post-mortem session.
1203 print "The program exited via sys.exit(). Exit status: ",
1204 print sys.exc_info()[1]
1205 except:
1206 traceback.print_exc()
1207 print "Uncaught exception. Entering post mortem debugging"
1208 print "Running 'cont' or 'step' will restart the program"
1209 t = sys.exc_info()[2]
1210 while t.tb_next is not None:
1211 t = t.tb_next
1212 pdb.interaction(t.tb_frame,t)
1213 print "Post mortem debugger finished. The "+mainpyfile+" will be restarted"
1214
1215
1216# When invoked as main program, invoke the debugger on a script
1217if __name__=='__main__':
1218 main()