blob: 2e450989b722d8f71fa223920bb76f1953374f21 [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
7import string
8import sys
9import linecache
Guido van Rossum23efba41992-01-27 16:58:47 +000010import cmd
11import bdb
12import repr
Guido van Rossumb5699c71998-07-20 23:13:54 +000013import os
Barry Warsaw2bee8fe1999-09-09 16:32:41 +000014import re
15
16def find_function(funcname, filename):
17 cre = re.compile(r'def\s+%s\s*[(]' % funcname)
18 try:
19 fp = open(filename)
20 except IOError:
21 return None
22 # consumer of this info expects the first line to be 1
23 lineno = 1
24 answer = None
25 while 1:
26 line = fp.readline()
27 if line == '':
28 break
29 if cre.match(line):
30 answer = funcname, filename, lineno
31 break
32 lineno = lineno + 1
33 fp.close()
34 return answer
Guido van Rossum921c8241992-01-10 14:54:42 +000035
36
Guido van Rossuma558e371994-11-10 22:27:35 +000037# Interaction prompt line will separate file and call info from code
38# text using value of line_prefix string. A newline and arrow may
39# be to your liking. You can set it once pdb is imported using the
40# command "pdb.line_prefix = '\n% '".
41# line_prefix = ': ' # Use this to get the old situation back
42line_prefix = '\n-> ' # Probably a better default
43
Guido van Rossum23efba41992-01-27 16:58:47 +000044class Pdb(bdb.Bdb, cmd.Cmd):
Guido van Rossum921c8241992-01-10 14:54:42 +000045
Guido van Rossum5ef74b81993-06-23 11:55:24 +000046 def __init__(self):
47 bdb.Bdb.__init__(self)
48 cmd.Cmd.__init__(self)
Guido van Rossum921c8241992-01-10 14:54:42 +000049 self.prompt = '(Pdb) '
Guido van Rossum2424f851998-09-11 22:50:09 +000050 self.aliases = {}
Guido van Rossumb5699c71998-07-20 23:13:54 +000051 # Try to load readline if it exists
52 try:
53 import readline
54 except ImportError:
55 pass
Guido van Rossum2424f851998-09-11 22:50:09 +000056
57 # Read $HOME/.pdbrc and ./.pdbrc
58 self.rcLines = []
59 if os.environ.has_key('HOME'):
60 envHome = os.environ['HOME']
61 try:
62 rcFile = open (envHome + "/.pdbrc")
63 except IOError:
64 pass
65 else:
66 for line in rcFile.readlines():
67 self.rcLines.append (line)
68 rcFile.close()
69 try:
70 rcFile = open ("./.pdbrc")
71 except IOError:
72 pass
73 else:
74 for line in rcFile.readlines():
75 self.rcLines.append (line)
76 rcFile.close()
Guido van Rossum921c8241992-01-10 14:54:42 +000077
78 def reset(self):
Guido van Rossum23efba41992-01-27 16:58:47 +000079 bdb.Bdb.reset(self)
Guido van Rossum921c8241992-01-10 14:54:42 +000080 self.forget()
81
82 def forget(self):
Guido van Rossum921c8241992-01-10 14:54:42 +000083 self.lineno = None
Guido van Rossum6fe08b01992-01-16 13:50:21 +000084 self.stack = []
Guido van Rossum7ac1c811992-01-16 13:55:21 +000085 self.curindex = 0
86 self.curframe = None
Guido van Rossum23efba41992-01-27 16:58:47 +000087
88 def setup(self, f, t):
89 self.forget()
90 self.stack, self.curindex = self.get_stack(f, t)
Guido van Rossum7ac1c811992-01-16 13:55:21 +000091 self.curframe = self.stack[self.curindex][0]
Guido van Rossum3a98e781998-09-17 15:00:30 +000092 self.execRcLines()
Guido van Rossum2424f851998-09-11 22:50:09 +000093
94 # Can be executed earlier than 'setup' if desired
95 def execRcLines(self):
96 if self.rcLines:
97 # Make local copy because of recursion
98 rcLines = self.rcLines
99 # executed only once
100 self.rcLines = []
101 for line in rcLines:
102 line = line[:-1]
103 if len (line) > 0 and line[0] != '#':
104 self.onecmd (line)
Guido van Rossum921c8241992-01-10 14:54:42 +0000105
Guido van Rossum23efba41992-01-27 16:58:47 +0000106 # Override Bdb methods (except user_call, for now)
Guido van Rossumb9142571992-01-12 23:32:55 +0000107
Guido van Rossum23efba41992-01-27 16:58:47 +0000108 def user_line(self, frame):
Guido van Rossum54f22ed2000-02-04 15:10:34 +0000109 """This function is called when we stop or break at this line."""
Guido van Rossum23efba41992-01-27 16:58:47 +0000110 self.interaction(frame, None)
Guido van Rossum7ac1c811992-01-16 13:55:21 +0000111
Guido van Rossum23efba41992-01-27 16:58:47 +0000112 def user_return(self, frame, return_value):
Guido van Rossum54f22ed2000-02-04 15:10:34 +0000113 """This function is called when a return trap is set here."""
Guido van Rossum23efba41992-01-27 16:58:47 +0000114 frame.f_locals['__return__'] = return_value
115 print '--Return--'
116 self.interaction(frame, None)
Guido van Rossum921c8241992-01-10 14:54:42 +0000117
Guido van Rossum23efba41992-01-27 16:58:47 +0000118 def user_exception(self, frame, (exc_type, exc_value, exc_traceback)):
Guido van Rossum54f22ed2000-02-04 15:10:34 +0000119 """This function is called if an exception occurs,
120 but only if we are to stop at or just below this level."""
Guido van Rossum23efba41992-01-27 16:58:47 +0000121 frame.f_locals['__exception__'] = exc_type, exc_value
Guido van Rossum5e38b6f1995-02-27 13:13:40 +0000122 if type(exc_type) == type(''):
123 exc_type_name = exc_type
124 else: exc_type_name = exc_type.__name__
125 print exc_type_name + ':', repr.repr(exc_value)
Guido van Rossum23efba41992-01-27 16:58:47 +0000126 self.interaction(frame, exc_traceback)
Guido van Rossum921c8241992-01-10 14:54:42 +0000127
Guido van Rossum23efba41992-01-27 16:58:47 +0000128 # General interaction function
Guido van Rossumb9142571992-01-12 23:32:55 +0000129
Guido van Rossum23efba41992-01-27 16:58:47 +0000130 def interaction(self, frame, traceback):
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000131 self.setup(frame, traceback)
Guido van Rossumb6aa92e1995-02-03 12:50:04 +0000132 self.print_stack_entry(self.stack[self.curindex])
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000133 self.cmdloop()
Guido van Rossumb9142571992-01-12 23:32:55 +0000134 self.forget()
Guido van Rossum23efba41992-01-27 16:58:47 +0000135
Guido van Rossum921c8241992-01-10 14:54:42 +0000136 def default(self, line):
Guido van Rossum23efba41992-01-27 16:58:47 +0000137 if line[:1] == '!': line = line[1:]
138 locals = self.curframe.f_locals
139 globals = self.curframe.f_globals
140 try:
Guido van Rossumf17361d1996-07-30 16:28:13 +0000141 code = compile(line + '\n', '<stdin>', 'single')
Guido van Rossumec8fd941995-08-07 20:16:05 +0000142 exec code in globals, locals
Guido van Rossum23efba41992-01-27 16:58:47 +0000143 except:
Guido van Rossumf15d1591997-09-29 23:22:12 +0000144 t, v = sys.exc_info()[:2]
145 if type(t) == type(''):
146 exc_type_name = t
147 else: exc_type_name = t.__name__
148 print '***', exc_type_name + ':', v
Guido van Rossum23efba41992-01-27 16:58:47 +0000149
Guido van Rossum2424f851998-09-11 22:50:09 +0000150 def precmd(self, line):
Guido van Rossum54f22ed2000-02-04 15:10:34 +0000151 """Handle alias expansion and ';;' separator."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000152 if not line:
153 return line
154 args = string.split(line)
155 while self.aliases.has_key(args[0]):
156 line = self.aliases[args[0]]
157 ii = 1
158 for tmpArg in args[1:]:
159 line = string.replace(line, "%" + str(ii),
160 tmpArg)
161 ii = ii + 1
Guido van Rossum3a98e781998-09-17 15:00:30 +0000162 line = string.replace(line, "%*",
163 string.join(args[1:], ' '))
Guido van Rossum2424f851998-09-11 22:50:09 +0000164 args = string.split(line)
Guido van Rossum3a98e781998-09-17 15:00:30 +0000165 # split into ';;' separated commands
Guido van Rossum2424f851998-09-11 22:50:09 +0000166 # unless it's an alias command
167 if args[0] != 'alias':
Guido van Rossum3a98e781998-09-17 15:00:30 +0000168 marker = string.find(line, ';;')
169 if marker >= 0:
170 # queue up everything after marker
171 next = string.lstrip(line[marker+2:])
Guido van Rossum2424f851998-09-11 22:50:09 +0000172 self.cmdqueue.append(next)
Guido van Rossum3a98e781998-09-17 15:00:30 +0000173 line = string.rstrip(line[:marker])
Guido van Rossum2424f851998-09-11 22:50:09 +0000174 return line
175
Guido van Rossum23efba41992-01-27 16:58:47 +0000176 # Command definitions, called by cmdloop()
177 # The argument is the remaining string on the command line
178 # Return true to exit from the command loop
Guido van Rossum921c8241992-01-10 14:54:42 +0000179
Guido van Rossum23efba41992-01-27 16:58:47 +0000180 do_h = cmd.Cmd.do_help
Guido van Rossumb6775db1994-08-01 11:34:53 +0000181
Guido van Rossum2424f851998-09-11 22:50:09 +0000182 def do_EOF(self, arg):
183 return 0 # Don't die on EOF
184
185 def do_break(self, arg, temporary = 0):
Guido van Rossumb5699c71998-07-20 23:13:54 +0000186 # break [ ([filename:]lineno | function) [, "condition"] ]
Guido van Rossum921c8241992-01-10 14:54:42 +0000187 if not arg:
Guido van Rossum2424f851998-09-11 22:50:09 +0000188 if self.breaks: # There's at least one
189 print "Num Type Disp Enb Where"
190 for bp in bdb.Breakpoint.bpbynumber:
191 if bp:
192 bp.bpprint()
Guido van Rossum921c8241992-01-10 14:54:42 +0000193 return
Guido van Rossumb5699c71998-07-20 23:13:54 +0000194 # parse arguments; comma has lowest precendence
195 # and cannot occur in filename
196 filename = None
197 lineno = None
198 cond = None
199 comma = string.find(arg, ',')
200 if comma > 0:
201 # parse stuff after comma: "condition"
202 cond = string.lstrip(arg[comma+1:])
203 arg = string.rstrip(arg[:comma])
Guido van Rossumb5699c71998-07-20 23:13:54 +0000204 # parse stuff before comma: [filename:]lineno | function
205 colon = string.rfind(arg, ':')
206 if colon >= 0:
207 filename = string.rstrip(arg[:colon])
Guido van Rossum2424f851998-09-11 22:50:09 +0000208 f = self.lookupmodule(filename)
209 if not f:
210 print '*** ', `filename`,
211 print 'not found from sys.path'
212 return
213 else:
214 filename = f
Guido van Rossumb5699c71998-07-20 23:13:54 +0000215 arg = string.lstrip(arg[colon+1:])
216 try:
217 lineno = int(arg)
218 except ValueError, msg:
219 print '*** Bad lineno:', arg
220 return
221 else:
222 # no colon; can be lineno or function
223 try:
224 lineno = int(arg)
225 except ValueError:
226 try:
227 func = eval(arg,
228 self.curframe.f_globals,
229 self.curframe.f_locals)
230 except:
Guido van Rossum2424f851998-09-11 22:50:09 +0000231 func = arg
Guido van Rossumb5699c71998-07-20 23:13:54 +0000232 try:
233 if hasattr(func, 'im_func'):
234 func = func.im_func
235 code = func.func_code
Guido van Rossum2424f851998-09-11 22:50:09 +0000236 lineno = code.co_firstlineno
Guido van Rossumb5699c71998-07-20 23:13:54 +0000237 filename = code.co_filename
Guido van Rossum2424f851998-09-11 22:50:09 +0000238 except:
239 # last thing to try
240 (ok, filename, ln) = self.lineinfo(arg)
241 if not ok:
242 print '*** The specified object',
243 print `arg`,
244 print 'is not a function'
245 print ('or was not found '
246 'along sys.path.')
247 return
248 lineno = int(ln)
Guido van Rossumb5699c71998-07-20 23:13:54 +0000249 if not filename:
Guido van Rossum2424f851998-09-11 22:50:09 +0000250 filename = self.defaultFile()
251 # Check for reasonable breakpoint
252 line = self.checkline(filename, lineno)
253 if line:
254 # now set the break point
255 err = self.set_break(filename, line, temporary, cond)
256 if err: print '***', err
Guido van Rossum816a9fb1999-01-25 20:56:07 +0000257 else:
258 bp = self.get_breaks(filename, line)[-1]
259 print "Breakpoint %d at %s:%d" % (bp.number,
260 bp.file,
261 bp.line)
Guido van Rossum2424f851998-09-11 22:50:09 +0000262
263 # To be overridden in derived debuggers
264 def defaultFile(self):
Guido van Rossum54f22ed2000-02-04 15:10:34 +0000265 """Produce a reasonable default."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000266 filename = self.curframe.f_code.co_filename
267 if filename == '<string>' and mainpyfile:
268 filename = mainpyfile
269 return filename
Guido van Rossum9e1ee971997-07-11 13:43:53 +0000270
Guido van Rossum921c8241992-01-10 14:54:42 +0000271 do_b = do_break
272
Guido van Rossum2424f851998-09-11 22:50:09 +0000273 def do_tbreak(self, arg):
274 self.do_break(arg, 1)
275
276 def lineinfo(self, identifier):
277 failed = (None, None, None)
278 # Input is identifier, may be in single quotes
279 idstring = string.split(identifier, "'")
280 if len(idstring) == 1:
281 # not in single quotes
282 id = string.strip(idstring[0])
283 elif len(idstring) == 3:
284 # quoted
285 id = string.strip(idstring[1])
286 else:
287 return failed
288 if id == '': return failed
289 parts = string.split(id, '.')
290 # Protection for derived debuggers
291 if parts[0] == 'self':
292 del parts[0]
293 if len(parts) == 0:
294 return failed
295 # Best first guess at file to look at
296 fname = self.defaultFile()
297 if len(parts) == 1:
298 item = parts[0]
299 else:
300 # More than one part.
301 # First is module, second is method/class
302 f = self.lookupmodule(parts[0])
303 if f:
304 fname = f
305 item = parts[1]
Barry Warsaw2bee8fe1999-09-09 16:32:41 +0000306 answer = find_function(item, fname)
307 return answer or failed
Guido van Rossum2424f851998-09-11 22:50:09 +0000308
309 def checkline(self, filename, lineno):
310 """Return line number of first line at or after input
311 argument such that if the input points to a 'def', the
312 returned line number is the first
313 non-blank/non-comment line to follow. If the input
314 points to a blank or comment line, return 0. At end
315 of file, also return 0."""
316
317 line = linecache.getline(filename, lineno)
318 if not line:
319 print 'End of file'
320 return 0
321 line = string.strip(line)
322 # Don't allow setting breakpoint at a blank line
323 if ( not line or (line[0] == '#') or
324 (line[:3] == '"""') or line[:3] == "'''" ):
325 print '*** Blank or comment'
326 return 0
327 # When a file is read in and a breakpoint is at
328 # the 'def' statement, the system stops there at
329 # code parse time. We don't want that, so all breakpoints
330 # set at 'def' statements are moved one line onward
331 if line[:3] == 'def':
332 incomment = ''
333 while 1:
334 lineno = lineno+1
335 line = linecache.getline(filename, lineno)
336 if not line:
337 print 'end of file'
338 return 0
339 line = string.strip(line)
340 if incomment:
341 if len(line) < 3: continue
342 if (line[-3:] == incomment):
343 incomment = ''
344 continue
345 if not line: continue # Blank line
346 if len(line) >= 3:
347 if (line[:3] == '"""'
348 or line[:3] == "'''"):
Guido van Rossum19878f51999-11-03 13:10:07 +0000349 if line[-3:] == line[:3]:
350 # one-line string
351 continue
Guido van Rossum2424f851998-09-11 22:50:09 +0000352 incomment = line[:3]
353 continue
354 if line[0] != '#': break
355 return lineno
356
357 def do_enable(self, arg):
358 args = string.split(arg)
359 for i in args:
360 bp = bdb.Breakpoint.bpbynumber[int(i)]
361 if bp:
362 bp.enable()
363
364 def do_disable(self, arg):
365 args = string.split(arg)
366 for i in args:
367 bp = bdb.Breakpoint.bpbynumber[int(i)]
368 if bp:
369 bp.disable()
370
371 def do_condition(self, arg):
372 # arg is breakpoint number and condition
373 args = string.split(arg, ' ', 1)
374 bpnum = int(string.strip(args[0]))
375 try:
376 cond = args[1]
377 except:
378 cond = None
379 bp = bdb.Breakpoint.bpbynumber[bpnum]
380 if bp:
381 bp.cond = cond
382 if not cond:
383 print 'Breakpoint', bpnum,
384 print 'is now unconditional.'
385
386 def do_ignore(self,arg):
Guido van Rossum54f22ed2000-02-04 15:10:34 +0000387 """arg is bp number followed by ignore count."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000388 args = string.split(arg)
389 bpnum = int(string.strip(args[0]))
390 try:
391 count = int(string.strip(args[1]))
392 except:
393 count = 0
394 bp = bdb.Breakpoint.bpbynumber[bpnum]
395 if bp:
396 bp.ignore = count
397 if (count > 0):
398 reply = 'Will ignore next '
399 if (count > 1):
400 reply = reply + '%d crossings' % count
401 else:
402 reply = reply + '1 crossing'
403 print reply + ' of breakpoint %d.' % bpnum
404 else:
405 print 'Will stop next time breakpoint',
406 print bpnum, 'is reached.'
407
Guido van Rossum921c8241992-01-10 14:54:42 +0000408 def do_clear(self, arg):
Guido van Rossum54f22ed2000-02-04 15:10:34 +0000409 """Three possibilities, tried in this order:
410 clear -> clear all breaks, ask for confirmation
411 clear file:lineno -> clear all breaks at file:lineno
412 clear bpno bpno ... -> clear breakpoints by number"""
Guido van Rossum921c8241992-01-10 14:54:42 +0000413 if not arg:
Guido van Rossumb9142571992-01-12 23:32:55 +0000414 try:
415 reply = raw_input('Clear all breaks? ')
416 except EOFError:
417 reply = 'no'
418 reply = string.lower(string.strip(reply))
419 if reply in ('y', 'yes'):
Guido van Rossum23efba41992-01-27 16:58:47 +0000420 self.clear_all_breaks()
Guido van Rossum921c8241992-01-10 14:54:42 +0000421 return
Guido van Rossum816a9fb1999-01-25 20:56:07 +0000422 if ':' in arg:
423 # Make sure it works for "clear C:\foo\bar.py:12"
424 i = string.rfind(arg, ':')
425 filename = arg[:i]
426 arg = arg[i+1:]
427 try:
428 lineno = int(arg)
429 except:
430 err = "Invalid line number (%s)" % arg
431 else:
432 err = self.clear_break(filename, lineno)
433 if err: print '***', err
434 return
Guido van Rossum2424f851998-09-11 22:50:09 +0000435 numberlist = string.split(arg)
436 for i in numberlist:
Guido van Rossum816a9fb1999-01-25 20:56:07 +0000437 err = self.clear_bpbynumber(i)
Guido van Rossum2424f851998-09-11 22:50:09 +0000438 if err:
Guido van Rossum816a9fb1999-01-25 20:56:07 +0000439 print '***', err
Guido van Rossum2424f851998-09-11 22:50:09 +0000440 else:
441 print 'Deleted breakpoint %s ' % (i,)
Guido van Rossumb9142571992-01-12 23:32:55 +0000442 do_cl = do_clear # 'c' is already an abbreviation for 'continue'
Guido van Rossum921c8241992-01-10 14:54:42 +0000443
444 def do_where(self, arg):
Guido van Rossum23efba41992-01-27 16:58:47 +0000445 self.print_stack_trace()
Guido van Rossum921c8241992-01-10 14:54:42 +0000446 do_w = do_where
447
448 def do_up(self, arg):
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000449 if self.curindex == 0:
450 print '*** Oldest frame'
Guido van Rossum921c8241992-01-10 14:54:42 +0000451 else:
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000452 self.curindex = self.curindex - 1
453 self.curframe = self.stack[self.curindex][0]
Guido van Rossum23efba41992-01-27 16:58:47 +0000454 self.print_stack_entry(self.stack[self.curindex])
Guido van Rossumc629d341992-11-05 10:43:02 +0000455 self.lineno = None
Guido van Rossumb9142571992-01-12 23:32:55 +0000456 do_u = do_up
457
458 def do_down(self, arg):
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000459 if self.curindex + 1 == len(self.stack):
460 print '*** Newest frame'
Guido van Rossumb9142571992-01-12 23:32:55 +0000461 else:
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000462 self.curindex = self.curindex + 1
463 self.curframe = self.stack[self.curindex][0]
Guido van Rossum23efba41992-01-27 16:58:47 +0000464 self.print_stack_entry(self.stack[self.curindex])
Guido van Rossumc629d341992-11-05 10:43:02 +0000465 self.lineno = None
Guido van Rossum921c8241992-01-10 14:54:42 +0000466 do_d = do_down
467
468 def do_step(self, arg):
Guido van Rossum23efba41992-01-27 16:58:47 +0000469 self.set_step()
Guido van Rossumb9142571992-01-12 23:32:55 +0000470 return 1
Guido van Rossum921c8241992-01-10 14:54:42 +0000471 do_s = do_step
472
473 def do_next(self, arg):
Guido van Rossum23efba41992-01-27 16:58:47 +0000474 self.set_next(self.curframe)
Guido van Rossumb9142571992-01-12 23:32:55 +0000475 return 1
Guido van Rossum921c8241992-01-10 14:54:42 +0000476 do_n = do_next
477
Guido van Rossumb9142571992-01-12 23:32:55 +0000478 def do_return(self, arg):
Guido van Rossum23efba41992-01-27 16:58:47 +0000479 self.set_return(self.curframe)
Guido van Rossumb9142571992-01-12 23:32:55 +0000480 return 1
481 do_r = do_return
482
Guido van Rossum921c8241992-01-10 14:54:42 +0000483 def do_continue(self, arg):
Guido van Rossum23efba41992-01-27 16:58:47 +0000484 self.set_continue()
Guido van Rossumb9142571992-01-12 23:32:55 +0000485 return 1
Guido van Rossum921c8241992-01-10 14:54:42 +0000486 do_c = do_cont = do_continue
487
488 def do_quit(self, arg):
Guido van Rossum23efba41992-01-27 16:58:47 +0000489 self.set_quit()
490 return 1
Guido van Rossum921c8241992-01-10 14:54:42 +0000491 do_q = do_quit
492
Guido van Rossum23efba41992-01-27 16:58:47 +0000493 def do_args(self, arg):
Guido van Rossum46c86bb1998-02-25 20:50:32 +0000494 f = self.curframe
495 co = f.f_code
496 dict = f.f_locals
497 n = co.co_argcount
498 if co.co_flags & 4: n = n+1
499 if co.co_flags & 8: n = n+1
500 for i in range(n):
501 name = co.co_varnames[i]
502 print name, '=',
503 if dict.has_key(name): print dict[name]
504 else: print "*** undefined ***"
Guido van Rossum23efba41992-01-27 16:58:47 +0000505 do_a = do_args
506
507 def do_retval(self, arg):
508 if self.curframe.f_locals.has_key('__return__'):
509 print self.curframe.f_locals['__return__']
510 else:
511 print '*** Not yet returned!'
512 do_rv = do_retval
513
514 def do_p(self, arg):
515 try:
Guido van Rossum2424f851998-09-11 22:50:09 +0000516 value = eval(arg, self.curframe.f_globals,
Guido van Rossum23efba41992-01-27 16:58:47 +0000517 self.curframe.f_locals)
518 except:
Guido van Rossumf15d1591997-09-29 23:22:12 +0000519 t, v = sys.exc_info()[:2]
520 if type(t) == type(''):
521 exc_type_name = t
522 else: exc_type_name = t.__name__
523 print '***', exc_type_name + ':', `v`
Guido van Rossum23efba41992-01-27 16:58:47 +0000524 return
Guido van Rossum8e2ec561993-07-29 09:37:38 +0000525
Guido van Rossum23efba41992-01-27 16:58:47 +0000526 print `value`
527
Guido van Rossum921c8241992-01-10 14:54:42 +0000528 def do_list(self, arg):
Guido van Rossumb9142571992-01-12 23:32:55 +0000529 self.lastcmd = 'list'
Guido van Rossum921c8241992-01-10 14:54:42 +0000530 last = None
531 if arg:
532 try:
533 x = eval(arg, {}, {})
534 if type(x) == type(()):
535 first, last = x
536 first = int(first)
537 last = int(last)
538 if last < first:
539 # Assume it's a count
540 last = first + last
541 else:
Guido van Rossumc629d341992-11-05 10:43:02 +0000542 first = max(1, int(x) - 5)
Guido van Rossum921c8241992-01-10 14:54:42 +0000543 except:
544 print '*** Error in argument:', `arg`
545 return
546 elif self.lineno is None:
547 first = max(1, self.curframe.f_lineno - 5)
548 else:
549 first = self.lineno + 1
Guido van Rossumc629d341992-11-05 10:43:02 +0000550 if last == None:
Guido van Rossum921c8241992-01-10 14:54:42 +0000551 last = first + 10
552 filename = self.curframe.f_code.co_filename
Guido van Rossum23efba41992-01-27 16:58:47 +0000553 breaklist = self.get_file_breaks(filename)
Guido van Rossum921c8241992-01-10 14:54:42 +0000554 try:
555 for lineno in range(first, last+1):
556 line = linecache.getline(filename, lineno)
557 if not line:
558 print '[EOF]'
559 break
560 else:
561 s = string.rjust(`lineno`, 3)
562 if len(s) < 4: s = s + ' '
563 if lineno in breaklist: s = s + 'B'
564 else: s = s + ' '
565 if lineno == self.curframe.f_lineno:
566 s = s + '->'
567 print s + '\t' + line,
568 self.lineno = lineno
569 except KeyboardInterrupt:
570 pass
571 do_l = do_list
Guido van Rossum00230781993-03-29 11:39:45 +0000572
573 def do_whatis(self, arg):
Guido van Rossum00230781993-03-29 11:39:45 +0000574 try:
Guido van Rossum2424f851998-09-11 22:50:09 +0000575 value = eval(arg, self.curframe.f_globals,
Guido van Rossum00230781993-03-29 11:39:45 +0000576 self.curframe.f_locals)
577 except:
Guido van Rossumf15d1591997-09-29 23:22:12 +0000578 t, v = sys.exc_info()[:2]
579 if type(t) == type(''):
580 exc_type_name = t
581 else: exc_type_name = t.__name__
582 print '***', exc_type_name + ':', `v`
Guido van Rossum00230781993-03-29 11:39:45 +0000583 return
584 code = None
585 # Is it a function?
586 try: code = value.func_code
587 except: pass
588 if code:
Guido van Rossumb6775db1994-08-01 11:34:53 +0000589 print 'Function', code.co_name
Guido van Rossum00230781993-03-29 11:39:45 +0000590 return
591 # Is it an instance method?
592 try: code = value.im_func.func_code
593 except: pass
594 if code:
Guido van Rossumb6775db1994-08-01 11:34:53 +0000595 print 'Method', code.co_name
Guido van Rossum00230781993-03-29 11:39:45 +0000596 return
597 # None of the above...
598 print type(value)
Guido van Rossum2424f851998-09-11 22:50:09 +0000599
600 def do_alias(self, arg):
601 args = string.split (arg)
602 if len(args) == 0:
603 keys = self.aliases.keys()
604 keys.sort()
605 for alias in keys:
606 print "%s = %s" % (alias, self.aliases[alias])
607 return
608 if self.aliases.has_key(args[0]) and len (args) == 1:
609 print "%s = %s" % (args[0], self.aliases[args[0]])
610 else:
611 self.aliases[args[0]] = string.join(args[1:], ' ')
612
613 def do_unalias(self, arg):
614 args = string.split (arg)
615 if len(args) == 0: return
616 if self.aliases.has_key(args[0]):
617 del self.aliases[args[0]]
618
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000619 # Print a traceback starting at the top stack frame.
Guido van Rossum23efba41992-01-27 16:58:47 +0000620 # The most recently entered frame is printed last;
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000621 # this is different from dbx and gdb, but consistent with
622 # the Python interpreter's stack trace.
623 # It is also consistent with the up/down commands (which are
624 # compatible with dbx and gdb: up moves towards 'main()'
625 # and down moves towards the most recent stack frame).
Guido van Rossum921c8241992-01-10 14:54:42 +0000626
Guido van Rossum23efba41992-01-27 16:58:47 +0000627 def print_stack_trace(self):
628 try:
629 for frame_lineno in self.stack:
630 self.print_stack_entry(frame_lineno)
631 except KeyboardInterrupt:
632 pass
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000633
Guido van Rossumb6aa92e1995-02-03 12:50:04 +0000634 def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix):
Guido van Rossum23efba41992-01-27 16:58:47 +0000635 frame, lineno = frame_lineno
636 if frame is self.curframe:
637 print '>',
638 else:
639 print ' ',
Guido van Rossuma558e371994-11-10 22:27:35 +0000640 print self.format_stack_entry(frame_lineno, prompt_prefix)
Guido van Rossum921c8241992-01-10 14:54:42 +0000641
642
Guido van Rossumb6775db1994-08-01 11:34:53 +0000643 # Help methods (derived from pdb.doc)
644
645 def help_help(self):
646 self.help_h()
647
648 def help_h(self):
649 print """h(elp)
650 Without argument, print the list of available commands.
651 With a command name as argument, print help about that command
652 "help pdb" pipes the full documentation file to the $PAGER
653 "help exec" gives help on the ! command"""
654
655 def help_where(self):
656 self.help_w()
657
658 def help_w(self):
659 print """w(here)
660 Print a stack trace, with the most recent frame at the bottom.
661 An arrow indicates the "current frame", which determines the
662 context of most commands."""
663
664 def help_down(self):
665 self.help_d()
666
667 def help_d(self):
668 print """d(own)
669 Move the current frame one level down in the stack trace
670 (to an older frame)."""
671
672 def help_up(self):
673 self.help_u()
674
675 def help_u(self):
676 print """u(p)
677 Move the current frame one level up in the stack trace
678 (to a newer frame)."""
679
680 def help_break(self):
681 self.help_b()
682
683 def help_b(self):
Guido van Rossum3a98e781998-09-17 15:00:30 +0000684 print """b(reak) ([file:]lineno | function) [, condition]
Guido van Rossumb6775db1994-08-01 11:34:53 +0000685 With a line number argument, set a break there in the current
Guido van Rossum2424f851998-09-11 22:50:09 +0000686 file. With a function name, set a break at first executable line
687 of that function. Without argument, list all breaks. If a second
Guido van Rossum9e1ee971997-07-11 13:43:53 +0000688 argument is present, it is a string specifying an expression
689 which must evaluate to true before the breakpoint is honored.
Guido van Rossumb5699c71998-07-20 23:13:54 +0000690
691 The line number may be prefixed with a filename and a colon,
692 to specify a breakpoint in another file (probably one that
Guido van Rossum2424f851998-09-11 22:50:09 +0000693 hasn't been loaded yet). The file is searched for on sys.path;
Guido van Rossum1f00eed1998-07-22 13:35:21 +0000694 the .py suffix may be omitted."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000695
696 def help_clear(self):
697 self.help_cl()
698
699 def help_cl(self):
Guido van Rossum816a9fb1999-01-25 20:56:07 +0000700 print "cl(ear) filename:lineno"
Guido van Rossum2424f851998-09-11 22:50:09 +0000701 print """cl(ear) [bpnumber [bpnumber...]]
702 With a space separated list of breakpoint numbers, clear
703 those breakpoints. Without argument, clear all breaks (but
Guido van Rossum816a9fb1999-01-25 20:56:07 +0000704 first ask confirmation). With a filename:lineno argument,
705 clear all breaks at that line in that file.
Guido van Rossumb5699c71998-07-20 23:13:54 +0000706
Guido van Rossum2424f851998-09-11 22:50:09 +0000707 Note that the argument is different from previous versions of
708 the debugger (in python distributions 1.5.1 and before) where
Guido van Rossumb657c931999-01-28 14:38:32 +0000709 a linenumber was used instead of either filename:lineno or
710 breakpoint numbers."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000711
712 def help_tbreak(self):
713 print """tbreak same arguments as break, but breakpoint is
714 removed when first hit."""
715
716 def help_enable(self):
717 print """enable bpnumber [bpnumber ...]
718 Enables the breakpoints given as a space separated list of
719 bp numbers."""
720
721 def help_disable(self):
722 print """disable bpnumber [bpnumber ...]
723 Disables the breakpoints given as a space separated list of
724 bp numbers."""
725
726 def help_ignore(self):
727 print """ignore bpnumber count
728 Sets the ignore count for the given breakpoint number. A breakpoint
729 becomes active when the ignore count is zero. When non-zero, the
730 count is decremented each time the breakpoint is reached and the
731 breakpoint is not disabled and any associated condition evaluates
732 to true."""
733
734 def help_condition(self):
735 print """condition bpnumber str_condition
736 str_condition is a string specifying an expression which
737 must evaluate to true before the breakpoint is honored.
738 If str_condition is absent, any existing condition is removed;
739 i.e., the breakpoint is made unconditional."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000740
741 def help_step(self):
742 self.help_s()
743
744 def help_s(self):
745 print """s(tep)
746 Execute the current line, stop at the first possible occasion
747 (either in a function that is called or in the current function)."""
748
749 def help_next(self):
750 self.help_n()
751
752 def help_n(self):
753 print """n(ext)
754 Continue execution until the next line in the current function
755 is reached or it returns."""
756
757 def help_return(self):
758 self.help_r()
759
760 def help_r(self):
761 print """r(eturn)
762 Continue execution until the current function returns."""
763
764 def help_continue(self):
765 self.help_c()
766
767 def help_cont(self):
768 self.help_c()
769
770 def help_c(self):
771 print """c(ont(inue))
772 Continue execution, only stop when a breakpoint is encountered."""
773
774 def help_list(self):
775 self.help_l()
776
777 def help_l(self):
778 print """l(ist) [first [,last]]
779 List source code for the current file.
780 Without arguments, list 11 lines around the current line
781 or continue the previous listing.
782 With one argument, list 11 lines starting at that line.
783 With two arguments, list the given range;
784 if the second argument is less than the first, it is a count."""
785
786 def help_args(self):
787 self.help_a()
788
789 def help_a(self):
790 print """a(rgs)
Guido van Rossum46c86bb1998-02-25 20:50:32 +0000791 Print the arguments of the current function."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000792
793 def help_p(self):
794 print """p expression
795 Print the value of the expression."""
796
797 def help_exec(self):
798 print """(!) statement
799 Execute the (one-line) statement in the context of
800 the current stack frame.
801 The exclamation point can be omitted unless the first word
802 of the statement resembles a debugger command.
803 To assign to a global variable you must always prefix the
804 command with a 'global' command, e.g.:
805 (Pdb) global list_options; list_options = ['-l']
806 (Pdb)"""
807
808 def help_quit(self):
809 self.help_q()
810
811 def help_q(self):
812 print """q(uit) Quit from the debugger.
813 The program being executed is aborted."""
814
Guido van Rossum2424f851998-09-11 22:50:09 +0000815 def help_whatis(self):
816 print """whatis arg
817 Prints the type of the argument."""
818
819 def help_EOF(self):
820 print """EOF
821 Handles the receipt of EOF as a command."""
822
823 def help_alias(self):
824 print """alias [name [command [parameter parameter ...] ]]
825 Creates an alias called 'name' the executes 'command'. The command
826 must *not* be enclosed in quotes. Replaceable parameters are
827 indicated by %1, %2, and so on, while %* is replaced by all the
828 parameters. If no command is given, the current alias for name
829 is shown. If no name is given, all aliases are listed.
830
831 Aliases may be nested and can contain anything that can be
832 legally typed at the pdb prompt. Note! You *can* override
833 internal pdb commands with aliases! Those internal commands
834 are then hidden until the alias is removed. Aliasing is recursively
835 applied to the first word of the command line; all other words
836 in the line are left alone.
837
838 Some useful aliases (especially when placed in the .pdbrc file) are:
839
840 #Print instance variables (usage "pi classInst")
841 alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
842
843 #Print instance variables in self
844 alias ps pi self
845 """
846
847 def help_unalias(self):
848 print """unalias name
849 Deletes the specified alias."""
850
Guido van Rossumb6775db1994-08-01 11:34:53 +0000851 def help_pdb(self):
852 help()
853
Guido van Rossumb5699c71998-07-20 23:13:54 +0000854 def lookupmodule(self, filename):
Guido van Rossum54f22ed2000-02-04 15:10:34 +0000855 """Helper function for break/clear parsing -- may be overridden."""
Guido van Rossum1f00eed1998-07-22 13:35:21 +0000856 root, ext = os.path.splitext(filename)
857 if ext == '':
858 filename = filename + '.py'
859 if os.path.isabs(filename):
860 return filename
Guido van Rossumb5699c71998-07-20 23:13:54 +0000861 for dirname in sys.path:
Guido van Rossum2424f851998-09-11 22:50:09 +0000862 while os.path.islink(dirname):
863 dirname = os.readlink(dirname)
Guido van Rossumb5699c71998-07-20 23:13:54 +0000864 fullname = os.path.join(dirname, filename)
865 if os.path.exists(fullname):
866 return fullname
Guido van Rossum2424f851998-09-11 22:50:09 +0000867 return None
Guido van Rossumb5699c71998-07-20 23:13:54 +0000868
Guido van Rossum35771131992-09-08 11:59:04 +0000869# Simplified interface
870
Guido van Rossum5e38b6f1995-02-27 13:13:40 +0000871def run(statement, globals=None, locals=None):
872 Pdb().run(statement, globals, locals)
873
874def runeval(expression, globals=None, locals=None):
875 return Pdb().runeval(expression, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000876
877def runctx(statement, globals, locals):
Guido van Rossum5e38b6f1995-02-27 13:13:40 +0000878 # B/W compatibility
879 run(statement, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000880
Guido van Rossum4e160981992-09-02 20:43:20 +0000881def runcall(*args):
Guido van Rossum5e38b6f1995-02-27 13:13:40 +0000882 return apply(Pdb().runcall, args)
Guido van Rossum4e160981992-09-02 20:43:20 +0000883
Guido van Rossumb6775db1994-08-01 11:34:53 +0000884def set_trace():
885 Pdb().set_trace()
Guido van Rossum35771131992-09-08 11:59:04 +0000886
887# Post-Mortem interface
888
889def post_mortem(t):
Guido van Rossum5ef74b81993-06-23 11:55:24 +0000890 p = Pdb()
Guido van Rossum35771131992-09-08 11:59:04 +0000891 p.reset()
892 while t.tb_next <> None: t = t.tb_next
893 p.interaction(t.tb_frame, t)
894
895def pm():
Guido van Rossum35771131992-09-08 11:59:04 +0000896 post_mortem(sys.last_traceback)
897
898
899# Main program for testing
900
Guido van Rossum23efba41992-01-27 16:58:47 +0000901TESTCMD = 'import x; x.main()'
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000902
Guido van Rossum921c8241992-01-10 14:54:42 +0000903def test():
Guido van Rossum23efba41992-01-27 16:58:47 +0000904 run(TESTCMD)
Guido van Rossume61fa0a1993-10-22 13:56:35 +0000905
906# print help
907def help():
908 for dirname in sys.path:
909 fullname = os.path.join(dirname, 'pdb.doc')
910 if os.path.exists(fullname):
911 sts = os.system('${PAGER-more} '+fullname)
912 if sts: print '*** Pager exit status:', sts
913 break
914 else:
915 print 'Sorry, can\'t find the help file "pdb.doc"',
916 print 'along the Python search path'
Guido van Rossumf17361d1996-07-30 16:28:13 +0000917
Guido van Rossumb5699c71998-07-20 23:13:54 +0000918mainmodule = ''
919mainpyfile = ''
920
Guido van Rossumf17361d1996-07-30 16:28:13 +0000921# When invoked as main program, invoke the debugger on a script
922if __name__=='__main__':
Guido van Rossumf17361d1996-07-30 16:28:13 +0000923 if not sys.argv[1:]:
924 print "usage: pdb.py scriptfile [arg] ..."
925 sys.exit(2)
926
Guido van Rossumb5699c71998-07-20 23:13:54 +0000927 mainpyfile = filename = sys.argv[1] # Get script filename
928 if not os.path.exists(filename):
929 print 'Error:', `filename`, 'does not exist'
930 sys.exit(1)
931 mainmodule = os.path.basename(filename)
Guido van Rossumec577d51996-09-10 17:39:34 +0000932 del sys.argv[0] # Hide "pdb.py" from argument list
933
934 # Insert script directory in front of module search path
935 sys.path.insert(0, os.path.dirname(filename))
Guido van Rossumf17361d1996-07-30 16:28:13 +0000936
Guido van Rossumc2047c11998-10-15 01:38:23 +0000937 run('execfile(' + `filename` + ')')