blob: b0c1a1736c9d897b5991a475aa8128215d406ef2 [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 Rossum6fe08b01992-01-16 13:50:21 +00003# pdb.py -- finally, 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
Guido van Rossum921c8241992-01-10 14:54:42 +000014
15
Guido van Rossuma558e371994-11-10 22:27:35 +000016# Interaction prompt line will separate file and call info from code
17# text using value of line_prefix string. A newline and arrow may
18# be to your liking. You can set it once pdb is imported using the
19# command "pdb.line_prefix = '\n% '".
20# line_prefix = ': ' # Use this to get the old situation back
21line_prefix = '\n-> ' # Probably a better default
22
Guido van Rossum23efba41992-01-27 16:58:47 +000023class Pdb(bdb.Bdb, cmd.Cmd):
Guido van Rossum921c8241992-01-10 14:54:42 +000024
Guido van Rossum5ef74b81993-06-23 11:55:24 +000025 def __init__(self):
26 bdb.Bdb.__init__(self)
27 cmd.Cmd.__init__(self)
Guido van Rossum921c8241992-01-10 14:54:42 +000028 self.prompt = '(Pdb) '
Guido van Rossum2424f851998-09-11 22:50:09 +000029 self.lineinfoCmd = 'egrep -n "def *%s *[(:]" %s /dev/null'
30 self.aliases = {}
Guido van Rossumb5699c71998-07-20 23:13:54 +000031 # Try to load readline if it exists
32 try:
33 import readline
34 except ImportError:
35 pass
Guido van Rossum2424f851998-09-11 22:50:09 +000036
37 # Read $HOME/.pdbrc and ./.pdbrc
38 self.rcLines = []
39 if os.environ.has_key('HOME'):
40 envHome = os.environ['HOME']
41 try:
42 rcFile = open (envHome + "/.pdbrc")
43 except IOError:
44 pass
45 else:
46 for line in rcFile.readlines():
47 self.rcLines.append (line)
48 rcFile.close()
49 try:
50 rcFile = open ("./.pdbrc")
51 except IOError:
52 pass
53 else:
54 for line in rcFile.readlines():
55 self.rcLines.append (line)
56 rcFile.close()
Guido van Rossum921c8241992-01-10 14:54:42 +000057
58 def reset(self):
Guido van Rossum23efba41992-01-27 16:58:47 +000059 bdb.Bdb.reset(self)
Guido van Rossum921c8241992-01-10 14:54:42 +000060 self.forget()
61
62 def forget(self):
Guido van Rossum921c8241992-01-10 14:54:42 +000063 self.lineno = None
Guido van Rossum6fe08b01992-01-16 13:50:21 +000064 self.stack = []
Guido van Rossum7ac1c811992-01-16 13:55:21 +000065 self.curindex = 0
66 self.curframe = None
Guido van Rossum23efba41992-01-27 16:58:47 +000067
68 def setup(self, f, t):
69 self.forget()
70 self.stack, self.curindex = self.get_stack(f, t)
Guido van Rossum7ac1c811992-01-16 13:55:21 +000071 self.curframe = self.stack[self.curindex][0]
Guido van Rossum2424f851998-09-11 22:50:09 +000072 self.execRcLines();
73
74 # Can be executed earlier than 'setup' if desired
75 def execRcLines(self):
76 if self.rcLines:
77 # Make local copy because of recursion
78 rcLines = self.rcLines
79 # executed only once
80 self.rcLines = []
81 for line in rcLines:
82 line = line[:-1]
83 if len (line) > 0 and line[0] != '#':
84 self.onecmd (line)
Guido van Rossum921c8241992-01-10 14:54:42 +000085
Guido van Rossum23efba41992-01-27 16:58:47 +000086 # Override Bdb methods (except user_call, for now)
Guido van Rossumb9142571992-01-12 23:32:55 +000087
Guido van Rossum23efba41992-01-27 16:58:47 +000088 def user_line(self, frame):
89 # This function is called when we stop or break at this line
90 self.interaction(frame, None)
Guido van Rossum7ac1c811992-01-16 13:55:21 +000091
Guido van Rossum23efba41992-01-27 16:58:47 +000092 def user_return(self, frame, return_value):
93 # This function is called when a return trap is set here
94 frame.f_locals['__return__'] = return_value
95 print '--Return--'
96 self.interaction(frame, None)
Guido van Rossum921c8241992-01-10 14:54:42 +000097
Guido van Rossum23efba41992-01-27 16:58:47 +000098 def user_exception(self, frame, (exc_type, exc_value, exc_traceback)):
99 # This function is called if an exception occurs,
100 # but only if we are to stop at or just below this level
101 frame.f_locals['__exception__'] = exc_type, exc_value
Guido van Rossum5e38b6f1995-02-27 13:13:40 +0000102 if type(exc_type) == type(''):
103 exc_type_name = exc_type
104 else: exc_type_name = exc_type.__name__
105 print exc_type_name + ':', repr.repr(exc_value)
Guido van Rossum23efba41992-01-27 16:58:47 +0000106 self.interaction(frame, exc_traceback)
Guido van Rossum921c8241992-01-10 14:54:42 +0000107
Guido van Rossum23efba41992-01-27 16:58:47 +0000108 # General interaction function
Guido van Rossumb9142571992-01-12 23:32:55 +0000109
Guido van Rossum23efba41992-01-27 16:58:47 +0000110 def interaction(self, frame, traceback):
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000111 self.setup(frame, traceback)
Guido van Rossumb6aa92e1995-02-03 12:50:04 +0000112 self.print_stack_entry(self.stack[self.curindex])
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000113 self.cmdloop()
Guido van Rossumb9142571992-01-12 23:32:55 +0000114 self.forget()
Guido van Rossum23efba41992-01-27 16:58:47 +0000115
Guido van Rossum921c8241992-01-10 14:54:42 +0000116 def default(self, line):
Guido van Rossum23efba41992-01-27 16:58:47 +0000117 if line[:1] == '!': line = line[1:]
118 locals = self.curframe.f_locals
119 globals = self.curframe.f_globals
120 try:
Guido van Rossumf17361d1996-07-30 16:28:13 +0000121 code = compile(line + '\n', '<stdin>', 'single')
Guido van Rossumec8fd941995-08-07 20:16:05 +0000122 exec code in globals, locals
Guido van Rossum23efba41992-01-27 16:58:47 +0000123 except:
Guido van Rossumf15d1591997-09-29 23:22:12 +0000124 t, v = sys.exc_info()[:2]
125 if type(t) == type(''):
126 exc_type_name = t
127 else: exc_type_name = t.__name__
128 print '***', exc_type_name + ':', v
Guido van Rossum23efba41992-01-27 16:58:47 +0000129
Guido van Rossum2424f851998-09-11 22:50:09 +0000130 def precmd(self, line):
131 # Handle alias expansion and ';' separator
132 if not line:
133 return line
134 args = string.split(line)
135 while self.aliases.has_key(args[0]):
136 line = self.aliases[args[0]]
137 ii = 1
138 for tmpArg in args[1:]:
139 line = string.replace(line, "%" + str(ii),
140 tmpArg)
141 ii = ii + 1
142 line = string.replace (line, "%*",
143 string.join(args[1:], ' '))
144 args = string.split(line)
145 # split into ';' separated commands
146 # unless it's an alias command
147 if args[0] != 'alias':
148 semicolon = string.find(line, ';')
149 if semicolon >= 0:
150 # queue up everything after semicolon
151 next = string.lstrip(line[semicolon+1:])
152 self.cmdqueue.append(next)
153 line = string.rstrip(line[:semicolon])
154 return line
155
Guido van Rossum23efba41992-01-27 16:58:47 +0000156 # Command definitions, called by cmdloop()
157 # The argument is the remaining string on the command line
158 # Return true to exit from the command loop
Guido van Rossum921c8241992-01-10 14:54:42 +0000159
Guido van Rossum23efba41992-01-27 16:58:47 +0000160 do_h = cmd.Cmd.do_help
Guido van Rossumb6775db1994-08-01 11:34:53 +0000161
Guido van Rossum2424f851998-09-11 22:50:09 +0000162 def do_EOF(self, arg):
163 return 0 # Don't die on EOF
164
165 def do_break(self, arg, temporary = 0):
Guido van Rossumb5699c71998-07-20 23:13:54 +0000166 # break [ ([filename:]lineno | function) [, "condition"] ]
Guido van Rossum921c8241992-01-10 14:54:42 +0000167 if not arg:
Guido van Rossum2424f851998-09-11 22:50:09 +0000168 if self.breaks: # There's at least one
169 print "Num Type Disp Enb Where"
170 for bp in bdb.Breakpoint.bpbynumber:
171 if bp:
172 bp.bpprint()
Guido van Rossum921c8241992-01-10 14:54:42 +0000173 return
Guido van Rossumb5699c71998-07-20 23:13:54 +0000174 # parse arguments; comma has lowest precendence
175 # and cannot occur in filename
176 filename = None
177 lineno = None
178 cond = None
179 comma = string.find(arg, ',')
180 if comma > 0:
181 # parse stuff after comma: "condition"
182 cond = string.lstrip(arg[comma+1:])
183 arg = string.rstrip(arg[:comma])
Guido van Rossumb5699c71998-07-20 23:13:54 +0000184 # parse stuff before comma: [filename:]lineno | function
185 colon = string.rfind(arg, ':')
186 if colon >= 0:
187 filename = string.rstrip(arg[:colon])
Guido van Rossum2424f851998-09-11 22:50:09 +0000188 f = self.lookupmodule(filename)
189 if not f:
190 print '*** ', `filename`,
191 print 'not found from sys.path'
192 return
193 else:
194 filename = f
Guido van Rossumb5699c71998-07-20 23:13:54 +0000195 arg = string.lstrip(arg[colon+1:])
196 try:
197 lineno = int(arg)
198 except ValueError, msg:
199 print '*** Bad lineno:', arg
200 return
201 else:
202 # no colon; can be lineno or function
203 try:
204 lineno = int(arg)
205 except ValueError:
206 try:
207 func = eval(arg,
208 self.curframe.f_globals,
209 self.curframe.f_locals)
210 except:
Guido van Rossum2424f851998-09-11 22:50:09 +0000211 func = arg
Guido van Rossumb5699c71998-07-20 23:13:54 +0000212 try:
213 if hasattr(func, 'im_func'):
214 func = func.im_func
215 code = func.func_code
Guido van Rossum2424f851998-09-11 22:50:09 +0000216 lineno = code.co_firstlineno
Guido van Rossumb5699c71998-07-20 23:13:54 +0000217 filename = code.co_filename
Guido van Rossum2424f851998-09-11 22:50:09 +0000218 except:
219 # last thing to try
220 (ok, filename, ln) = self.lineinfo(arg)
221 if not ok:
222 print '*** The specified object',
223 print `arg`,
224 print 'is not a function'
225 print ('or was not found '
226 'along sys.path.')
227 return
228 lineno = int(ln)
Guido van Rossumb5699c71998-07-20 23:13:54 +0000229 if not filename:
Guido van Rossum2424f851998-09-11 22:50:09 +0000230 filename = self.defaultFile()
231 # Check for reasonable breakpoint
232 line = self.checkline(filename, lineno)
233 if line:
234 # now set the break point
235 err = self.set_break(filename, line, temporary, cond)
236 if err: print '***', err
237
238 # To be overridden in derived debuggers
239 def defaultFile(self):
240 # Produce a reasonable default
241 filename = self.curframe.f_code.co_filename
242 if filename == '<string>' and mainpyfile:
243 filename = mainpyfile
244 return filename
Guido van Rossum9e1ee971997-07-11 13:43:53 +0000245
Guido van Rossum921c8241992-01-10 14:54:42 +0000246 do_b = do_break
247
Guido van Rossum2424f851998-09-11 22:50:09 +0000248 def do_tbreak(self, arg):
249 self.do_break(arg, 1)
250
251 def lineinfo(self, identifier):
252 failed = (None, None, None)
253 # Input is identifier, may be in single quotes
254 idstring = string.split(identifier, "'")
255 if len(idstring) == 1:
256 # not in single quotes
257 id = string.strip(idstring[0])
258 elif len(idstring) == 3:
259 # quoted
260 id = string.strip(idstring[1])
261 else:
262 return failed
263 if id == '': return failed
264 parts = string.split(id, '.')
265 # Protection for derived debuggers
266 if parts[0] == 'self':
267 del parts[0]
268 if len(parts) == 0:
269 return failed
270 # Best first guess at file to look at
271 fname = self.defaultFile()
272 if len(parts) == 1:
273 item = parts[0]
274 else:
275 # More than one part.
276 # First is module, second is method/class
277 f = self.lookupmodule(parts[0])
278 if f:
279 fname = f
280 item = parts[1]
281 grepstring = self.lineinfoCmd % (item, fname)
282 answer = os.popen(grepstring, 'r').readline()
283 if answer:
284 f, line, junk = string.split(answer, ':', 2)
285 return(item, f,line)
286 else:
287 return failed
288
289 def checkline(self, filename, lineno):
290 """Return line number of first line at or after input
291 argument such that if the input points to a 'def', the
292 returned line number is the first
293 non-blank/non-comment line to follow. If the input
294 points to a blank or comment line, return 0. At end
295 of file, also return 0."""
296
297 line = linecache.getline(filename, lineno)
298 if not line:
299 print 'End of file'
300 return 0
301 line = string.strip(line)
302 # Don't allow setting breakpoint at a blank line
303 if ( not line or (line[0] == '#') or
304 (line[:3] == '"""') or line[:3] == "'''" ):
305 print '*** Blank or comment'
306 return 0
307 # When a file is read in and a breakpoint is at
308 # the 'def' statement, the system stops there at
309 # code parse time. We don't want that, so all breakpoints
310 # set at 'def' statements are moved one line onward
311 if line[:3] == 'def':
312 incomment = ''
313 while 1:
314 lineno = lineno+1
315 line = linecache.getline(filename, lineno)
316 if not line:
317 print 'end of file'
318 return 0
319 line = string.strip(line)
320 if incomment:
321 if len(line) < 3: continue
322 if (line[-3:] == incomment):
323 incomment = ''
324 continue
325 if not line: continue # Blank line
326 if len(line) >= 3:
327 if (line[:3] == '"""'
328 or line[:3] == "'''"):
329 incomment = line[:3]
330 continue
331 if line[0] != '#': break
332 return lineno
333
334 def do_enable(self, arg):
335 args = string.split(arg)
336 for i in args:
337 bp = bdb.Breakpoint.bpbynumber[int(i)]
338 if bp:
339 bp.enable()
340
341 def do_disable(self, arg):
342 args = string.split(arg)
343 for i in args:
344 bp = bdb.Breakpoint.bpbynumber[int(i)]
345 if bp:
346 bp.disable()
347
348 def do_condition(self, arg):
349 # arg is breakpoint number and condition
350 args = string.split(arg, ' ', 1)
351 bpnum = int(string.strip(args[0]))
352 try:
353 cond = args[1]
354 except:
355 cond = None
356 bp = bdb.Breakpoint.bpbynumber[bpnum]
357 if bp:
358 bp.cond = cond
359 if not cond:
360 print 'Breakpoint', bpnum,
361 print 'is now unconditional.'
362
363 def do_ignore(self,arg):
364 # arg is bp number followed by ignore count
365 args = string.split(arg)
366 bpnum = int(string.strip(args[0]))
367 try:
368 count = int(string.strip(args[1]))
369 except:
370 count = 0
371 bp = bdb.Breakpoint.bpbynumber[bpnum]
372 if bp:
373 bp.ignore = count
374 if (count > 0):
375 reply = 'Will ignore next '
376 if (count > 1):
377 reply = reply + '%d crossings' % count
378 else:
379 reply = reply + '1 crossing'
380 print reply + ' of breakpoint %d.' % bpnum
381 else:
382 print 'Will stop next time breakpoint',
383 print bpnum, 'is reached.'
384
Guido van Rossum921c8241992-01-10 14:54:42 +0000385 def do_clear(self, arg):
386 if not arg:
Guido van Rossumb9142571992-01-12 23:32:55 +0000387 try:
388 reply = raw_input('Clear all breaks? ')
389 except EOFError:
390 reply = 'no'
391 reply = string.lower(string.strip(reply))
392 if reply in ('y', 'yes'):
Guido van Rossum23efba41992-01-27 16:58:47 +0000393 self.clear_all_breaks()
Guido van Rossum921c8241992-01-10 14:54:42 +0000394 return
Guido van Rossum2424f851998-09-11 22:50:09 +0000395 numberlist = string.split(arg)
396 for i in numberlist:
397 err = self.clear_break(i)
398 if err:
399 print '***'+err
400 else:
401 print 'Deleted breakpoint %s ' % (i,)
Guido van Rossumb9142571992-01-12 23:32:55 +0000402 do_cl = do_clear # 'c' is already an abbreviation for 'continue'
Guido van Rossum921c8241992-01-10 14:54:42 +0000403
404 def do_where(self, arg):
Guido van Rossum23efba41992-01-27 16:58:47 +0000405 self.print_stack_trace()
Guido van Rossum921c8241992-01-10 14:54:42 +0000406 do_w = do_where
407
408 def do_up(self, arg):
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000409 if self.curindex == 0:
410 print '*** Oldest frame'
Guido van Rossum921c8241992-01-10 14:54:42 +0000411 else:
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000412 self.curindex = self.curindex - 1
413 self.curframe = self.stack[self.curindex][0]
Guido van Rossum23efba41992-01-27 16:58:47 +0000414 self.print_stack_entry(self.stack[self.curindex])
Guido van Rossumc629d341992-11-05 10:43:02 +0000415 self.lineno = None
Guido van Rossumb9142571992-01-12 23:32:55 +0000416 do_u = do_up
417
418 def do_down(self, arg):
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000419 if self.curindex + 1 == len(self.stack):
420 print '*** Newest frame'
Guido van Rossumb9142571992-01-12 23:32:55 +0000421 else:
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000422 self.curindex = self.curindex + 1
423 self.curframe = self.stack[self.curindex][0]
Guido van Rossum23efba41992-01-27 16:58:47 +0000424 self.print_stack_entry(self.stack[self.curindex])
Guido van Rossumc629d341992-11-05 10:43:02 +0000425 self.lineno = None
Guido van Rossum921c8241992-01-10 14:54:42 +0000426 do_d = do_down
427
428 def do_step(self, arg):
Guido van Rossum23efba41992-01-27 16:58:47 +0000429 self.set_step()
Guido van Rossumb9142571992-01-12 23:32:55 +0000430 return 1
Guido van Rossum921c8241992-01-10 14:54:42 +0000431 do_s = do_step
432
433 def do_next(self, arg):
Guido van Rossum23efba41992-01-27 16:58:47 +0000434 self.set_next(self.curframe)
Guido van Rossumb9142571992-01-12 23:32:55 +0000435 return 1
Guido van Rossum921c8241992-01-10 14:54:42 +0000436 do_n = do_next
437
Guido van Rossumb9142571992-01-12 23:32:55 +0000438 def do_return(self, arg):
Guido van Rossum23efba41992-01-27 16:58:47 +0000439 self.set_return(self.curframe)
Guido van Rossumb9142571992-01-12 23:32:55 +0000440 return 1
441 do_r = do_return
442
Guido van Rossum921c8241992-01-10 14:54:42 +0000443 def do_continue(self, arg):
Guido van Rossum23efba41992-01-27 16:58:47 +0000444 self.set_continue()
Guido van Rossumb9142571992-01-12 23:32:55 +0000445 return 1
Guido van Rossum921c8241992-01-10 14:54:42 +0000446 do_c = do_cont = do_continue
447
448 def do_quit(self, arg):
Guido van Rossum23efba41992-01-27 16:58:47 +0000449 self.set_quit()
450 return 1
Guido van Rossum921c8241992-01-10 14:54:42 +0000451 do_q = do_quit
452
Guido van Rossum23efba41992-01-27 16:58:47 +0000453 def do_args(self, arg):
Guido van Rossum46c86bb1998-02-25 20:50:32 +0000454 f = self.curframe
455 co = f.f_code
456 dict = f.f_locals
457 n = co.co_argcount
458 if co.co_flags & 4: n = n+1
459 if co.co_flags & 8: n = n+1
460 for i in range(n):
461 name = co.co_varnames[i]
462 print name, '=',
463 if dict.has_key(name): print dict[name]
464 else: print "*** undefined ***"
Guido van Rossum23efba41992-01-27 16:58:47 +0000465 do_a = do_args
466
467 def do_retval(self, arg):
468 if self.curframe.f_locals.has_key('__return__'):
469 print self.curframe.f_locals['__return__']
470 else:
471 print '*** Not yet returned!'
472 do_rv = do_retval
473
474 def do_p(self, arg):
475 try:
Guido van Rossum2424f851998-09-11 22:50:09 +0000476 value = eval(arg, self.curframe.f_globals,
Guido van Rossum23efba41992-01-27 16:58:47 +0000477 self.curframe.f_locals)
478 except:
Guido van Rossumf15d1591997-09-29 23:22:12 +0000479 t, v = sys.exc_info()[:2]
480 if type(t) == type(''):
481 exc_type_name = t
482 else: exc_type_name = t.__name__
483 print '***', exc_type_name + ':', `v`
Guido van Rossum23efba41992-01-27 16:58:47 +0000484 return
Guido van Rossum8e2ec561993-07-29 09:37:38 +0000485
Guido van Rossum23efba41992-01-27 16:58:47 +0000486 print `value`
487
Guido van Rossum921c8241992-01-10 14:54:42 +0000488 def do_list(self, arg):
Guido van Rossumb9142571992-01-12 23:32:55 +0000489 self.lastcmd = 'list'
Guido van Rossum921c8241992-01-10 14:54:42 +0000490 last = None
491 if arg:
492 try:
493 x = eval(arg, {}, {})
494 if type(x) == type(()):
495 first, last = x
496 first = int(first)
497 last = int(last)
498 if last < first:
499 # Assume it's a count
500 last = first + last
501 else:
Guido van Rossumc629d341992-11-05 10:43:02 +0000502 first = max(1, int(x) - 5)
Guido van Rossum921c8241992-01-10 14:54:42 +0000503 except:
504 print '*** Error in argument:', `arg`
505 return
506 elif self.lineno is None:
507 first = max(1, self.curframe.f_lineno - 5)
508 else:
509 first = self.lineno + 1
Guido van Rossumc629d341992-11-05 10:43:02 +0000510 if last == None:
Guido van Rossum921c8241992-01-10 14:54:42 +0000511 last = first + 10
512 filename = self.curframe.f_code.co_filename
Guido van Rossum23efba41992-01-27 16:58:47 +0000513 breaklist = self.get_file_breaks(filename)
Guido van Rossum921c8241992-01-10 14:54:42 +0000514 try:
515 for lineno in range(first, last+1):
516 line = linecache.getline(filename, lineno)
517 if not line:
518 print '[EOF]'
519 break
520 else:
521 s = string.rjust(`lineno`, 3)
522 if len(s) < 4: s = s + ' '
523 if lineno in breaklist: s = s + 'B'
524 else: s = s + ' '
525 if lineno == self.curframe.f_lineno:
526 s = s + '->'
527 print s + '\t' + line,
528 self.lineno = lineno
529 except KeyboardInterrupt:
530 pass
531 do_l = do_list
Guido van Rossum00230781993-03-29 11:39:45 +0000532
533 def do_whatis(self, arg):
Guido van Rossum00230781993-03-29 11:39:45 +0000534 try:
Guido van Rossum2424f851998-09-11 22:50:09 +0000535 value = eval(arg, self.curframe.f_globals,
Guido van Rossum00230781993-03-29 11:39:45 +0000536 self.curframe.f_locals)
537 except:
Guido van Rossumf15d1591997-09-29 23:22:12 +0000538 t, v = sys.exc_info()[:2]
539 if type(t) == type(''):
540 exc_type_name = t
541 else: exc_type_name = t.__name__
542 print '***', exc_type_name + ':', `v`
Guido van Rossum00230781993-03-29 11:39:45 +0000543 return
544 code = None
545 # Is it a function?
546 try: code = value.func_code
547 except: pass
548 if code:
Guido van Rossumb6775db1994-08-01 11:34:53 +0000549 print 'Function', code.co_name
Guido van Rossum00230781993-03-29 11:39:45 +0000550 return
551 # Is it an instance method?
552 try: code = value.im_func.func_code
553 except: pass
554 if code:
Guido van Rossumb6775db1994-08-01 11:34:53 +0000555 print 'Method', code.co_name
Guido van Rossum00230781993-03-29 11:39:45 +0000556 return
557 # None of the above...
558 print type(value)
Guido van Rossum2424f851998-09-11 22:50:09 +0000559
560 def do_alias(self, arg):
561 args = string.split (arg)
562 if len(args) == 0:
563 keys = self.aliases.keys()
564 keys.sort()
565 for alias in keys:
566 print "%s = %s" % (alias, self.aliases[alias])
567 return
568 if self.aliases.has_key(args[0]) and len (args) == 1:
569 print "%s = %s" % (args[0], self.aliases[args[0]])
570 else:
571 self.aliases[args[0]] = string.join(args[1:], ' ')
572
573 def do_unalias(self, arg):
574 args = string.split (arg)
575 if len(args) == 0: return
576 if self.aliases.has_key(args[0]):
577 del self.aliases[args[0]]
578
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000579 # Print a traceback starting at the top stack frame.
Guido van Rossum23efba41992-01-27 16:58:47 +0000580 # The most recently entered frame is printed last;
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000581 # this is different from dbx and gdb, but consistent with
582 # the Python interpreter's stack trace.
583 # It is also consistent with the up/down commands (which are
584 # compatible with dbx and gdb: up moves towards 'main()'
585 # and down moves towards the most recent stack frame).
Guido van Rossum921c8241992-01-10 14:54:42 +0000586
Guido van Rossum23efba41992-01-27 16:58:47 +0000587 def print_stack_trace(self):
588 try:
589 for frame_lineno in self.stack:
590 self.print_stack_entry(frame_lineno)
591 except KeyboardInterrupt:
592 pass
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000593
Guido van Rossumb6aa92e1995-02-03 12:50:04 +0000594 def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix):
Guido van Rossum23efba41992-01-27 16:58:47 +0000595 frame, lineno = frame_lineno
596 if frame is self.curframe:
597 print '>',
598 else:
599 print ' ',
Guido van Rossuma558e371994-11-10 22:27:35 +0000600 print self.format_stack_entry(frame_lineno, prompt_prefix)
Guido van Rossum921c8241992-01-10 14:54:42 +0000601
602
Guido van Rossumb6775db1994-08-01 11:34:53 +0000603 # Help methods (derived from pdb.doc)
604
605 def help_help(self):
606 self.help_h()
607
608 def help_h(self):
609 print """h(elp)
610 Without argument, print the list of available commands.
611 With a command name as argument, print help about that command
612 "help pdb" pipes the full documentation file to the $PAGER
613 "help exec" gives help on the ! command"""
614
615 def help_where(self):
616 self.help_w()
617
618 def help_w(self):
619 print """w(here)
620 Print a stack trace, with the most recent frame at the bottom.
621 An arrow indicates the "current frame", which determines the
622 context of most commands."""
623
624 def help_down(self):
625 self.help_d()
626
627 def help_d(self):
628 print """d(own)
629 Move the current frame one level down in the stack trace
630 (to an older frame)."""
631
632 def help_up(self):
633 self.help_u()
634
635 def help_u(self):
636 print """u(p)
637 Move the current frame one level up in the stack trace
638 (to a newer frame)."""
639
640 def help_break(self):
641 self.help_b()
642
643 def help_b(self):
Guido van Rossumb5699c71998-07-20 23:13:54 +0000644 print """b(reak) ([file:]lineno | function) [, "condition"]
Guido van Rossumb6775db1994-08-01 11:34:53 +0000645 With a line number argument, set a break there in the current
Guido van Rossum2424f851998-09-11 22:50:09 +0000646 file. With a function name, set a break at first executable line
647 of that function. Without argument, list all breaks. If a second
Guido van Rossum9e1ee971997-07-11 13:43:53 +0000648 argument is present, it is a string specifying an expression
649 which must evaluate to true before the breakpoint is honored.
Guido van Rossumb5699c71998-07-20 23:13:54 +0000650
651 The line number may be prefixed with a filename and a colon,
652 to specify a breakpoint in another file (probably one that
Guido van Rossum2424f851998-09-11 22:50:09 +0000653 hasn't been loaded yet). The file is searched for on sys.path;
Guido van Rossum1f00eed1998-07-22 13:35:21 +0000654 the .py suffix may be omitted."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000655
656 def help_clear(self):
657 self.help_cl()
658
659 def help_cl(self):
Guido van Rossum2424f851998-09-11 22:50:09 +0000660 print """cl(ear) [bpnumber [bpnumber...]]
661 With a space separated list of breakpoint numbers, clear
662 those breakpoints. Without argument, clear all breaks (but
663 first ask confirmation).
Guido van Rossumb5699c71998-07-20 23:13:54 +0000664
Guido van Rossum2424f851998-09-11 22:50:09 +0000665 Note that the argument is different from previous versions of
666 the debugger (in python distributions 1.5.1 and before) where
667 a linenumber was used instead of breakpoint numbers."""
668
669 def help_tbreak(self):
670 print """tbreak same arguments as break, but breakpoint is
671 removed when first hit."""
672
673 def help_enable(self):
674 print """enable bpnumber [bpnumber ...]
675 Enables the breakpoints given as a space separated list of
676 bp numbers."""
677
678 def help_disable(self):
679 print """disable bpnumber [bpnumber ...]
680 Disables the breakpoints given as a space separated list of
681 bp numbers."""
682
683 def help_ignore(self):
684 print """ignore bpnumber count
685 Sets the ignore count for the given breakpoint number. A breakpoint
686 becomes active when the ignore count is zero. When non-zero, the
687 count is decremented each time the breakpoint is reached and the
688 breakpoint is not disabled and any associated condition evaluates
689 to true."""
690
691 def help_condition(self):
692 print """condition bpnumber str_condition
693 str_condition is a string specifying an expression which
694 must evaluate to true before the breakpoint is honored.
695 If str_condition is absent, any existing condition is removed;
696 i.e., the breakpoint is made unconditional."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000697
698 def help_step(self):
699 self.help_s()
700
701 def help_s(self):
702 print """s(tep)
703 Execute the current line, stop at the first possible occasion
704 (either in a function that is called or in the current function)."""
705
706 def help_next(self):
707 self.help_n()
708
709 def help_n(self):
710 print """n(ext)
711 Continue execution until the next line in the current function
712 is reached or it returns."""
713
714 def help_return(self):
715 self.help_r()
716
717 def help_r(self):
718 print """r(eturn)
719 Continue execution until the current function returns."""
720
721 def help_continue(self):
722 self.help_c()
723
724 def help_cont(self):
725 self.help_c()
726
727 def help_c(self):
728 print """c(ont(inue))
729 Continue execution, only stop when a breakpoint is encountered."""
730
731 def help_list(self):
732 self.help_l()
733
734 def help_l(self):
735 print """l(ist) [first [,last]]
736 List source code for the current file.
737 Without arguments, list 11 lines around the current line
738 or continue the previous listing.
739 With one argument, list 11 lines starting at that line.
740 With two arguments, list the given range;
741 if the second argument is less than the first, it is a count."""
742
743 def help_args(self):
744 self.help_a()
745
746 def help_a(self):
747 print """a(rgs)
Guido van Rossum46c86bb1998-02-25 20:50:32 +0000748 Print the arguments of the current function."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000749
750 def help_p(self):
751 print """p expression
752 Print the value of the expression."""
753
754 def help_exec(self):
755 print """(!) statement
756 Execute the (one-line) statement in the context of
757 the current stack frame.
758 The exclamation point can be omitted unless the first word
759 of the statement resembles a debugger command.
760 To assign to a global variable you must always prefix the
761 command with a 'global' command, e.g.:
762 (Pdb) global list_options; list_options = ['-l']
763 (Pdb)"""
764
765 def help_quit(self):
766 self.help_q()
767
768 def help_q(self):
769 print """q(uit) Quit from the debugger.
770 The program being executed is aborted."""
771
Guido van Rossum2424f851998-09-11 22:50:09 +0000772 def help_whatis(self):
773 print """whatis arg
774 Prints the type of the argument."""
775
776 def help_EOF(self):
777 print """EOF
778 Handles the receipt of EOF as a command."""
779
780 def help_alias(self):
781 print """alias [name [command [parameter parameter ...] ]]
782 Creates an alias called 'name' the executes 'command'. The command
783 must *not* be enclosed in quotes. Replaceable parameters are
784 indicated by %1, %2, and so on, while %* is replaced by all the
785 parameters. If no command is given, the current alias for name
786 is shown. If no name is given, all aliases are listed.
787
788 Aliases may be nested and can contain anything that can be
789 legally typed at the pdb prompt. Note! You *can* override
790 internal pdb commands with aliases! Those internal commands
791 are then hidden until the alias is removed. Aliasing is recursively
792 applied to the first word of the command line; all other words
793 in the line are left alone.
794
795 Some useful aliases (especially when placed in the .pdbrc file) are:
796
797 #Print instance variables (usage "pi classInst")
798 alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
799
800 #Print instance variables in self
801 alias ps pi self
802 """
803
804 def help_unalias(self):
805 print """unalias name
806 Deletes the specified alias."""
807
Guido van Rossumb6775db1994-08-01 11:34:53 +0000808 def help_pdb(self):
809 help()
810
Guido van Rossumb5699c71998-07-20 23:13:54 +0000811 # Helper function for break/clear parsing -- may be overridden
812
813 def lookupmodule(self, filename):
Guido van Rossum1f00eed1998-07-22 13:35:21 +0000814 root, ext = os.path.splitext(filename)
815 if ext == '':
816 filename = filename + '.py'
817 if os.path.isabs(filename):
818 return filename
Guido van Rossumb5699c71998-07-20 23:13:54 +0000819 for dirname in sys.path:
Guido van Rossum2424f851998-09-11 22:50:09 +0000820 while os.path.islink(dirname):
821 dirname = os.readlink(dirname)
Guido van Rossumb5699c71998-07-20 23:13:54 +0000822 fullname = os.path.join(dirname, filename)
823 if os.path.exists(fullname):
824 return fullname
Guido van Rossum2424f851998-09-11 22:50:09 +0000825 return None
Guido van Rossumb5699c71998-07-20 23:13:54 +0000826
Guido van Rossum35771131992-09-08 11:59:04 +0000827# Simplified interface
828
Guido van Rossum5e38b6f1995-02-27 13:13:40 +0000829def run(statement, globals=None, locals=None):
830 Pdb().run(statement, globals, locals)
831
832def runeval(expression, globals=None, locals=None):
833 return Pdb().runeval(expression, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000834
835def runctx(statement, globals, locals):
Guido van Rossum5e38b6f1995-02-27 13:13:40 +0000836 # B/W compatibility
837 run(statement, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000838
Guido van Rossum4e160981992-09-02 20:43:20 +0000839def runcall(*args):
Guido van Rossum5e38b6f1995-02-27 13:13:40 +0000840 return apply(Pdb().runcall, args)
Guido van Rossum4e160981992-09-02 20:43:20 +0000841
Guido van Rossumb6775db1994-08-01 11:34:53 +0000842def set_trace():
843 Pdb().set_trace()
Guido van Rossum35771131992-09-08 11:59:04 +0000844
845# Post-Mortem interface
846
847def post_mortem(t):
Guido van Rossum5ef74b81993-06-23 11:55:24 +0000848 p = Pdb()
Guido van Rossum35771131992-09-08 11:59:04 +0000849 p.reset()
850 while t.tb_next <> None: t = t.tb_next
851 p.interaction(t.tb_frame, t)
852
853def pm():
Guido van Rossum35771131992-09-08 11:59:04 +0000854 post_mortem(sys.last_traceback)
855
856
857# Main program for testing
858
Guido van Rossum23efba41992-01-27 16:58:47 +0000859TESTCMD = 'import x; x.main()'
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000860
Guido van Rossum921c8241992-01-10 14:54:42 +0000861def test():
Guido van Rossum23efba41992-01-27 16:58:47 +0000862 run(TESTCMD)
Guido van Rossume61fa0a1993-10-22 13:56:35 +0000863
864# print help
865def help():
866 for dirname in sys.path:
867 fullname = os.path.join(dirname, 'pdb.doc')
868 if os.path.exists(fullname):
869 sts = os.system('${PAGER-more} '+fullname)
870 if sts: print '*** Pager exit status:', sts
871 break
872 else:
873 print 'Sorry, can\'t find the help file "pdb.doc"',
874 print 'along the Python search path'
Guido van Rossumf17361d1996-07-30 16:28:13 +0000875
Guido van Rossumb5699c71998-07-20 23:13:54 +0000876mainmodule = ''
877mainpyfile = ''
878
Guido van Rossumf17361d1996-07-30 16:28:13 +0000879# When invoked as main program, invoke the debugger on a script
880if __name__=='__main__':
Guido van Rossumb5699c71998-07-20 23:13:54 +0000881 global mainmodule, mainpyfile
Guido van Rossumf17361d1996-07-30 16:28:13 +0000882 if not sys.argv[1:]:
883 print "usage: pdb.py scriptfile [arg] ..."
884 sys.exit(2)
885
Guido van Rossumb5699c71998-07-20 23:13:54 +0000886 mainpyfile = filename = sys.argv[1] # Get script filename
887 if not os.path.exists(filename):
888 print 'Error:', `filename`, 'does not exist'
889 sys.exit(1)
890 mainmodule = os.path.basename(filename)
Guido van Rossumec577d51996-09-10 17:39:34 +0000891 del sys.argv[0] # Hide "pdb.py" from argument list
892
893 # Insert script directory in front of module search path
894 sys.path.insert(0, os.path.dirname(filename))
Guido van Rossumf17361d1996-07-30 16:28:13 +0000895
896 run('execfile(' + `filename` + ')', {'__name__': '__main__'})