blob: 87eac0e4681dbd6e651bbff05e278ab1f74f1f35 [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 Rossum3a98e781998-09-17 15:00:30 +000072 self.execRcLines()
Guido van Rossum2424f851998-09-11 22:50:09 +000073
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):
Guido van Rossum3a98e781998-09-17 15:00:30 +0000131 # Handle alias expansion and ';;' separator
Guido van Rossum2424f851998-09-11 22:50:09 +0000132 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
Guido van Rossum3a98e781998-09-17 15:00:30 +0000142 line = string.replace(line, "%*",
143 string.join(args[1:], ' '))
Guido van Rossum2424f851998-09-11 22:50:09 +0000144 args = string.split(line)
Guido van Rossum3a98e781998-09-17 15:00:30 +0000145 # split into ';;' separated commands
Guido van Rossum2424f851998-09-11 22:50:09 +0000146 # unless it's an alias command
147 if args[0] != 'alias':
Guido van Rossum3a98e781998-09-17 15:00:30 +0000148 marker = string.find(line, ';;')
149 if marker >= 0:
150 # queue up everything after marker
151 next = string.lstrip(line[marker+2:])
Guido van Rossum2424f851998-09-11 22:50:09 +0000152 self.cmdqueue.append(next)
Guido van Rossum3a98e781998-09-17 15:00:30 +0000153 line = string.rstrip(line[:marker])
Guido van Rossum2424f851998-09-11 22:50:09 +0000154 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
Guido van Rossum816a9fb1999-01-25 20:56:07 +0000237 else:
238 bp = self.get_breaks(filename, line)[-1]
239 print "Breakpoint %d at %s:%d" % (bp.number,
240 bp.file,
241 bp.line)
Guido van Rossum2424f851998-09-11 22:50:09 +0000242
243 # To be overridden in derived debuggers
244 def defaultFile(self):
245 # Produce a reasonable default
246 filename = self.curframe.f_code.co_filename
247 if filename == '<string>' and mainpyfile:
248 filename = mainpyfile
249 return filename
Guido van Rossum9e1ee971997-07-11 13:43:53 +0000250
Guido van Rossum921c8241992-01-10 14:54:42 +0000251 do_b = do_break
252
Guido van Rossum2424f851998-09-11 22:50:09 +0000253 def do_tbreak(self, arg):
254 self.do_break(arg, 1)
255
256 def lineinfo(self, identifier):
257 failed = (None, None, None)
258 # Input is identifier, may be in single quotes
259 idstring = string.split(identifier, "'")
260 if len(idstring) == 1:
261 # not in single quotes
262 id = string.strip(idstring[0])
263 elif len(idstring) == 3:
264 # quoted
265 id = string.strip(idstring[1])
266 else:
267 return failed
268 if id == '': return failed
269 parts = string.split(id, '.')
270 # Protection for derived debuggers
271 if parts[0] == 'self':
272 del parts[0]
273 if len(parts) == 0:
274 return failed
275 # Best first guess at file to look at
276 fname = self.defaultFile()
277 if len(parts) == 1:
278 item = parts[0]
279 else:
280 # More than one part.
281 # First is module, second is method/class
282 f = self.lookupmodule(parts[0])
283 if f:
284 fname = f
285 item = parts[1]
286 grepstring = self.lineinfoCmd % (item, fname)
287 answer = os.popen(grepstring, 'r').readline()
288 if answer:
289 f, line, junk = string.split(answer, ':', 2)
290 return(item, f,line)
291 else:
292 return failed
293
294 def checkline(self, filename, lineno):
295 """Return line number of first line at or after input
296 argument such that if the input points to a 'def', the
297 returned line number is the first
298 non-blank/non-comment line to follow. If the input
299 points to a blank or comment line, return 0. At end
300 of file, also return 0."""
301
302 line = linecache.getline(filename, lineno)
303 if not line:
304 print 'End of file'
305 return 0
306 line = string.strip(line)
307 # Don't allow setting breakpoint at a blank line
308 if ( not line or (line[0] == '#') or
309 (line[:3] == '"""') or line[:3] == "'''" ):
310 print '*** Blank or comment'
311 return 0
312 # When a file is read in and a breakpoint is at
313 # the 'def' statement, the system stops there at
314 # code parse time. We don't want that, so all breakpoints
315 # set at 'def' statements are moved one line onward
316 if line[:3] == 'def':
317 incomment = ''
318 while 1:
319 lineno = lineno+1
320 line = linecache.getline(filename, lineno)
321 if not line:
322 print 'end of file'
323 return 0
324 line = string.strip(line)
325 if incomment:
326 if len(line) < 3: continue
327 if (line[-3:] == incomment):
328 incomment = ''
329 continue
330 if not line: continue # Blank line
331 if len(line) >= 3:
332 if (line[:3] == '"""'
333 or line[:3] == "'''"):
334 incomment = line[:3]
335 continue
336 if line[0] != '#': break
337 return lineno
338
339 def do_enable(self, arg):
340 args = string.split(arg)
341 for i in args:
342 bp = bdb.Breakpoint.bpbynumber[int(i)]
343 if bp:
344 bp.enable()
345
346 def do_disable(self, arg):
347 args = string.split(arg)
348 for i in args:
349 bp = bdb.Breakpoint.bpbynumber[int(i)]
350 if bp:
351 bp.disable()
352
353 def do_condition(self, arg):
354 # arg is breakpoint number and condition
355 args = string.split(arg, ' ', 1)
356 bpnum = int(string.strip(args[0]))
357 try:
358 cond = args[1]
359 except:
360 cond = None
361 bp = bdb.Breakpoint.bpbynumber[bpnum]
362 if bp:
363 bp.cond = cond
364 if not cond:
365 print 'Breakpoint', bpnum,
366 print 'is now unconditional.'
367
368 def do_ignore(self,arg):
369 # arg is bp number followed by ignore count
370 args = string.split(arg)
371 bpnum = int(string.strip(args[0]))
372 try:
373 count = int(string.strip(args[1]))
374 except:
375 count = 0
376 bp = bdb.Breakpoint.bpbynumber[bpnum]
377 if bp:
378 bp.ignore = count
379 if (count > 0):
380 reply = 'Will ignore next '
381 if (count > 1):
382 reply = reply + '%d crossings' % count
383 else:
384 reply = reply + '1 crossing'
385 print reply + ' of breakpoint %d.' % bpnum
386 else:
387 print 'Will stop next time breakpoint',
388 print bpnum, 'is reached.'
389
Guido van Rossum921c8241992-01-10 14:54:42 +0000390 def do_clear(self, arg):
Guido van Rossum816a9fb1999-01-25 20:56:07 +0000391 # Three possibilities, tried in this order:
392 # clear -> clear all breaks, ask for confirmation
393 # clear file:lineno -> clear all breaks at file:lineno
394 # clear bpno bpno ... -> clear breakpoints by number
Guido van Rossum921c8241992-01-10 14:54:42 +0000395 if not arg:
Guido van Rossumb9142571992-01-12 23:32:55 +0000396 try:
397 reply = raw_input('Clear all breaks? ')
398 except EOFError:
399 reply = 'no'
400 reply = string.lower(string.strip(reply))
401 if reply in ('y', 'yes'):
Guido van Rossum23efba41992-01-27 16:58:47 +0000402 self.clear_all_breaks()
Guido van Rossum921c8241992-01-10 14:54:42 +0000403 return
Guido van Rossum816a9fb1999-01-25 20:56:07 +0000404 if ':' in arg:
405 # Make sure it works for "clear C:\foo\bar.py:12"
406 i = string.rfind(arg, ':')
407 filename = arg[:i]
408 arg = arg[i+1:]
409 try:
410 lineno = int(arg)
411 except:
412 err = "Invalid line number (%s)" % arg
413 else:
414 err = self.clear_break(filename, lineno)
415 if err: print '***', err
416 return
Guido van Rossum2424f851998-09-11 22:50:09 +0000417 numberlist = string.split(arg)
418 for i in numberlist:
Guido van Rossum816a9fb1999-01-25 20:56:07 +0000419 err = self.clear_bpbynumber(i)
Guido van Rossum2424f851998-09-11 22:50:09 +0000420 if err:
Guido van Rossum816a9fb1999-01-25 20:56:07 +0000421 print '***', err
Guido van Rossum2424f851998-09-11 22:50:09 +0000422 else:
423 print 'Deleted breakpoint %s ' % (i,)
Guido van Rossumb9142571992-01-12 23:32:55 +0000424 do_cl = do_clear # 'c' is already an abbreviation for 'continue'
Guido van Rossum816a9fb1999-01-25 20:56:07 +0000425
426 def do_clear_break(self, arg):
427 if not arg:
428 self.do_clear("")
429 return
430 arg = string.strip(arg)
431 # First arg is file, second is line, ignore anything else
432 args = string.split(arg)
433 if len(args) < 2:
434 print '*** Specify file and line number.'
435 return
436 try:
437 line = int(args[1])
438 except:
439 print '*** line number must be an integer.'
440 return
441 result =self.clear_break(args[0], line)
442 if result:
443 print result
444 do_clb = do_clear_break
Guido van Rossum921c8241992-01-10 14:54:42 +0000445
446 def do_where(self, arg):
Guido van Rossum23efba41992-01-27 16:58:47 +0000447 self.print_stack_trace()
Guido van Rossum921c8241992-01-10 14:54:42 +0000448 do_w = do_where
449
450 def do_up(self, arg):
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000451 if self.curindex == 0:
452 print '*** Oldest frame'
Guido van Rossum921c8241992-01-10 14:54:42 +0000453 else:
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000454 self.curindex = self.curindex - 1
455 self.curframe = self.stack[self.curindex][0]
Guido van Rossum23efba41992-01-27 16:58:47 +0000456 self.print_stack_entry(self.stack[self.curindex])
Guido van Rossumc629d341992-11-05 10:43:02 +0000457 self.lineno = None
Guido van Rossumb9142571992-01-12 23:32:55 +0000458 do_u = do_up
459
460 def do_down(self, arg):
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000461 if self.curindex + 1 == len(self.stack):
462 print '*** Newest frame'
Guido van Rossumb9142571992-01-12 23:32:55 +0000463 else:
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000464 self.curindex = self.curindex + 1
465 self.curframe = self.stack[self.curindex][0]
Guido van Rossum23efba41992-01-27 16:58:47 +0000466 self.print_stack_entry(self.stack[self.curindex])
Guido van Rossumc629d341992-11-05 10:43:02 +0000467 self.lineno = None
Guido van Rossum921c8241992-01-10 14:54:42 +0000468 do_d = do_down
469
470 def do_step(self, arg):
Guido van Rossum23efba41992-01-27 16:58:47 +0000471 self.set_step()
Guido van Rossumb9142571992-01-12 23:32:55 +0000472 return 1
Guido van Rossum921c8241992-01-10 14:54:42 +0000473 do_s = do_step
474
475 def do_next(self, arg):
Guido van Rossum23efba41992-01-27 16:58:47 +0000476 self.set_next(self.curframe)
Guido van Rossumb9142571992-01-12 23:32:55 +0000477 return 1
Guido van Rossum921c8241992-01-10 14:54:42 +0000478 do_n = do_next
479
Guido van Rossumb9142571992-01-12 23:32:55 +0000480 def do_return(self, arg):
Guido van Rossum23efba41992-01-27 16:58:47 +0000481 self.set_return(self.curframe)
Guido van Rossumb9142571992-01-12 23:32:55 +0000482 return 1
483 do_r = do_return
484
Guido van Rossum921c8241992-01-10 14:54:42 +0000485 def do_continue(self, arg):
Guido van Rossum23efba41992-01-27 16:58:47 +0000486 self.set_continue()
Guido van Rossumb9142571992-01-12 23:32:55 +0000487 return 1
Guido van Rossum921c8241992-01-10 14:54:42 +0000488 do_c = do_cont = do_continue
489
490 def do_quit(self, arg):
Guido van Rossum23efba41992-01-27 16:58:47 +0000491 self.set_quit()
492 return 1
Guido van Rossum921c8241992-01-10 14:54:42 +0000493 do_q = do_quit
494
Guido van Rossum23efba41992-01-27 16:58:47 +0000495 def do_args(self, arg):
Guido van Rossum46c86bb1998-02-25 20:50:32 +0000496 f = self.curframe
497 co = f.f_code
498 dict = f.f_locals
499 n = co.co_argcount
500 if co.co_flags & 4: n = n+1
501 if co.co_flags & 8: n = n+1
502 for i in range(n):
503 name = co.co_varnames[i]
504 print name, '=',
505 if dict.has_key(name): print dict[name]
506 else: print "*** undefined ***"
Guido van Rossum23efba41992-01-27 16:58:47 +0000507 do_a = do_args
508
509 def do_retval(self, arg):
510 if self.curframe.f_locals.has_key('__return__'):
511 print self.curframe.f_locals['__return__']
512 else:
513 print '*** Not yet returned!'
514 do_rv = do_retval
515
516 def do_p(self, arg):
517 try:
Guido van Rossum2424f851998-09-11 22:50:09 +0000518 value = eval(arg, self.curframe.f_globals,
Guido van Rossum23efba41992-01-27 16:58:47 +0000519 self.curframe.f_locals)
520 except:
Guido van Rossumf15d1591997-09-29 23:22:12 +0000521 t, v = sys.exc_info()[:2]
522 if type(t) == type(''):
523 exc_type_name = t
524 else: exc_type_name = t.__name__
525 print '***', exc_type_name + ':', `v`
Guido van Rossum23efba41992-01-27 16:58:47 +0000526 return
Guido van Rossum8e2ec561993-07-29 09:37:38 +0000527
Guido van Rossum23efba41992-01-27 16:58:47 +0000528 print `value`
529
Guido van Rossum921c8241992-01-10 14:54:42 +0000530 def do_list(self, arg):
Guido van Rossumb9142571992-01-12 23:32:55 +0000531 self.lastcmd = 'list'
Guido van Rossum921c8241992-01-10 14:54:42 +0000532 last = None
533 if arg:
534 try:
535 x = eval(arg, {}, {})
536 if type(x) == type(()):
537 first, last = x
538 first = int(first)
539 last = int(last)
540 if last < first:
541 # Assume it's a count
542 last = first + last
543 else:
Guido van Rossumc629d341992-11-05 10:43:02 +0000544 first = max(1, int(x) - 5)
Guido van Rossum921c8241992-01-10 14:54:42 +0000545 except:
546 print '*** Error in argument:', `arg`
547 return
548 elif self.lineno is None:
549 first = max(1, self.curframe.f_lineno - 5)
550 else:
551 first = self.lineno + 1
Guido van Rossumc629d341992-11-05 10:43:02 +0000552 if last == None:
Guido van Rossum921c8241992-01-10 14:54:42 +0000553 last = first + 10
554 filename = self.curframe.f_code.co_filename
Guido van Rossum23efba41992-01-27 16:58:47 +0000555 breaklist = self.get_file_breaks(filename)
Guido van Rossum921c8241992-01-10 14:54:42 +0000556 try:
557 for lineno in range(first, last+1):
558 line = linecache.getline(filename, lineno)
559 if not line:
560 print '[EOF]'
561 break
562 else:
563 s = string.rjust(`lineno`, 3)
564 if len(s) < 4: s = s + ' '
565 if lineno in breaklist: s = s + 'B'
566 else: s = s + ' '
567 if lineno == self.curframe.f_lineno:
568 s = s + '->'
569 print s + '\t' + line,
570 self.lineno = lineno
571 except KeyboardInterrupt:
572 pass
573 do_l = do_list
Guido van Rossum00230781993-03-29 11:39:45 +0000574
575 def do_whatis(self, arg):
Guido van Rossum00230781993-03-29 11:39:45 +0000576 try:
Guido van Rossum2424f851998-09-11 22:50:09 +0000577 value = eval(arg, self.curframe.f_globals,
Guido van Rossum00230781993-03-29 11:39:45 +0000578 self.curframe.f_locals)
579 except:
Guido van Rossumf15d1591997-09-29 23:22:12 +0000580 t, v = sys.exc_info()[:2]
581 if type(t) == type(''):
582 exc_type_name = t
583 else: exc_type_name = t.__name__
584 print '***', exc_type_name + ':', `v`
Guido van Rossum00230781993-03-29 11:39:45 +0000585 return
586 code = None
587 # Is it a function?
588 try: code = value.func_code
589 except: pass
590 if code:
Guido van Rossumb6775db1994-08-01 11:34:53 +0000591 print 'Function', code.co_name
Guido van Rossum00230781993-03-29 11:39:45 +0000592 return
593 # Is it an instance method?
594 try: code = value.im_func.func_code
595 except: pass
596 if code:
Guido van Rossumb6775db1994-08-01 11:34:53 +0000597 print 'Method', code.co_name
Guido van Rossum00230781993-03-29 11:39:45 +0000598 return
599 # None of the above...
600 print type(value)
Guido van Rossum2424f851998-09-11 22:50:09 +0000601
602 def do_alias(self, arg):
603 args = string.split (arg)
604 if len(args) == 0:
605 keys = self.aliases.keys()
606 keys.sort()
607 for alias in keys:
608 print "%s = %s" % (alias, self.aliases[alias])
609 return
610 if self.aliases.has_key(args[0]) and len (args) == 1:
611 print "%s = %s" % (args[0], self.aliases[args[0]])
612 else:
613 self.aliases[args[0]] = string.join(args[1:], ' ')
614
615 def do_unalias(self, arg):
616 args = string.split (arg)
617 if len(args) == 0: return
618 if self.aliases.has_key(args[0]):
619 del self.aliases[args[0]]
620
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000621 # Print a traceback starting at the top stack frame.
Guido van Rossum23efba41992-01-27 16:58:47 +0000622 # The most recently entered frame is printed last;
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000623 # this is different from dbx and gdb, but consistent with
624 # the Python interpreter's stack trace.
625 # It is also consistent with the up/down commands (which are
626 # compatible with dbx and gdb: up moves towards 'main()'
627 # and down moves towards the most recent stack frame).
Guido van Rossum921c8241992-01-10 14:54:42 +0000628
Guido van Rossum23efba41992-01-27 16:58:47 +0000629 def print_stack_trace(self):
630 try:
631 for frame_lineno in self.stack:
632 self.print_stack_entry(frame_lineno)
633 except KeyboardInterrupt:
634 pass
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000635
Guido van Rossumb6aa92e1995-02-03 12:50:04 +0000636 def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix):
Guido van Rossum23efba41992-01-27 16:58:47 +0000637 frame, lineno = frame_lineno
638 if frame is self.curframe:
639 print '>',
640 else:
641 print ' ',
Guido van Rossuma558e371994-11-10 22:27:35 +0000642 print self.format_stack_entry(frame_lineno, prompt_prefix)
Guido van Rossum921c8241992-01-10 14:54:42 +0000643
644
Guido van Rossumb6775db1994-08-01 11:34:53 +0000645 # Help methods (derived from pdb.doc)
646
647 def help_help(self):
648 self.help_h()
649
650 def help_h(self):
651 print """h(elp)
652 Without argument, print the list of available commands.
653 With a command name as argument, print help about that command
654 "help pdb" pipes the full documentation file to the $PAGER
655 "help exec" gives help on the ! command"""
656
657 def help_where(self):
658 self.help_w()
659
660 def help_w(self):
661 print """w(here)
662 Print a stack trace, with the most recent frame at the bottom.
663 An arrow indicates the "current frame", which determines the
664 context of most commands."""
665
666 def help_down(self):
667 self.help_d()
668
669 def help_d(self):
670 print """d(own)
671 Move the current frame one level down in the stack trace
672 (to an older frame)."""
673
674 def help_up(self):
675 self.help_u()
676
677 def help_u(self):
678 print """u(p)
679 Move the current frame one level up in the stack trace
680 (to a newer frame)."""
681
682 def help_break(self):
683 self.help_b()
684
685 def help_b(self):
Guido van Rossum3a98e781998-09-17 15:00:30 +0000686 print """b(reak) ([file:]lineno | function) [, condition]
Guido van Rossumb6775db1994-08-01 11:34:53 +0000687 With a line number argument, set a break there in the current
Guido van Rossum2424f851998-09-11 22:50:09 +0000688 file. With a function name, set a break at first executable line
689 of that function. Without argument, list all breaks. If a second
Guido van Rossum9e1ee971997-07-11 13:43:53 +0000690 argument is present, it is a string specifying an expression
691 which must evaluate to true before the breakpoint is honored.
Guido van Rossumb5699c71998-07-20 23:13:54 +0000692
693 The line number may be prefixed with a filename and a colon,
694 to specify a breakpoint in another file (probably one that
Guido van Rossum2424f851998-09-11 22:50:09 +0000695 hasn't been loaded yet). The file is searched for on sys.path;
Guido van Rossum1f00eed1998-07-22 13:35:21 +0000696 the .py suffix may be omitted."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000697
698 def help_clear(self):
699 self.help_cl()
700
701 def help_cl(self):
Guido van Rossum816a9fb1999-01-25 20:56:07 +0000702 print "cl(ear) filename:lineno"
Guido van Rossum2424f851998-09-11 22:50:09 +0000703 print """cl(ear) [bpnumber [bpnumber...]]
704 With a space separated list of breakpoint numbers, clear
705 those breakpoints. Without argument, clear all breaks (but
Guido van Rossum816a9fb1999-01-25 20:56:07 +0000706 first ask confirmation). With a filename:lineno argument,
707 clear all breaks at that line in that file.
Guido van Rossumb5699c71998-07-20 23:13:54 +0000708
Guido van Rossum2424f851998-09-11 22:50:09 +0000709 Note that the argument is different from previous versions of
710 the debugger (in python distributions 1.5.1 and before) where
711 a linenumber was used instead of breakpoint numbers."""
712
713 def help_tbreak(self):
714 print """tbreak same arguments as break, but breakpoint is
715 removed when first hit."""
716
717 def help_enable(self):
718 print """enable bpnumber [bpnumber ...]
719 Enables the breakpoints given as a space separated list of
720 bp numbers."""
721
722 def help_disable(self):
723 print """disable bpnumber [bpnumber ...]
724 Disables the breakpoints given as a space separated list of
725 bp numbers."""
726
727 def help_ignore(self):
728 print """ignore bpnumber count
729 Sets the ignore count for the given breakpoint number. A breakpoint
730 becomes active when the ignore count is zero. When non-zero, the
731 count is decremented each time the breakpoint is reached and the
732 breakpoint is not disabled and any associated condition evaluates
733 to true."""
734
735 def help_condition(self):
736 print """condition bpnumber str_condition
737 str_condition is a string specifying an expression which
738 must evaluate to true before the breakpoint is honored.
739 If str_condition is absent, any existing condition is removed;
740 i.e., the breakpoint is made unconditional."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000741
742 def help_step(self):
743 self.help_s()
744
745 def help_s(self):
746 print """s(tep)
747 Execute the current line, stop at the first possible occasion
748 (either in a function that is called or in the current function)."""
749
750 def help_next(self):
751 self.help_n()
752
753 def help_n(self):
754 print """n(ext)
755 Continue execution until the next line in the current function
756 is reached or it returns."""
757
758 def help_return(self):
759 self.help_r()
760
761 def help_r(self):
762 print """r(eturn)
763 Continue execution until the current function returns."""
764
765 def help_continue(self):
766 self.help_c()
767
768 def help_cont(self):
769 self.help_c()
770
771 def help_c(self):
772 print """c(ont(inue))
773 Continue execution, only stop when a breakpoint is encountered."""
774
775 def help_list(self):
776 self.help_l()
777
778 def help_l(self):
779 print """l(ist) [first [,last]]
780 List source code for the current file.
781 Without arguments, list 11 lines around the current line
782 or continue the previous listing.
783 With one argument, list 11 lines starting at that line.
784 With two arguments, list the given range;
785 if the second argument is less than the first, it is a count."""
786
787 def help_args(self):
788 self.help_a()
789
790 def help_a(self):
791 print """a(rgs)
Guido van Rossum46c86bb1998-02-25 20:50:32 +0000792 Print the arguments of the current function."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000793
794 def help_p(self):
795 print """p expression
796 Print the value of the expression."""
797
798 def help_exec(self):
799 print """(!) statement
800 Execute the (one-line) statement in the context of
801 the current stack frame.
802 The exclamation point can be omitted unless the first word
803 of the statement resembles a debugger command.
804 To assign to a global variable you must always prefix the
805 command with a 'global' command, e.g.:
806 (Pdb) global list_options; list_options = ['-l']
807 (Pdb)"""
808
809 def help_quit(self):
810 self.help_q()
811
812 def help_q(self):
813 print """q(uit) Quit from the debugger.
814 The program being executed is aborted."""
815
Guido van Rossum2424f851998-09-11 22:50:09 +0000816 def help_whatis(self):
817 print """whatis arg
818 Prints the type of the argument."""
819
820 def help_EOF(self):
821 print """EOF
822 Handles the receipt of EOF as a command."""
823
824 def help_alias(self):
825 print """alias [name [command [parameter parameter ...] ]]
826 Creates an alias called 'name' the executes 'command'. The command
827 must *not* be enclosed in quotes. Replaceable parameters are
828 indicated by %1, %2, and so on, while %* is replaced by all the
829 parameters. If no command is given, the current alias for name
830 is shown. If no name is given, all aliases are listed.
831
832 Aliases may be nested and can contain anything that can be
833 legally typed at the pdb prompt. Note! You *can* override
834 internal pdb commands with aliases! Those internal commands
835 are then hidden until the alias is removed. Aliasing is recursively
836 applied to the first word of the command line; all other words
837 in the line are left alone.
838
839 Some useful aliases (especially when placed in the .pdbrc file) are:
840
841 #Print instance variables (usage "pi classInst")
842 alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
843
844 #Print instance variables in self
845 alias ps pi self
846 """
847
848 def help_unalias(self):
849 print """unalias name
850 Deletes the specified alias."""
851
Guido van Rossumb6775db1994-08-01 11:34:53 +0000852 def help_pdb(self):
853 help()
854
Guido van Rossumb5699c71998-07-20 23:13:54 +0000855 # Helper function for break/clear parsing -- may be overridden
856
857 def lookupmodule(self, filename):
Guido van Rossum1f00eed1998-07-22 13:35:21 +0000858 root, ext = os.path.splitext(filename)
859 if ext == '':
860 filename = filename + '.py'
861 if os.path.isabs(filename):
862 return filename
Guido van Rossumb5699c71998-07-20 23:13:54 +0000863 for dirname in sys.path:
Guido van Rossum2424f851998-09-11 22:50:09 +0000864 while os.path.islink(dirname):
865 dirname = os.readlink(dirname)
Guido van Rossumb5699c71998-07-20 23:13:54 +0000866 fullname = os.path.join(dirname, filename)
867 if os.path.exists(fullname):
868 return fullname
Guido van Rossum2424f851998-09-11 22:50:09 +0000869 return None
Guido van Rossumb5699c71998-07-20 23:13:54 +0000870
Guido van Rossum35771131992-09-08 11:59:04 +0000871# Simplified interface
872
Guido van Rossum5e38b6f1995-02-27 13:13:40 +0000873def run(statement, globals=None, locals=None):
874 Pdb().run(statement, globals, locals)
875
876def runeval(expression, globals=None, locals=None):
877 return Pdb().runeval(expression, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000878
879def runctx(statement, globals, locals):
Guido van Rossum5e38b6f1995-02-27 13:13:40 +0000880 # B/W compatibility
881 run(statement, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000882
Guido van Rossum4e160981992-09-02 20:43:20 +0000883def runcall(*args):
Guido van Rossum5e38b6f1995-02-27 13:13:40 +0000884 return apply(Pdb().runcall, args)
Guido van Rossum4e160981992-09-02 20:43:20 +0000885
Guido van Rossumb6775db1994-08-01 11:34:53 +0000886def set_trace():
887 Pdb().set_trace()
Guido van Rossum35771131992-09-08 11:59:04 +0000888
889# Post-Mortem interface
890
891def post_mortem(t):
Guido van Rossum5ef74b81993-06-23 11:55:24 +0000892 p = Pdb()
Guido van Rossum35771131992-09-08 11:59:04 +0000893 p.reset()
894 while t.tb_next <> None: t = t.tb_next
895 p.interaction(t.tb_frame, t)
896
897def pm():
Guido van Rossum35771131992-09-08 11:59:04 +0000898 post_mortem(sys.last_traceback)
899
900
901# Main program for testing
902
Guido van Rossum23efba41992-01-27 16:58:47 +0000903TESTCMD = 'import x; x.main()'
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000904
Guido van Rossum921c8241992-01-10 14:54:42 +0000905def test():
Guido van Rossum23efba41992-01-27 16:58:47 +0000906 run(TESTCMD)
Guido van Rossume61fa0a1993-10-22 13:56:35 +0000907
908# print help
909def help():
910 for dirname in sys.path:
911 fullname = os.path.join(dirname, 'pdb.doc')
912 if os.path.exists(fullname):
913 sts = os.system('${PAGER-more} '+fullname)
914 if sts: print '*** Pager exit status:', sts
915 break
916 else:
917 print 'Sorry, can\'t find the help file "pdb.doc"',
918 print 'along the Python search path'
Guido van Rossumf17361d1996-07-30 16:28:13 +0000919
Guido van Rossumb5699c71998-07-20 23:13:54 +0000920mainmodule = ''
921mainpyfile = ''
922
Guido van Rossumf17361d1996-07-30 16:28:13 +0000923# When invoked as main program, invoke the debugger on a script
924if __name__=='__main__':
Guido van Rossumb5699c71998-07-20 23:13:54 +0000925 global mainmodule, mainpyfile
Guido van Rossumf17361d1996-07-30 16:28:13 +0000926 if not sys.argv[1:]:
927 print "usage: pdb.py scriptfile [arg] ..."
928 sys.exit(2)
929
Guido van Rossumb5699c71998-07-20 23:13:54 +0000930 mainpyfile = filename = sys.argv[1] # Get script filename
931 if not os.path.exists(filename):
932 print 'Error:', `filename`, 'does not exist'
933 sys.exit(1)
934 mainmodule = os.path.basename(filename)
Guido van Rossumec577d51996-09-10 17:39:34 +0000935 del sys.argv[0] # Hide "pdb.py" from argument list
936
937 # Insert script directory in front of module search path
938 sys.path.insert(0, os.path.dirname(filename))
Guido van Rossumf17361d1996-07-30 16:28:13 +0000939
Guido van Rossumc2047c11998-10-15 01:38:23 +0000940 run('execfile(' + `filename` + ')')