blob: 7d6a09ce89c2bc8561bea102faefdc2a8a59b40f [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
Barry Warsaw2bee8fe1999-09-09 16:32:41 +000025def find_function(funcname, filename):
Tim Peters2344fae2001-01-15 00:50:52 +000026 cre = re.compile(r'def\s+%s\s*[(]' % funcname)
27 try:
28 fp = open(filename)
29 except IOError:
30 return None
31 # consumer of this info expects the first line to be 1
32 lineno = 1
33 answer = None
34 while 1:
35 line = fp.readline()
36 if line == '':
37 break
38 if cre.match(line):
39 answer = funcname, filename, lineno
40 break
41 lineno = lineno + 1
42 fp.close()
43 return answer
Guido van Rossum921c8241992-01-10 14:54:42 +000044
45
Guido van Rossuma558e371994-11-10 22:27:35 +000046# Interaction prompt line will separate file and call info from code
47# text using value of line_prefix string. A newline and arrow may
48# be to your liking. You can set it once pdb is imported using the
49# command "pdb.line_prefix = '\n% '".
Tim Peters2344fae2001-01-15 00:50:52 +000050# line_prefix = ': ' # Use this to get the old situation back
51line_prefix = '\n-> ' # Probably a better default
Guido van Rossuma558e371994-11-10 22:27:35 +000052
Guido van Rossum23efba41992-01-27 16:58:47 +000053class Pdb(bdb.Bdb, cmd.Cmd):
Guido van Rossum2424f851998-09-11 22:50:09 +000054
Georg Brandl19564802006-05-10 17:13:20 +000055 def __init__(self, completekey='tab', stdin=None, stdout=None):
Tim Peters2344fae2001-01-15 00:50:52 +000056 bdb.Bdb.__init__(self)
Georg Brandl19564802006-05-10 17:13:20 +000057 cmd.Cmd.__init__(self, completekey, stdin, stdout)
58 if stdout:
59 self.use_rawinput = 0
Tim Peters2344fae2001-01-15 00:50:52 +000060 self.prompt = '(Pdb) '
61 self.aliases = {}
Johannes Gijsbers25b38c82004-10-12 18:12:09 +000062 self.mainpyfile = ''
63 self._wait_for_mainpyfile = 0
Tim Peters2344fae2001-01-15 00:50:52 +000064 # Try to load readline if it exists
65 try:
66 import readline
67 except ImportError:
68 pass
Guido van Rossum2424f851998-09-11 22:50:09 +000069
Tim Peters2344fae2001-01-15 00:50:52 +000070 # Read $HOME/.pdbrc and ./.pdbrc
71 self.rcLines = []
Raymond Hettinger54f02222002-06-01 14:18:47 +000072 if 'HOME' in os.environ:
Tim Peters2344fae2001-01-15 00:50:52 +000073 envHome = os.environ['HOME']
74 try:
75 rcFile = open(os.path.join(envHome, ".pdbrc"))
76 except IOError:
77 pass
78 else:
79 for line in rcFile.readlines():
80 self.rcLines.append(line)
81 rcFile.close()
82 try:
83 rcFile = open(".pdbrc")
84 except IOError:
85 pass
86 else:
87 for line in rcFile.readlines():
88 self.rcLines.append(line)
89 rcFile.close()
Guido van Rossum23efba41992-01-27 16:58:47 +000090
Martin v. Löwisbd30f522006-04-17 17:08:37 +000091 self.commands = {} # associates a command list to breakpoint numbers
92 self.commands_doprompt = {} # for each bp num, tells if the prompt must be disp. after execing the cmd list
93 self.commands_silent = {} # for each bp num, tells if the stack trace must be disp. after execing the cmd list
94 self.commands_defining = False # True while in the process of defining a command list
95 self.commands_bnum = None # The breakpoint number for which we are defining a list
96
Tim Peters2344fae2001-01-15 00:50:52 +000097 def reset(self):
98 bdb.Bdb.reset(self)
99 self.forget()
Guido van Rossum23efba41992-01-27 16:58:47 +0000100
Tim Peters2344fae2001-01-15 00:50:52 +0000101 def forget(self):
102 self.lineno = None
103 self.stack = []
104 self.curindex = 0
105 self.curframe = None
Guido van Rossum2424f851998-09-11 22:50:09 +0000106
Tim Peters2344fae2001-01-15 00:50:52 +0000107 def setup(self, f, t):
108 self.forget()
109 self.stack, self.curindex = self.get_stack(f, t)
110 self.curframe = self.stack[self.curindex][0]
111 self.execRcLines()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000112
Tim Peters2344fae2001-01-15 00:50:52 +0000113 # Can be executed earlier than 'setup' if desired
114 def execRcLines(self):
115 if self.rcLines:
116 # Make local copy because of recursion
117 rcLines = self.rcLines
118 # executed only once
119 self.rcLines = []
120 for line in rcLines:
121 line = line[:-1]
Guido van Rossum08454592002-07-12 13:10:53 +0000122 if len(line) > 0 and line[0] != '#':
123 self.onecmd(line)
Guido van Rossum2424f851998-09-11 22:50:09 +0000124
Tim Peters280488b2002-08-23 18:19:30 +0000125 # Override Bdb methods
Michael W. Hudsondd32a912002-08-15 14:59:02 +0000126
127 def user_call(self, frame, argument_list):
128 """This method is called when there is the remote possibility
129 that we ever need to stop in this function."""
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000130 if self._wait_for_mainpyfile:
131 return
Michael W. Hudson01eb85c2003-01-31 17:48:29 +0000132 if self.stop_here(frame):
Georg Brandl19564802006-05-10 17:13:20 +0000133 print >>self.stdout, '--Call--'
Michael W. Hudson01eb85c2003-01-31 17:48:29 +0000134 self.interaction(frame, None)
Guido van Rossum2424f851998-09-11 22:50:09 +0000135
Tim Peters2344fae2001-01-15 00:50:52 +0000136 def user_line(self, frame):
137 """This function is called when we stop or break at this line."""
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000138 if self._wait_for_mainpyfile:
139 if (self.mainpyfile != self.canonic(frame.f_code.co_filename)
140 or frame.f_lineno<= 0):
141 return
142 self._wait_for_mainpyfile = 0
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000143 if self.bp_commands(frame):
144 self.interaction(frame, None)
Martin v. Löwis1a00e182006-04-17 19:18:18 +0000145
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000146 def bp_commands(self,frame):
147 """ Call every command that was set for the current active breakpoint (if there is one)
148 Returns True if the normal interaction function must be called, False otherwise """
149 #self.currentbp is set in bdb.py in bdb.break_here if a breakpoint was hit
150 if getattr(self,"currentbp",False) and self.currentbp in self.commands:
151 currentbp = self.currentbp
152 self.currentbp = 0
153 lastcmd_back = self.lastcmd
154 self.setup(frame, None)
155 for line in self.commands[currentbp]:
156 self.onecmd(line)
157 self.lastcmd = lastcmd_back
158 if not self.commands_silent[currentbp]:
159 self.print_stack_entry(self.stack[self.curindex])
160 if self.commands_doprompt[currentbp]:
161 self.cmdloop()
162 self.forget()
Martin v. Löwis1a00e182006-04-17 19:18:18 +0000163 return
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000164 return 1
Guido van Rossum9e1ee971997-07-11 13:43:53 +0000165
Tim Peters2344fae2001-01-15 00:50:52 +0000166 def user_return(self, frame, return_value):
167 """This function is called when a return trap is set here."""
168 frame.f_locals['__return__'] = return_value
Georg Brandl19564802006-05-10 17:13:20 +0000169 print >>self.stdout, '--Return--'
Tim Peters2344fae2001-01-15 00:50:52 +0000170 self.interaction(frame, None)
Guido van Rossum2424f851998-09-11 22:50:09 +0000171
Tim Peters2344fae2001-01-15 00:50:52 +0000172 def user_exception(self, frame, (exc_type, exc_value, exc_traceback)):
173 """This function is called if an exception occurs,
174 but only if we are to stop at or just below this level."""
175 frame.f_locals['__exception__'] = exc_type, exc_value
176 if type(exc_type) == type(''):
177 exc_type_name = exc_type
178 else: exc_type_name = exc_type.__name__
Georg Brandl19564802006-05-10 17:13:20 +0000179 print >>self.stdout, exc_type_name + ':', _saferepr(exc_value)
Tim Peters2344fae2001-01-15 00:50:52 +0000180 self.interaction(frame, exc_traceback)
Guido van Rossum2424f851998-09-11 22:50:09 +0000181
Tim Peters2344fae2001-01-15 00:50:52 +0000182 # General interaction function
183
184 def interaction(self, frame, traceback):
185 self.setup(frame, traceback)
186 self.print_stack_entry(self.stack[self.curindex])
187 self.cmdloop()
188 self.forget()
189
190 def default(self, line):
191 if line[:1] == '!': line = line[1:]
192 locals = self.curframe.f_locals
193 globals = self.curframe.f_globals
194 try:
195 code = compile(line + '\n', '<stdin>', 'single')
196 exec code in globals, locals
197 except:
198 t, v = sys.exc_info()[:2]
199 if type(t) == type(''):
200 exc_type_name = t
201 else: exc_type_name = t.__name__
Georg Brandl19564802006-05-10 17:13:20 +0000202 print >>self.stdout, '***', exc_type_name + ':', v
Tim Peters2344fae2001-01-15 00:50:52 +0000203
204 def precmd(self, line):
205 """Handle alias expansion and ';;' separator."""
Guido van Rossum08454592002-07-12 13:10:53 +0000206 if not line.strip():
Tim Peters2344fae2001-01-15 00:50:52 +0000207 return line
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000208 args = line.split()
Raymond Hettinger54f02222002-06-01 14:18:47 +0000209 while args[0] in self.aliases:
Tim Peters2344fae2001-01-15 00:50:52 +0000210 line = self.aliases[args[0]]
211 ii = 1
212 for tmpArg in args[1:]:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000213 line = line.replace("%" + str(ii),
Tim Peters2344fae2001-01-15 00:50:52 +0000214 tmpArg)
215 ii = ii + 1
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000216 line = line.replace("%*", ' '.join(args[1:]))
217 args = line.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000218 # split into ';;' separated commands
219 # unless it's an alias command
220 if args[0] != 'alias':
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000221 marker = line.find(';;')
Tim Peters2344fae2001-01-15 00:50:52 +0000222 if marker >= 0:
223 # queue up everything after marker
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000224 next = line[marker+2:].lstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000225 self.cmdqueue.append(next)
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000226 line = line[:marker].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000227 return line
228
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000229 def onecmd(self, line):
230 """Interpret the argument as though it had been typed in response
Martin v. Löwis1a00e182006-04-17 19:18:18 +0000231 to the prompt.
232
Andrew M. Kuchling9aed98f2006-07-27 12:18:20 +0000233 Checks whether this line is typed at the normal prompt or in
Tim Petersdaea0352006-07-27 15:11:00 +0000234 a breakpoint command list definition.
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000235 """
236 if not self.commands_defining:
237 return cmd.Cmd.onecmd(self, line)
238 else:
239 return self.handle_command_def(line)
240
Martin v. Löwis1a00e182006-04-17 19:18:18 +0000241 def handle_command_def(self,line):
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000242 """ Handles one command line during command list definition. """
243 cmd, arg, line = self.parseline(line)
244 if cmd == 'silent':
245 self.commands_silent[self.commands_bnum] = True
246 return # continue to handle other cmd def in the cmd list
247 elif cmd == 'end':
248 self.cmdqueue = []
249 return 1 # end of cmd list
250 cmdlist = self.commands[self.commands_bnum]
251 if (arg):
252 cmdlist.append(cmd+' '+arg)
253 else:
254 cmdlist.append(cmd)
255 # Determine if we must stop
256 try:
257 func = getattr(self, 'do_' + cmd)
258 except AttributeError:
259 func = self.default
Martin v. Löwis1a00e182006-04-17 19:18:18 +0000260 if func.func_name in self.commands_resuming : # one of the resuming commands.
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000261 self.commands_doprompt[self.commands_bnum] = False
262 self.cmdqueue = []
263 return 1
Martin v. Löwis1a00e182006-04-17 19:18:18 +0000264 return
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000265
Tim Peters2344fae2001-01-15 00:50:52 +0000266 # Command definitions, called by cmdloop()
267 # The argument is the remaining string on the command line
268 # Return true to exit from the command loop
269
270 do_h = cmd.Cmd.do_help
271
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000272 def do_commands(self, arg):
273 """Defines a list of commands associated to a breakpoint
274 Those commands will be executed whenever the breakpoint causes the program to stop execution."""
275 if not arg:
276 bnum = len(bdb.Breakpoint.bpbynumber)-1
277 else:
278 try:
279 bnum = int(arg)
280 except:
Georg Brandl19564802006-05-10 17:13:20 +0000281 print >>self.stdout, "Usage : commands [bnum]\n ...\n end"
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000282 return
283 self.commands_bnum = bnum
284 self.commands[bnum] = []
285 self.commands_doprompt[bnum] = True
286 self.commands_silent[bnum] = False
287 prompt_back = self.prompt
288 self.prompt = '(com) '
289 self.commands_defining = True
290 self.cmdloop()
291 self.commands_defining = False
292 self.prompt = prompt_back
293
Tim Peters2344fae2001-01-15 00:50:52 +0000294 def do_break(self, arg, temporary = 0):
295 # break [ ([filename:]lineno | function) [, "condition"] ]
296 if not arg:
297 if self.breaks: # There's at least one
Georg Brandl19564802006-05-10 17:13:20 +0000298 print >>self.stdout, "Num Type Disp Enb Where"
Tim Peters2344fae2001-01-15 00:50:52 +0000299 for bp in bdb.Breakpoint.bpbynumber:
300 if bp:
Georg Brandl19564802006-05-10 17:13:20 +0000301 bp.bpprint(self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000302 return
303 # parse arguments; comma has lowest precedence
304 # and cannot occur in filename
305 filename = None
306 lineno = None
307 cond = None
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000308 comma = arg.find(',')
Tim Peters2344fae2001-01-15 00:50:52 +0000309 if comma > 0:
310 # parse stuff after comma: "condition"
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000311 cond = arg[comma+1:].lstrip()
312 arg = arg[:comma].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000313 # parse stuff before comma: [filename:]lineno | function
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000314 colon = arg.rfind(':')
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000315 funcname = None
Tim Peters2344fae2001-01-15 00:50:52 +0000316 if colon >= 0:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000317 filename = arg[:colon].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000318 f = self.lookupmodule(filename)
319 if not f:
Georg Brandl19564802006-05-10 17:13:20 +0000320 print >>self.stdout, '*** ', repr(filename),
321 print >>self.stdout, 'not found from sys.path'
Tim Peters2344fae2001-01-15 00:50:52 +0000322 return
323 else:
324 filename = f
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000325 arg = arg[colon+1:].lstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000326 try:
327 lineno = int(arg)
328 except ValueError, msg:
Georg Brandl19564802006-05-10 17:13:20 +0000329 print >>self.stdout, '*** Bad lineno:', arg
Tim Peters2344fae2001-01-15 00:50:52 +0000330 return
331 else:
332 # no colon; can be lineno or function
333 try:
334 lineno = int(arg)
335 except ValueError:
336 try:
337 func = eval(arg,
338 self.curframe.f_globals,
339 self.curframe.f_locals)
340 except:
341 func = arg
342 try:
343 if hasattr(func, 'im_func'):
344 func = func.im_func
345 code = func.func_code
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000346 #use co_name to identify the bkpt (function names
347 #could be aliased, but co_name is invariant)
348 funcname = code.co_name
Tim Peters2344fae2001-01-15 00:50:52 +0000349 lineno = code.co_firstlineno
350 filename = code.co_filename
351 except:
352 # last thing to try
353 (ok, filename, ln) = self.lineinfo(arg)
354 if not ok:
Georg Brandl19564802006-05-10 17:13:20 +0000355 print >>self.stdout, '*** The specified object',
356 print >>self.stdout, repr(arg),
357 print >>self.stdout, 'is not a function'
358 print >>self.stdout, 'or was not found along sys.path.'
Tim Peters2344fae2001-01-15 00:50:52 +0000359 return
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000360 funcname = ok # ok contains a function name
Tim Peters2344fae2001-01-15 00:50:52 +0000361 lineno = int(ln)
362 if not filename:
363 filename = self.defaultFile()
364 # Check for reasonable breakpoint
365 line = self.checkline(filename, lineno)
366 if line:
367 # now set the break point
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000368 err = self.set_break(filename, line, temporary, cond, funcname)
Georg Brandl19564802006-05-10 17:13:20 +0000369 if err: print >>self.stdout, '***', err
Tim Peters2344fae2001-01-15 00:50:52 +0000370 else:
371 bp = self.get_breaks(filename, line)[-1]
Georg Brandl19564802006-05-10 17:13:20 +0000372 print >>self.stdout, "Breakpoint %d at %s:%d" % (bp.number,
373 bp.file,
374 bp.line)
Tim Peters2344fae2001-01-15 00:50:52 +0000375
376 # To be overridden in derived debuggers
377 def defaultFile(self):
378 """Produce a reasonable default."""
379 filename = self.curframe.f_code.co_filename
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000380 if filename == '<string>' and self.mainpyfile:
381 filename = self.mainpyfile
Tim Peters2344fae2001-01-15 00:50:52 +0000382 return filename
383
384 do_b = do_break
385
386 def do_tbreak(self, arg):
387 self.do_break(arg, 1)
388
389 def lineinfo(self, identifier):
390 failed = (None, None, None)
391 # Input is identifier, may be in single quotes
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000392 idstring = identifier.split("'")
Tim Peters2344fae2001-01-15 00:50:52 +0000393 if len(idstring) == 1:
394 # not in single quotes
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000395 id = idstring[0].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000396 elif len(idstring) == 3:
397 # quoted
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000398 id = idstring[1].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000399 else:
400 return failed
401 if id == '': return failed
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000402 parts = id.split('.')
Tim Peters2344fae2001-01-15 00:50:52 +0000403 # Protection for derived debuggers
404 if parts[0] == 'self':
405 del parts[0]
406 if len(parts) == 0:
407 return failed
408 # Best first guess at file to look at
409 fname = self.defaultFile()
410 if len(parts) == 1:
411 item = parts[0]
412 else:
413 # More than one part.
414 # First is module, second is method/class
415 f = self.lookupmodule(parts[0])
416 if f:
417 fname = f
418 item = parts[1]
419 answer = find_function(item, fname)
420 return answer or failed
421
422 def checkline(self, filename, lineno):
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000423 """Check whether specified line seems to be executable.
Tim Peters2344fae2001-01-15 00:50:52 +0000424
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000425 Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
426 line or EOF). Warning: testing is not comprehensive.
427 """
Tim Peters2344fae2001-01-15 00:50:52 +0000428 line = linecache.getline(filename, lineno)
429 if not line:
Georg Brandl19564802006-05-10 17:13:20 +0000430 print >>self.stdout, 'End of file'
Tim Peters2344fae2001-01-15 00:50:52 +0000431 return 0
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000432 line = line.strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000433 # Don't allow setting breakpoint at a blank line
Guido van Rossum08454592002-07-12 13:10:53 +0000434 if (not line or (line[0] == '#') or
435 (line[:3] == '"""') or line[:3] == "'''"):
Georg Brandl19564802006-05-10 17:13:20 +0000436 print >>self.stdout, '*** Blank or comment'
Tim Peters2344fae2001-01-15 00:50:52 +0000437 return 0
Tim Peters2344fae2001-01-15 00:50:52 +0000438 return lineno
439
440 def do_enable(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000441 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000442 for i in args:
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000443 try:
444 i = int(i)
445 except ValueError:
Georg Brandl19564802006-05-10 17:13:20 +0000446 print >>self.stdout, 'Breakpoint index %r is not a number' % i
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000447 continue
448
449 if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
Georg Brandl19564802006-05-10 17:13:20 +0000450 print >>self.stdout, 'No breakpoint numbered', i
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000451 continue
452
453 bp = bdb.Breakpoint.bpbynumber[i]
Tim Peters2344fae2001-01-15 00:50:52 +0000454 if bp:
455 bp.enable()
456
457 def do_disable(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000458 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000459 for i in args:
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000460 try:
461 i = int(i)
462 except ValueError:
Georg Brandl19564802006-05-10 17:13:20 +0000463 print >>self.stdout, 'Breakpoint index %r is not a number' % i
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000464 continue
Tim Petersf545baa2003-06-15 23:26:30 +0000465
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000466 if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
Georg Brandl19564802006-05-10 17:13:20 +0000467 print >>self.stdout, 'No breakpoint numbered', i
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000468 continue
469
470 bp = bdb.Breakpoint.bpbynumber[i]
Tim Peters2344fae2001-01-15 00:50:52 +0000471 if bp:
472 bp.disable()
473
474 def do_condition(self, arg):
475 # arg is breakpoint number and condition
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000476 args = arg.split(' ', 1)
Georg Brandl1e4bb442007-01-22 21:23:45 +0000477 try:
478 bpnum = int(args[0].strip())
479 except ValueError:
480 # something went wrong
481 print >>self.stdout, \
482 'Breakpoint index %r is not a number' % args[0]
Georg Brandld28d9c82007-03-11 08:28:50 +0000483 return
Tim Peters2344fae2001-01-15 00:50:52 +0000484 try:
485 cond = args[1]
486 except:
487 cond = None
Collin Winter3e43bcc2007-03-11 16:04:01 +0000488 try:
489 bp = bdb.Breakpoint.bpbynumber[bpnum]
490 except IndexError:
491 print >>self.stdout, 'Breakpoint index %r is not valid' % args[0]
492 return
Tim Peters2344fae2001-01-15 00:50:52 +0000493 if bp:
494 bp.cond = cond
495 if not cond:
Georg Brandl19564802006-05-10 17:13:20 +0000496 print >>self.stdout, 'Breakpoint', bpnum,
497 print >>self.stdout, 'is now unconditional.'
Tim Peters2344fae2001-01-15 00:50:52 +0000498
499 def do_ignore(self,arg):
500 """arg is bp number followed by ignore count."""
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000501 args = arg.split()
Georg Brandl1e4bb442007-01-22 21:23:45 +0000502 try:
503 bpnum = int(args[0].strip())
504 except ValueError:
505 # something went wrong
506 print >>self.stdout, \
507 'Breakpoint index %r is not a number' % args[0]
Georg Brandld28d9c82007-03-11 08:28:50 +0000508 return
Tim Peters2344fae2001-01-15 00:50:52 +0000509 try:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000510 count = int(args[1].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000511 except:
512 count = 0
Collin Winter3e43bcc2007-03-11 16:04:01 +0000513 try:
514 bp = bdb.Breakpoint.bpbynumber[bpnum]
515 except IndexError:
516 print >>self.stdout, 'Breakpoint index %r is not valid' % args[0]
517 return
Tim Peters2344fae2001-01-15 00:50:52 +0000518 if bp:
519 bp.ignore = count
Guido van Rossum08454592002-07-12 13:10:53 +0000520 if count > 0:
Tim Peters2344fae2001-01-15 00:50:52 +0000521 reply = 'Will ignore next '
Guido van Rossum08454592002-07-12 13:10:53 +0000522 if count > 1:
Tim Peters2344fae2001-01-15 00:50:52 +0000523 reply = reply + '%d crossings' % count
524 else:
525 reply = reply + '1 crossing'
Georg Brandl19564802006-05-10 17:13:20 +0000526 print >>self.stdout, reply + ' of breakpoint %d.' % bpnum
Tim Peters2344fae2001-01-15 00:50:52 +0000527 else:
Georg Brandl19564802006-05-10 17:13:20 +0000528 print >>self.stdout, 'Will stop next time breakpoint',
529 print >>self.stdout, bpnum, 'is reached.'
Tim Peters2344fae2001-01-15 00:50:52 +0000530
531 def do_clear(self, arg):
532 """Three possibilities, tried in this order:
533 clear -> clear all breaks, ask for confirmation
534 clear file:lineno -> clear all breaks at file:lineno
535 clear bpno bpno ... -> clear breakpoints by number"""
536 if not arg:
537 try:
538 reply = raw_input('Clear all breaks? ')
539 except EOFError:
540 reply = 'no'
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000541 reply = reply.strip().lower()
Tim Peters2344fae2001-01-15 00:50:52 +0000542 if reply in ('y', 'yes'):
543 self.clear_all_breaks()
544 return
545 if ':' in arg:
546 # Make sure it works for "clear C:\foo\bar.py:12"
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000547 i = arg.rfind(':')
Tim Peters2344fae2001-01-15 00:50:52 +0000548 filename = arg[:i]
549 arg = arg[i+1:]
550 try:
551 lineno = int(arg)
Georg Brandl23d9d452006-05-03 18:12:33 +0000552 except ValueError:
Tim Peters2344fae2001-01-15 00:50:52 +0000553 err = "Invalid line number (%s)" % arg
554 else:
555 err = self.clear_break(filename, lineno)
Georg Brandl19564802006-05-10 17:13:20 +0000556 if err: print >>self.stdout, '***', err
Tim Peters2344fae2001-01-15 00:50:52 +0000557 return
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000558 numberlist = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000559 for i in numberlist:
Georg Brandl23d9d452006-05-03 18:12:33 +0000560 try:
561 i = int(i)
562 except ValueError:
Georg Brandl19564802006-05-10 17:13:20 +0000563 print >>self.stdout, 'Breakpoint index %r is not a number' % i
Georg Brandl23d9d452006-05-03 18:12:33 +0000564 continue
565
Georg Brandl6d2b3462005-08-24 07:36:17 +0000566 if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
Georg Brandl19564802006-05-10 17:13:20 +0000567 print >>self.stdout, 'No breakpoint numbered', i
Georg Brandl6d2b3462005-08-24 07:36:17 +0000568 continue
Tim Peters2344fae2001-01-15 00:50:52 +0000569 err = self.clear_bpbynumber(i)
570 if err:
Georg Brandl19564802006-05-10 17:13:20 +0000571 print >>self.stdout, '***', err
Tim Peters2344fae2001-01-15 00:50:52 +0000572 else:
Georg Brandl19564802006-05-10 17:13:20 +0000573 print >>self.stdout, 'Deleted breakpoint', i
Tim Peters2344fae2001-01-15 00:50:52 +0000574 do_cl = do_clear # 'c' is already an abbreviation for 'continue'
575
576 def do_where(self, arg):
577 self.print_stack_trace()
578 do_w = do_where
Guido van Rossum6bd68352001-01-20 17:57:37 +0000579 do_bt = do_where
Tim Peters2344fae2001-01-15 00:50:52 +0000580
581 def do_up(self, arg):
582 if self.curindex == 0:
Georg Brandl19564802006-05-10 17:13:20 +0000583 print >>self.stdout, '*** Oldest frame'
Tim Peters2344fae2001-01-15 00:50:52 +0000584 else:
585 self.curindex = self.curindex - 1
586 self.curframe = self.stack[self.curindex][0]
587 self.print_stack_entry(self.stack[self.curindex])
588 self.lineno = None
589 do_u = do_up
590
591 def do_down(self, arg):
592 if self.curindex + 1 == len(self.stack):
Georg Brandl19564802006-05-10 17:13:20 +0000593 print >>self.stdout, '*** Newest frame'
Tim Peters2344fae2001-01-15 00:50:52 +0000594 else:
595 self.curindex = self.curindex + 1
596 self.curframe = self.stack[self.curindex][0]
597 self.print_stack_entry(self.stack[self.curindex])
598 self.lineno = None
599 do_d = do_down
600
601 def do_step(self, arg):
602 self.set_step()
603 return 1
604 do_s = do_step
605
606 def do_next(self, arg):
607 self.set_next(self.curframe)
608 return 1
609 do_n = do_next
610
611 def do_return(self, arg):
612 self.set_return(self.curframe)
613 return 1
614 do_r = do_return
615
616 def do_continue(self, arg):
617 self.set_continue()
618 return 1
619 do_c = do_cont = do_continue
620
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000621 def do_jump(self, arg):
622 if self.curindex + 1 != len(self.stack):
Georg Brandl19564802006-05-10 17:13:20 +0000623 print >>self.stdout, "*** You can only jump within the bottom frame"
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000624 return
625 try:
626 arg = int(arg)
627 except ValueError:
Georg Brandl19564802006-05-10 17:13:20 +0000628 print >>self.stdout, "*** The 'jump' command requires a line number."
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000629 else:
630 try:
631 # Do the jump, fix up our copy of the stack, and display the
632 # new position
633 self.curframe.f_lineno = arg
634 self.stack[self.curindex] = self.stack[self.curindex][0], arg
635 self.print_stack_entry(self.stack[self.curindex])
636 except ValueError, e:
Georg Brandl19564802006-05-10 17:13:20 +0000637 print >>self.stdout, '*** Jump failed:', e
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000638 do_j = do_jump
639
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000640 def do_debug(self, arg):
641 sys.settrace(None)
642 globals = self.curframe.f_globals
643 locals = self.curframe.f_locals
Guido van Rossume41f1552008-02-13 18:41:48 +0000644 p = Pdb(self.completekey, self.stdin, self.stdout)
Guido van Rossumed538d82003-04-09 19:36:34 +0000645 p.prompt = "(%s) " % self.prompt.strip()
Georg Brandl19564802006-05-10 17:13:20 +0000646 print >>self.stdout, "ENTERING RECURSIVE DEBUGGER"
Guido van Rossumed538d82003-04-09 19:36:34 +0000647 sys.call_tracing(p.run, (arg, globals, locals))
Georg Brandl19564802006-05-10 17:13:20 +0000648 print >>self.stdout, "LEAVING RECURSIVE DEBUGGER"
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000649 sys.settrace(self.trace_dispatch)
650 self.lastcmd = p.lastcmd
651
Tim Peters2344fae2001-01-15 00:50:52 +0000652 def do_quit(self, arg):
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000653 self._user_requested_quit = 1
Tim Peters2344fae2001-01-15 00:50:52 +0000654 self.set_quit()
655 return 1
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000656
Tim Peters2344fae2001-01-15 00:50:52 +0000657 do_q = do_quit
Guido van Rossumd1c08f32002-04-15 00:48:24 +0000658 do_exit = do_quit
Tim Peters2344fae2001-01-15 00:50:52 +0000659
Guido van Rossumeef26072003-01-13 21:13:55 +0000660 def do_EOF(self, arg):
Georg Brandl19564802006-05-10 17:13:20 +0000661 print >>self.stdout
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000662 self._user_requested_quit = 1
Guido van Rossumeef26072003-01-13 21:13:55 +0000663 self.set_quit()
664 return 1
665
Tim Peters2344fae2001-01-15 00:50:52 +0000666 def do_args(self, arg):
667 f = self.curframe
668 co = f.f_code
669 dict = f.f_locals
670 n = co.co_argcount
671 if co.co_flags & 4: n = n+1
672 if co.co_flags & 8: n = n+1
673 for i in range(n):
674 name = co.co_varnames[i]
Georg Brandl19564802006-05-10 17:13:20 +0000675 print >>self.stdout, name, '=',
676 if name in dict: print >>self.stdout, dict[name]
677 else: print >>self.stdout, "*** undefined ***"
Tim Peters2344fae2001-01-15 00:50:52 +0000678 do_a = do_args
Guido van Rossum2424f851998-09-11 22:50:09 +0000679
Tim Peters2344fae2001-01-15 00:50:52 +0000680 def do_retval(self, arg):
Raymond Hettinger54f02222002-06-01 14:18:47 +0000681 if '__return__' in self.curframe.f_locals:
Georg Brandl19564802006-05-10 17:13:20 +0000682 print >>self.stdout, self.curframe.f_locals['__return__']
Tim Peters2344fae2001-01-15 00:50:52 +0000683 else:
Georg Brandl19564802006-05-10 17:13:20 +0000684 print >>self.stdout, '*** Not yet returned!'
Tim Peters2344fae2001-01-15 00:50:52 +0000685 do_rv = do_retval
Guido van Rossum2424f851998-09-11 22:50:09 +0000686
Barry Warsaw210bd202002-11-05 22:40:20 +0000687 def _getval(self, arg):
Tim Peters2344fae2001-01-15 00:50:52 +0000688 try:
Barry Warsaw210bd202002-11-05 22:40:20 +0000689 return eval(arg, self.curframe.f_globals,
690 self.curframe.f_locals)
Tim Peters2344fae2001-01-15 00:50:52 +0000691 except:
692 t, v = sys.exc_info()[:2]
Barry Warsaw210bd202002-11-05 22:40:20 +0000693 if isinstance(t, str):
Tim Peters2344fae2001-01-15 00:50:52 +0000694 exc_type_name = t
695 else: exc_type_name = t.__name__
Georg Brandl19564802006-05-10 17:13:20 +0000696 print >>self.stdout, '***', exc_type_name + ':', repr(v)
Barry Warsaw210bd202002-11-05 22:40:20 +0000697 raise
Guido van Rossum2424f851998-09-11 22:50:09 +0000698
Barry Warsaw210bd202002-11-05 22:40:20 +0000699 def do_p(self, arg):
700 try:
Georg Brandl19564802006-05-10 17:13:20 +0000701 print >>self.stdout, repr(self._getval(arg))
Barry Warsaw210bd202002-11-05 22:40:20 +0000702 except:
703 pass
704
705 def do_pp(self, arg):
706 try:
Georg Brandl19564802006-05-10 17:13:20 +0000707 pprint.pprint(self._getval(arg), self.stdout)
Barry Warsaw210bd202002-11-05 22:40:20 +0000708 except:
709 pass
Guido van Rossum2424f851998-09-11 22:50:09 +0000710
Tim Peters2344fae2001-01-15 00:50:52 +0000711 def do_list(self, arg):
712 self.lastcmd = 'list'
713 last = None
714 if arg:
715 try:
716 x = eval(arg, {}, {})
717 if type(x) == type(()):
718 first, last = x
719 first = int(first)
720 last = int(last)
721 if last < first:
722 # Assume it's a count
723 last = first + last
724 else:
725 first = max(1, int(x) - 5)
726 except:
Georg Brandl19564802006-05-10 17:13:20 +0000727 print >>self.stdout, '*** Error in argument:', repr(arg)
Tim Peters2344fae2001-01-15 00:50:52 +0000728 return
729 elif self.lineno is None:
730 first = max(1, self.curframe.f_lineno - 5)
731 else:
732 first = self.lineno + 1
733 if last is None:
734 last = first + 10
735 filename = self.curframe.f_code.co_filename
736 breaklist = self.get_file_breaks(filename)
737 try:
738 for lineno in range(first, last+1):
739 line = linecache.getline(filename, lineno)
740 if not line:
Georg Brandl19564802006-05-10 17:13:20 +0000741 print >>self.stdout, '[EOF]'
Tim Peters2344fae2001-01-15 00:50:52 +0000742 break
743 else:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000744 s = repr(lineno).rjust(3)
Tim Peters2344fae2001-01-15 00:50:52 +0000745 if len(s) < 4: s = s + ' '
746 if lineno in breaklist: s = s + 'B'
747 else: s = s + ' '
748 if lineno == self.curframe.f_lineno:
749 s = s + '->'
Georg Brandl19564802006-05-10 17:13:20 +0000750 print >>self.stdout, s + '\t' + line,
Tim Peters2344fae2001-01-15 00:50:52 +0000751 self.lineno = lineno
752 except KeyboardInterrupt:
753 pass
754 do_l = do_list
Guido van Rossum2424f851998-09-11 22:50:09 +0000755
Tim Peters2344fae2001-01-15 00:50:52 +0000756 def do_whatis(self, arg):
757 try:
758 value = eval(arg, self.curframe.f_globals,
759 self.curframe.f_locals)
760 except:
761 t, v = sys.exc_info()[:2]
762 if type(t) == type(''):
763 exc_type_name = t
764 else: exc_type_name = t.__name__
Georg Brandl19564802006-05-10 17:13:20 +0000765 print >>self.stdout, '***', exc_type_name + ':', repr(v)
Tim Peters2344fae2001-01-15 00:50:52 +0000766 return
767 code = None
768 # Is it a function?
769 try: code = value.func_code
770 except: pass
771 if code:
Georg Brandl19564802006-05-10 17:13:20 +0000772 print >>self.stdout, 'Function', code.co_name
Tim Peters2344fae2001-01-15 00:50:52 +0000773 return
774 # Is it an instance method?
775 try: code = value.im_func.func_code
776 except: pass
777 if code:
Georg Brandl19564802006-05-10 17:13:20 +0000778 print >>self.stdout, 'Method', code.co_name
Tim Peters2344fae2001-01-15 00:50:52 +0000779 return
780 # None of the above...
Georg Brandl19564802006-05-10 17:13:20 +0000781 print >>self.stdout, type(value)
Guido van Rossum8e2ec561993-07-29 09:37:38 +0000782
Tim Peters2344fae2001-01-15 00:50:52 +0000783 def do_alias(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000784 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000785 if len(args) == 0:
786 keys = self.aliases.keys()
787 keys.sort()
788 for alias in keys:
Georg Brandl19564802006-05-10 17:13:20 +0000789 print >>self.stdout, "%s = %s" % (alias, self.aliases[alias])
Tim Peters2344fae2001-01-15 00:50:52 +0000790 return
Guido van Rossum08454592002-07-12 13:10:53 +0000791 if args[0] in self.aliases and len(args) == 1:
Georg Brandl19564802006-05-10 17:13:20 +0000792 print >>self.stdout, "%s = %s" % (args[0], self.aliases[args[0]])
Tim Peters2344fae2001-01-15 00:50:52 +0000793 else:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000794 self.aliases[args[0]] = ' '.join(args[1:])
Guido van Rossum23efba41992-01-27 16:58:47 +0000795
Tim Peters2344fae2001-01-15 00:50:52 +0000796 def do_unalias(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000797 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000798 if len(args) == 0: return
Raymond Hettinger54f02222002-06-01 14:18:47 +0000799 if args[0] in self.aliases:
Tim Peters2344fae2001-01-15 00:50:52 +0000800 del self.aliases[args[0]]
Guido van Rossum00230781993-03-29 11:39:45 +0000801
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000802 #list of all the commands making the program resume execution.
Georg Brandl19564802006-05-10 17:13:20 +0000803 commands_resuming = ['do_continue', 'do_step', 'do_next', 'do_return',
804 'do_quit', 'do_jump']
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000805
Tim Peters2344fae2001-01-15 00:50:52 +0000806 # Print a traceback starting at the top stack frame.
807 # The most recently entered frame is printed last;
808 # this is different from dbx and gdb, but consistent with
809 # the Python interpreter's stack trace.
810 # It is also consistent with the up/down commands (which are
811 # compatible with dbx and gdb: up moves towards 'main()'
812 # and down moves towards the most recent stack frame).
Guido van Rossum2424f851998-09-11 22:50:09 +0000813
Tim Peters2344fae2001-01-15 00:50:52 +0000814 def print_stack_trace(self):
815 try:
816 for frame_lineno in self.stack:
817 self.print_stack_entry(frame_lineno)
818 except KeyboardInterrupt:
819 pass
Guido van Rossum2424f851998-09-11 22:50:09 +0000820
Tim Peters2344fae2001-01-15 00:50:52 +0000821 def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix):
822 frame, lineno = frame_lineno
823 if frame is self.curframe:
Georg Brandl19564802006-05-10 17:13:20 +0000824 print >>self.stdout, '>',
Tim Peters2344fae2001-01-15 00:50:52 +0000825 else:
Georg Brandl19564802006-05-10 17:13:20 +0000826 print >>self.stdout, ' ',
827 print >>self.stdout, self.format_stack_entry(frame_lineno,
828 prompt_prefix)
Guido van Rossum2424f851998-09-11 22:50:09 +0000829
Guido van Rossum921c8241992-01-10 14:54:42 +0000830
Tim Peters2344fae2001-01-15 00:50:52 +0000831 # Help methods (derived from pdb.doc)
Guido van Rossum921c8241992-01-10 14:54:42 +0000832
Tim Peters2344fae2001-01-15 00:50:52 +0000833 def help_help(self):
834 self.help_h()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000835
Tim Peters2344fae2001-01-15 00:50:52 +0000836 def help_h(self):
Georg Brandl19564802006-05-10 17:13:20 +0000837 print >>self.stdout, """h(elp)
Tim Peters2344fae2001-01-15 00:50:52 +0000838Without argument, print the list of available commands.
839With a command name as argument, print help about that command
840"help pdb" pipes the full documentation file to the $PAGER
841"help exec" gives help on the ! command"""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000842
Tim Peters2344fae2001-01-15 00:50:52 +0000843 def help_where(self):
844 self.help_w()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000845
Tim Peters2344fae2001-01-15 00:50:52 +0000846 def help_w(self):
Georg Brandl19564802006-05-10 17:13:20 +0000847 print >>self.stdout, """w(here)
Tim Peters2344fae2001-01-15 00:50:52 +0000848Print a stack trace, with the most recent frame at the bottom.
849An arrow indicates the "current frame", which determines the
Guido van Rossum6bd68352001-01-20 17:57:37 +0000850context of most commands. 'bt' is an alias for this command."""
851
852 help_bt = help_w
Guido van Rossumb6775db1994-08-01 11:34:53 +0000853
Tim Peters2344fae2001-01-15 00:50:52 +0000854 def help_down(self):
855 self.help_d()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000856
Tim Peters2344fae2001-01-15 00:50:52 +0000857 def help_d(self):
Georg Brandl19564802006-05-10 17:13:20 +0000858 print >>self.stdout, """d(own)
Tim Peters2344fae2001-01-15 00:50:52 +0000859Move the current frame one level down in the stack trace
Johannes Gijsbers34c41202004-08-14 15:19:28 +0000860(to a newer frame)."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000861
Tim Peters2344fae2001-01-15 00:50:52 +0000862 def help_up(self):
863 self.help_u()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000864
Tim Peters2344fae2001-01-15 00:50:52 +0000865 def help_u(self):
Georg Brandl19564802006-05-10 17:13:20 +0000866 print >>self.stdout, """u(p)
Tim Peters2344fae2001-01-15 00:50:52 +0000867Move the current frame one level up in the stack trace
Johannes Gijsbers34c41202004-08-14 15:19:28 +0000868(to an older frame)."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000869
Tim Peters2344fae2001-01-15 00:50:52 +0000870 def help_break(self):
871 self.help_b()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000872
Tim Peters2344fae2001-01-15 00:50:52 +0000873 def help_b(self):
Georg Brandl19564802006-05-10 17:13:20 +0000874 print >>self.stdout, """b(reak) ([file:]lineno | function) [, condition]
Tim Peters2344fae2001-01-15 00:50:52 +0000875With a line number argument, set a break there in the current
876file. With a function name, set a break at first executable line
877of that function. Without argument, list all breaks. If a second
878argument is present, it is a string specifying an expression
879which must evaluate to true before the breakpoint is honored.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000880
Tim Peters2344fae2001-01-15 00:50:52 +0000881The line number may be prefixed with a filename and a colon,
882to specify a breakpoint in another file (probably one that
883hasn't been loaded yet). The file is searched for on sys.path;
884the .py suffix may be omitted."""
Guido van Rossumb5699c71998-07-20 23:13:54 +0000885
Tim Peters2344fae2001-01-15 00:50:52 +0000886 def help_clear(self):
887 self.help_cl()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000888
Tim Peters2344fae2001-01-15 00:50:52 +0000889 def help_cl(self):
Georg Brandl19564802006-05-10 17:13:20 +0000890 print >>self.stdout, "cl(ear) filename:lineno"
891 print >>self.stdout, """cl(ear) [bpnumber [bpnumber...]]
Tim Peters2344fae2001-01-15 00:50:52 +0000892With a space separated list of breakpoint numbers, clear
893those breakpoints. Without argument, clear all breaks (but
894first ask confirmation). With a filename:lineno argument,
895clear all breaks at that line in that file.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000896
Tim Peters2344fae2001-01-15 00:50:52 +0000897Note that the argument is different from previous versions of
898the debugger (in python distributions 1.5.1 and before) where
899a linenumber was used instead of either filename:lineno or
900breakpoint numbers."""
Guido van Rossumb5699c71998-07-20 23:13:54 +0000901
Tim Peters2344fae2001-01-15 00:50:52 +0000902 def help_tbreak(self):
Georg Brandl19564802006-05-10 17:13:20 +0000903 print >>self.stdout, """tbreak same arguments as break, but breakpoint is
Tim Peters2344fae2001-01-15 00:50:52 +0000904removed when first hit."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000905
Tim Peters2344fae2001-01-15 00:50:52 +0000906 def help_enable(self):
Georg Brandl19564802006-05-10 17:13:20 +0000907 print >>self.stdout, """enable bpnumber [bpnumber ...]
Tim Peters2344fae2001-01-15 00:50:52 +0000908Enables the breakpoints given as a space separated list of
909bp numbers."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000910
Tim Peters2344fae2001-01-15 00:50:52 +0000911 def help_disable(self):
Georg Brandl19564802006-05-10 17:13:20 +0000912 print >>self.stdout, """disable bpnumber [bpnumber ...]
Tim Peters2344fae2001-01-15 00:50:52 +0000913Disables the breakpoints given as a space separated list of
914bp numbers."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000915
Tim Peters2344fae2001-01-15 00:50:52 +0000916 def help_ignore(self):
Georg Brandl19564802006-05-10 17:13:20 +0000917 print >>self.stdout, """ignore bpnumber count
Tim Peters2344fae2001-01-15 00:50:52 +0000918Sets the ignore count for the given breakpoint number. A breakpoint
919becomes active when the ignore count is zero. When non-zero, the
920count is decremented each time the breakpoint is reached and the
921breakpoint is not disabled and any associated condition evaluates
922to true."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000923
Tim Peters2344fae2001-01-15 00:50:52 +0000924 def help_condition(self):
Georg Brandl19564802006-05-10 17:13:20 +0000925 print >>self.stdout, """condition bpnumber str_condition
Tim Peters2344fae2001-01-15 00:50:52 +0000926str_condition is a string specifying an expression which
927must evaluate to true before the breakpoint is honored.
928If str_condition is absent, any existing condition is removed;
929i.e., the breakpoint is made unconditional."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000930
Tim Peters2344fae2001-01-15 00:50:52 +0000931 def help_step(self):
932 self.help_s()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000933
Tim Peters2344fae2001-01-15 00:50:52 +0000934 def help_s(self):
Georg Brandl19564802006-05-10 17:13:20 +0000935 print >>self.stdout, """s(tep)
Tim Peters2344fae2001-01-15 00:50:52 +0000936Execute the current line, stop at the first possible occasion
937(either in a function that is called or in the current function)."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000938
Tim Peters2344fae2001-01-15 00:50:52 +0000939 def help_next(self):
940 self.help_n()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000941
Tim Peters2344fae2001-01-15 00:50:52 +0000942 def help_n(self):
Georg Brandl19564802006-05-10 17:13:20 +0000943 print >>self.stdout, """n(ext)
Tim Peters2344fae2001-01-15 00:50:52 +0000944Continue execution until the next line in the current function
945is reached or it returns."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000946
Tim Peters2344fae2001-01-15 00:50:52 +0000947 def help_return(self):
948 self.help_r()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000949
Tim Peters2344fae2001-01-15 00:50:52 +0000950 def help_r(self):
Georg Brandl19564802006-05-10 17:13:20 +0000951 print >>self.stdout, """r(eturn)
Tim Peters2344fae2001-01-15 00:50:52 +0000952Continue execution until the current function returns."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000953
Tim Peters2344fae2001-01-15 00:50:52 +0000954 def help_continue(self):
955 self.help_c()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000956
Tim Peters2344fae2001-01-15 00:50:52 +0000957 def help_cont(self):
958 self.help_c()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000959
Tim Peters2344fae2001-01-15 00:50:52 +0000960 def help_c(self):
Georg Brandl19564802006-05-10 17:13:20 +0000961 print >>self.stdout, """c(ont(inue))
Tim Peters2344fae2001-01-15 00:50:52 +0000962Continue execution, only stop when a breakpoint is encountered."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000963
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000964 def help_jump(self):
965 self.help_j()
966
967 def help_j(self):
Georg Brandl19564802006-05-10 17:13:20 +0000968 print >>self.stdout, """j(ump) lineno
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000969Set the next line that will be executed."""
970
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000971 def help_debug(self):
Georg Brandl19564802006-05-10 17:13:20 +0000972 print >>self.stdout, """debug code
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000973Enter a recursive debugger that steps through the code argument
974(which is an arbitrary expression or statement to be executed
975in the current environment)."""
976
Tim Peters2344fae2001-01-15 00:50:52 +0000977 def help_list(self):
978 self.help_l()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000979
Tim Peters2344fae2001-01-15 00:50:52 +0000980 def help_l(self):
Georg Brandl19564802006-05-10 17:13:20 +0000981 print >>self.stdout, """l(ist) [first [,last]]
Tim Peters2344fae2001-01-15 00:50:52 +0000982List source code for the current file.
983Without arguments, list 11 lines around the current line
984or continue the previous listing.
985With one argument, list 11 lines starting at that line.
986With two arguments, list the given range;
987if the second argument is less than the first, it is a count."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000988
Tim Peters2344fae2001-01-15 00:50:52 +0000989 def help_args(self):
990 self.help_a()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000991
Tim Peters2344fae2001-01-15 00:50:52 +0000992 def help_a(self):
Georg Brandl19564802006-05-10 17:13:20 +0000993 print >>self.stdout, """a(rgs)
Tim Peters2344fae2001-01-15 00:50:52 +0000994Print the arguments of the current function."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000995
Tim Peters2344fae2001-01-15 00:50:52 +0000996 def help_p(self):
Georg Brandl19564802006-05-10 17:13:20 +0000997 print >>self.stdout, """p expression
Tim Peters2344fae2001-01-15 00:50:52 +0000998Print the value of the expression."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000999
Barry Warsaw210bd202002-11-05 22:40:20 +00001000 def help_pp(self):
Georg Brandl19564802006-05-10 17:13:20 +00001001 print >>self.stdout, """pp expression
Barry Warsaw210bd202002-11-05 22:40:20 +00001002Pretty-print the value of the expression."""
1003
Tim Peters2344fae2001-01-15 00:50:52 +00001004 def help_exec(self):
Georg Brandl19564802006-05-10 17:13:20 +00001005 print >>self.stdout, """(!) statement
Tim Peters2344fae2001-01-15 00:50:52 +00001006Execute the (one-line) statement in the context of
1007the current stack frame.
1008The exclamation point can be omitted unless the first word
1009of the statement resembles a debugger command.
1010To assign to a global variable you must always prefix the
1011command with a 'global' command, e.g.:
1012(Pdb) global list_options; list_options = ['-l']
1013(Pdb)"""
Guido van Rossumb6775db1994-08-01 11:34:53 +00001014
Tim Peters2344fae2001-01-15 00:50:52 +00001015 def help_quit(self):
1016 self.help_q()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001017
Tim Peters2344fae2001-01-15 00:50:52 +00001018 def help_q(self):
Georg Brandl19564802006-05-10 17:13:20 +00001019 print >>self.stdout, """q(uit) or exit - Quit from the debugger.
Tim Peters2344fae2001-01-15 00:50:52 +00001020The program being executed is aborted."""
Guido van Rossumb6775db1994-08-01 11:34:53 +00001021
Guido van Rossumd1c08f32002-04-15 00:48:24 +00001022 help_exit = help_q
1023
Tim Peters2344fae2001-01-15 00:50:52 +00001024 def help_whatis(self):
Georg Brandl19564802006-05-10 17:13:20 +00001025 print >>self.stdout, """whatis arg
Tim Peters2344fae2001-01-15 00:50:52 +00001026Prints the type of the argument."""
Guido van Rossumb6775db1994-08-01 11:34:53 +00001027
Tim Peters2344fae2001-01-15 00:50:52 +00001028 def help_EOF(self):
Georg Brandl19564802006-05-10 17:13:20 +00001029 print >>self.stdout, """EOF
Tim Peters2344fae2001-01-15 00:50:52 +00001030Handles the receipt of EOF as a command."""
Guido van Rossum2424f851998-09-11 22:50:09 +00001031
Tim Peters2344fae2001-01-15 00:50:52 +00001032 def help_alias(self):
Georg Brandl19564802006-05-10 17:13:20 +00001033 print >>self.stdout, """alias [name [command [parameter parameter ...] ]]
Tim Peters2344fae2001-01-15 00:50:52 +00001034Creates an alias called 'name' the executes 'command'. The command
1035must *not* be enclosed in quotes. Replaceable parameters are
1036indicated by %1, %2, and so on, while %* is replaced by all the
1037parameters. If no command is given, the current alias for name
1038is shown. If no name is given, all aliases are listed.
Guido van Rossum2424f851998-09-11 22:50:09 +00001039
Tim Peters2344fae2001-01-15 00:50:52 +00001040Aliases may be nested and can contain anything that can be
1041legally typed at the pdb prompt. Note! You *can* override
1042internal pdb commands with aliases! Those internal commands
1043are then hidden until the alias is removed. Aliasing is recursively
1044applied to the first word of the command line; all other words
1045in the line are left alone.
Guido van Rossum2424f851998-09-11 22:50:09 +00001046
Tim Peters2344fae2001-01-15 00:50:52 +00001047Some useful aliases (especially when placed in the .pdbrc file) are:
Guido van Rossum2424f851998-09-11 22:50:09 +00001048
Tim Peters2344fae2001-01-15 00:50:52 +00001049#Print instance variables (usage "pi classInst")
1050alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
Guido van Rossum2424f851998-09-11 22:50:09 +00001051
Tim Peters2344fae2001-01-15 00:50:52 +00001052#Print instance variables in self
1053alias ps pi self
1054"""
Guido van Rossum2424f851998-09-11 22:50:09 +00001055
Tim Peters2344fae2001-01-15 00:50:52 +00001056 def help_unalias(self):
Georg Brandl19564802006-05-10 17:13:20 +00001057 print >>self.stdout, """unalias name
Tim Peters2344fae2001-01-15 00:50:52 +00001058Deletes the specified alias."""
Guido van Rossum2424f851998-09-11 22:50:09 +00001059
Martin v. Löwisbd30f522006-04-17 17:08:37 +00001060 def help_commands(self):
Georg Brandl19564802006-05-10 17:13:20 +00001061 print >>self.stdout, """commands [bpnumber]
Martin v. Löwisbd30f522006-04-17 17:08:37 +00001062(com) ...
1063(com) end
1064(Pdb)
1065
1066Specify a list of commands for breakpoint number bpnumber. The
1067commands themselves appear on the following lines. Type a line
1068containing just 'end' to terminate the commands.
1069
1070To remove all commands from a breakpoint, type commands and
1071follow it immediately with end; that is, give no commands.
1072
1073With no bpnumber argument, commands refers to the last
1074breakpoint set.
1075
1076You can use breakpoint commands to start your program up again.
1077Simply use the continue command, or step, or any other
1078command that resumes execution.
1079
1080Specifying any command resuming execution (currently continue,
1081step, next, return, jump, quit and their abbreviations) terminates
1082the command list (as if that command was immediately followed by end).
1083This is because any time you resume execution
Martin v. Löwisf62eee12006-04-17 17:37:09 +00001084(even with a simple next or step), you may encounter
Martin v. Löwisbd30f522006-04-17 17:08:37 +00001085another breakpoint--which could have its own command list, leading to
1086ambiguities about which list to execute.
1087
1088 If you use the 'silent' command in the command list, the
1089usual message about stopping at a breakpoint is not printed. This may
1090be desirable for breakpoints that are to print a specific message and
1091then continue. If none of the other commands print anything, you
1092see no sign that the breakpoint was reached.
1093"""
1094
Tim Peters2344fae2001-01-15 00:50:52 +00001095 def help_pdb(self):
1096 help()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001097
Tim Peters2344fae2001-01-15 00:50:52 +00001098 def lookupmodule(self, filename):
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001099 """Helper function for break/clear parsing -- may be overridden.
1100
1101 lookupmodule() translates (possibly incomplete) file or module name
1102 into an absolute file name.
1103 """
1104 if os.path.isabs(filename) and os.path.exists(filename):
Tim Peterse718f612004-10-12 21:51:32 +00001105 return filename
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001106 f = os.path.join(sys.path[0], filename)
1107 if os.path.exists(f) and self.canonic(f) == self.mainpyfile:
1108 return f
Tim Peters2344fae2001-01-15 00:50:52 +00001109 root, ext = os.path.splitext(filename)
1110 if ext == '':
1111 filename = filename + '.py'
1112 if os.path.isabs(filename):
1113 return filename
1114 for dirname in sys.path:
1115 while os.path.islink(dirname):
1116 dirname = os.readlink(dirname)
1117 fullname = os.path.join(dirname, filename)
1118 if os.path.exists(fullname):
1119 return fullname
1120 return None
Guido van Rossumb5699c71998-07-20 23:13:54 +00001121
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001122 def _runscript(self, filename):
1123 # Start with fresh empty copy of globals and locals and tell the script
1124 # that it's being run as __main__ to avoid scripts being able to access
1125 # the pdb.py namespace.
Christian Heimes50bbcc22007-11-12 17:28:45 +00001126 globals_ = {"__name__" : "__main__", "__file__" : filename}
Tim Peterse718f612004-10-12 21:51:32 +00001127 locals_ = globals_
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001128
1129 # When bdb sets tracing, a number of call and line events happens
1130 # BEFORE debugger even reaches user's code (and the exact sequence of
1131 # events depends on python version). So we take special measures to
1132 # avoid stopping before we reach the main script (see user_line and
1133 # user_call for details).
1134 self._wait_for_mainpyfile = 1
1135 self.mainpyfile = self.canonic(filename)
1136 self._user_requested_quit = 0
1137 statement = 'execfile( "%s")' % filename
1138 self.run(statement, globals=globals_, locals=locals_)
1139
Guido van Rossum35771131992-09-08 11:59:04 +00001140# Simplified interface
1141
Guido van Rossum5e38b6f1995-02-27 13:13:40 +00001142def run(statement, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +00001143 Pdb().run(statement, globals, locals)
Guido van Rossum5e38b6f1995-02-27 13:13:40 +00001144
1145def runeval(expression, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +00001146 return Pdb().runeval(expression, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001147
1148def runctx(statement, globals, locals):
Tim Peters2344fae2001-01-15 00:50:52 +00001149 # B/W compatibility
1150 run(statement, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001151
Raymond Hettinger2ef7e6c2004-10-24 00:32:24 +00001152def runcall(*args, **kwds):
1153 return Pdb().runcall(*args, **kwds)
Guido van Rossum4e160981992-09-02 20:43:20 +00001154
Guido van Rossumb6775db1994-08-01 11:34:53 +00001155def set_trace():
Johannes Gijsbers84a6c202004-11-07 11:35:30 +00001156 Pdb().set_trace(sys._getframe().f_back)
Guido van Rossum35771131992-09-08 11:59:04 +00001157
1158# Post-Mortem interface
1159
1160def post_mortem(t):
Tim Peters2344fae2001-01-15 00:50:52 +00001161 p = Pdb()
1162 p.reset()
1163 while t.tb_next is not None:
1164 t = t.tb_next
1165 p.interaction(t.tb_frame, t)
Guido van Rossum35771131992-09-08 11:59:04 +00001166
1167def pm():
Tim Peters2344fae2001-01-15 00:50:52 +00001168 post_mortem(sys.last_traceback)
Guido van Rossum35771131992-09-08 11:59:04 +00001169
1170
1171# Main program for testing
1172
Guido van Rossum23efba41992-01-27 16:58:47 +00001173TESTCMD = 'import x; x.main()'
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001174
Guido van Rossum921c8241992-01-10 14:54:42 +00001175def test():
Tim Peters2344fae2001-01-15 00:50:52 +00001176 run(TESTCMD)
Guido van Rossume61fa0a1993-10-22 13:56:35 +00001177
1178# print help
1179def help():
Tim Peters2344fae2001-01-15 00:50:52 +00001180 for dirname in sys.path:
1181 fullname = os.path.join(dirname, 'pdb.doc')
1182 if os.path.exists(fullname):
1183 sts = os.system('${PAGER-more} '+fullname)
1184 if sts: print '*** Pager exit status:', sts
1185 break
1186 else:
1187 print 'Sorry, can\'t find the help file "pdb.doc"',
1188 print 'along the Python search path'
Guido van Rossumf17361d1996-07-30 16:28:13 +00001189
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001190def main():
Tim Peters2344fae2001-01-15 00:50:52 +00001191 if not sys.argv[1:]:
1192 print "usage: pdb.py scriptfile [arg] ..."
1193 sys.exit(2)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001194
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001195 mainpyfile = sys.argv[1] # Get script filename
1196 if not os.path.exists(mainpyfile):
1197 print 'Error:', mainpyfile, 'does not exist'
Tim Peters2344fae2001-01-15 00:50:52 +00001198 sys.exit(1)
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001199
Tim Peters2344fae2001-01-15 00:50:52 +00001200 del sys.argv[0] # Hide "pdb.py" from argument list
Guido van Rossumec577d51996-09-10 17:39:34 +00001201
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001202 # Replace pdb's dir with script's dir in front of module search path.
1203 sys.path[0] = os.path.dirname(mainpyfile)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001204
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001205 # Note on saving/restoring sys.argv: it's a good idea when sys.argv was
1206 # modified by the script being debugged. It's a bad idea when it was
1207 # changed by the user from the command line. The best approach would be to
1208 # have a "restart" command which would allow explicit specification of
1209 # command line arguments.
1210 pdb = Pdb()
1211 while 1:
1212 try:
1213 pdb._runscript(mainpyfile)
1214 if pdb._user_requested_quit:
1215 break
Tim Peterse718f612004-10-12 21:51:32 +00001216 print "The program finished and will be restarted"
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001217 except SystemExit:
1218 # In most cases SystemExit does not warrant a post-mortem session.
1219 print "The program exited via sys.exit(). Exit status: ",
1220 print sys.exc_info()[1]
1221 except:
1222 traceback.print_exc()
1223 print "Uncaught exception. Entering post mortem debugging"
1224 print "Running 'cont' or 'step' will restart the program"
1225 t = sys.exc_info()[2]
1226 while t.tb_next is not None:
1227 t = t.tb_next
1228 pdb.interaction(t.tb_frame,t)
1229 print "Post mortem debugger finished. The "+mainpyfile+" will be restarted"
1230
1231
1232# When invoked as main program, invoke the debugger on a script
1233if __name__=='__main__':
1234 main()