blob: 7d84e3c13cb55a5de0d7211f83783a27b6d5f534 [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 Rossum921c8241992-01-10 14:54:42 +0000425
426 def do_where(self, arg):
Guido van Rossum23efba41992-01-27 16:58:47 +0000427 self.print_stack_trace()
Guido van Rossum921c8241992-01-10 14:54:42 +0000428 do_w = do_where
429
430 def do_up(self, arg):
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000431 if self.curindex == 0:
432 print '*** Oldest frame'
Guido van Rossum921c8241992-01-10 14:54:42 +0000433 else:
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000434 self.curindex = self.curindex - 1
435 self.curframe = self.stack[self.curindex][0]
Guido van Rossum23efba41992-01-27 16:58:47 +0000436 self.print_stack_entry(self.stack[self.curindex])
Guido van Rossumc629d341992-11-05 10:43:02 +0000437 self.lineno = None
Guido van Rossumb9142571992-01-12 23:32:55 +0000438 do_u = do_up
439
440 def do_down(self, arg):
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000441 if self.curindex + 1 == len(self.stack):
442 print '*** Newest frame'
Guido van Rossumb9142571992-01-12 23:32:55 +0000443 else:
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000444 self.curindex = self.curindex + 1
445 self.curframe = self.stack[self.curindex][0]
Guido van Rossum23efba41992-01-27 16:58:47 +0000446 self.print_stack_entry(self.stack[self.curindex])
Guido van Rossumc629d341992-11-05 10:43:02 +0000447 self.lineno = None
Guido van Rossum921c8241992-01-10 14:54:42 +0000448 do_d = do_down
449
450 def do_step(self, arg):
Guido van Rossum23efba41992-01-27 16:58:47 +0000451 self.set_step()
Guido van Rossumb9142571992-01-12 23:32:55 +0000452 return 1
Guido van Rossum921c8241992-01-10 14:54:42 +0000453 do_s = do_step
454
455 def do_next(self, arg):
Guido van Rossum23efba41992-01-27 16:58:47 +0000456 self.set_next(self.curframe)
Guido van Rossumb9142571992-01-12 23:32:55 +0000457 return 1
Guido van Rossum921c8241992-01-10 14:54:42 +0000458 do_n = do_next
459
Guido van Rossumb9142571992-01-12 23:32:55 +0000460 def do_return(self, arg):
Guido van Rossum23efba41992-01-27 16:58:47 +0000461 self.set_return(self.curframe)
Guido van Rossumb9142571992-01-12 23:32:55 +0000462 return 1
463 do_r = do_return
464
Guido van Rossum921c8241992-01-10 14:54:42 +0000465 def do_continue(self, arg):
Guido van Rossum23efba41992-01-27 16:58:47 +0000466 self.set_continue()
Guido van Rossumb9142571992-01-12 23:32:55 +0000467 return 1
Guido van Rossum921c8241992-01-10 14:54:42 +0000468 do_c = do_cont = do_continue
469
470 def do_quit(self, arg):
Guido van Rossum23efba41992-01-27 16:58:47 +0000471 self.set_quit()
472 return 1
Guido van Rossum921c8241992-01-10 14:54:42 +0000473 do_q = do_quit
474
Guido van Rossum23efba41992-01-27 16:58:47 +0000475 def do_args(self, arg):
Guido van Rossum46c86bb1998-02-25 20:50:32 +0000476 f = self.curframe
477 co = f.f_code
478 dict = f.f_locals
479 n = co.co_argcount
480 if co.co_flags & 4: n = n+1
481 if co.co_flags & 8: n = n+1
482 for i in range(n):
483 name = co.co_varnames[i]
484 print name, '=',
485 if dict.has_key(name): print dict[name]
486 else: print "*** undefined ***"
Guido van Rossum23efba41992-01-27 16:58:47 +0000487 do_a = do_args
488
489 def do_retval(self, arg):
490 if self.curframe.f_locals.has_key('__return__'):
491 print self.curframe.f_locals['__return__']
492 else:
493 print '*** Not yet returned!'
494 do_rv = do_retval
495
496 def do_p(self, arg):
497 try:
Guido van Rossum2424f851998-09-11 22:50:09 +0000498 value = eval(arg, self.curframe.f_globals,
Guido van Rossum23efba41992-01-27 16:58:47 +0000499 self.curframe.f_locals)
500 except:
Guido van Rossumf15d1591997-09-29 23:22:12 +0000501 t, v = sys.exc_info()[:2]
502 if type(t) == type(''):
503 exc_type_name = t
504 else: exc_type_name = t.__name__
505 print '***', exc_type_name + ':', `v`
Guido van Rossum23efba41992-01-27 16:58:47 +0000506 return
Guido van Rossum8e2ec561993-07-29 09:37:38 +0000507
Guido van Rossum23efba41992-01-27 16:58:47 +0000508 print `value`
509
Guido van Rossum921c8241992-01-10 14:54:42 +0000510 def do_list(self, arg):
Guido van Rossumb9142571992-01-12 23:32:55 +0000511 self.lastcmd = 'list'
Guido van Rossum921c8241992-01-10 14:54:42 +0000512 last = None
513 if arg:
514 try:
515 x = eval(arg, {}, {})
516 if type(x) == type(()):
517 first, last = x
518 first = int(first)
519 last = int(last)
520 if last < first:
521 # Assume it's a count
522 last = first + last
523 else:
Guido van Rossumc629d341992-11-05 10:43:02 +0000524 first = max(1, int(x) - 5)
Guido van Rossum921c8241992-01-10 14:54:42 +0000525 except:
526 print '*** Error in argument:', `arg`
527 return
528 elif self.lineno is None:
529 first = max(1, self.curframe.f_lineno - 5)
530 else:
531 first = self.lineno + 1
Guido van Rossumc629d341992-11-05 10:43:02 +0000532 if last == None:
Guido van Rossum921c8241992-01-10 14:54:42 +0000533 last = first + 10
534 filename = self.curframe.f_code.co_filename
Guido van Rossum23efba41992-01-27 16:58:47 +0000535 breaklist = self.get_file_breaks(filename)
Guido van Rossum921c8241992-01-10 14:54:42 +0000536 try:
537 for lineno in range(first, last+1):
538 line = linecache.getline(filename, lineno)
539 if not line:
540 print '[EOF]'
541 break
542 else:
543 s = string.rjust(`lineno`, 3)
544 if len(s) < 4: s = s + ' '
545 if lineno in breaklist: s = s + 'B'
546 else: s = s + ' '
547 if lineno == self.curframe.f_lineno:
548 s = s + '->'
549 print s + '\t' + line,
550 self.lineno = lineno
551 except KeyboardInterrupt:
552 pass
553 do_l = do_list
Guido van Rossum00230781993-03-29 11:39:45 +0000554
555 def do_whatis(self, arg):
Guido van Rossum00230781993-03-29 11:39:45 +0000556 try:
Guido van Rossum2424f851998-09-11 22:50:09 +0000557 value = eval(arg, self.curframe.f_globals,
Guido van Rossum00230781993-03-29 11:39:45 +0000558 self.curframe.f_locals)
559 except:
Guido van Rossumf15d1591997-09-29 23:22:12 +0000560 t, v = sys.exc_info()[:2]
561 if type(t) == type(''):
562 exc_type_name = t
563 else: exc_type_name = t.__name__
564 print '***', exc_type_name + ':', `v`
Guido van Rossum00230781993-03-29 11:39:45 +0000565 return
566 code = None
567 # Is it a function?
568 try: code = value.func_code
569 except: pass
570 if code:
Guido van Rossumb6775db1994-08-01 11:34:53 +0000571 print 'Function', code.co_name
Guido van Rossum00230781993-03-29 11:39:45 +0000572 return
573 # Is it an instance method?
574 try: code = value.im_func.func_code
575 except: pass
576 if code:
Guido van Rossumb6775db1994-08-01 11:34:53 +0000577 print 'Method', code.co_name
Guido van Rossum00230781993-03-29 11:39:45 +0000578 return
579 # None of the above...
580 print type(value)
Guido van Rossum2424f851998-09-11 22:50:09 +0000581
582 def do_alias(self, arg):
583 args = string.split (arg)
584 if len(args) == 0:
585 keys = self.aliases.keys()
586 keys.sort()
587 for alias in keys:
588 print "%s = %s" % (alias, self.aliases[alias])
589 return
590 if self.aliases.has_key(args[0]) and len (args) == 1:
591 print "%s = %s" % (args[0], self.aliases[args[0]])
592 else:
593 self.aliases[args[0]] = string.join(args[1:], ' ')
594
595 def do_unalias(self, arg):
596 args = string.split (arg)
597 if len(args) == 0: return
598 if self.aliases.has_key(args[0]):
599 del self.aliases[args[0]]
600
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000601 # Print a traceback starting at the top stack frame.
Guido van Rossum23efba41992-01-27 16:58:47 +0000602 # The most recently entered frame is printed last;
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000603 # this is different from dbx and gdb, but consistent with
604 # the Python interpreter's stack trace.
605 # It is also consistent with the up/down commands (which are
606 # compatible with dbx and gdb: up moves towards 'main()'
607 # and down moves towards the most recent stack frame).
Guido van Rossum921c8241992-01-10 14:54:42 +0000608
Guido van Rossum23efba41992-01-27 16:58:47 +0000609 def print_stack_trace(self):
610 try:
611 for frame_lineno in self.stack:
612 self.print_stack_entry(frame_lineno)
613 except KeyboardInterrupt:
614 pass
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000615
Guido van Rossumb6aa92e1995-02-03 12:50:04 +0000616 def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix):
Guido van Rossum23efba41992-01-27 16:58:47 +0000617 frame, lineno = frame_lineno
618 if frame is self.curframe:
619 print '>',
620 else:
621 print ' ',
Guido van Rossuma558e371994-11-10 22:27:35 +0000622 print self.format_stack_entry(frame_lineno, prompt_prefix)
Guido van Rossum921c8241992-01-10 14:54:42 +0000623
624
Guido van Rossumb6775db1994-08-01 11:34:53 +0000625 # Help methods (derived from pdb.doc)
626
627 def help_help(self):
628 self.help_h()
629
630 def help_h(self):
631 print """h(elp)
632 Without argument, print the list of available commands.
633 With a command name as argument, print help about that command
634 "help pdb" pipes the full documentation file to the $PAGER
635 "help exec" gives help on the ! command"""
636
637 def help_where(self):
638 self.help_w()
639
640 def help_w(self):
641 print """w(here)
642 Print a stack trace, with the most recent frame at the bottom.
643 An arrow indicates the "current frame", which determines the
644 context of most commands."""
645
646 def help_down(self):
647 self.help_d()
648
649 def help_d(self):
650 print """d(own)
651 Move the current frame one level down in the stack trace
652 (to an older frame)."""
653
654 def help_up(self):
655 self.help_u()
656
657 def help_u(self):
658 print """u(p)
659 Move the current frame one level up in the stack trace
660 (to a newer frame)."""
661
662 def help_break(self):
663 self.help_b()
664
665 def help_b(self):
Guido van Rossum3a98e781998-09-17 15:00:30 +0000666 print """b(reak) ([file:]lineno | function) [, condition]
Guido van Rossumb6775db1994-08-01 11:34:53 +0000667 With a line number argument, set a break there in the current
Guido van Rossum2424f851998-09-11 22:50:09 +0000668 file. With a function name, set a break at first executable line
669 of that function. Without argument, list all breaks. If a second
Guido van Rossum9e1ee971997-07-11 13:43:53 +0000670 argument is present, it is a string specifying an expression
671 which must evaluate to true before the breakpoint is honored.
Guido van Rossumb5699c71998-07-20 23:13:54 +0000672
673 The line number may be prefixed with a filename and a colon,
674 to specify a breakpoint in another file (probably one that
Guido van Rossum2424f851998-09-11 22:50:09 +0000675 hasn't been loaded yet). The file is searched for on sys.path;
Guido van Rossum1f00eed1998-07-22 13:35:21 +0000676 the .py suffix may be omitted."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000677
678 def help_clear(self):
679 self.help_cl()
680
681 def help_cl(self):
Guido van Rossum816a9fb1999-01-25 20:56:07 +0000682 print "cl(ear) filename:lineno"
Guido van Rossum2424f851998-09-11 22:50:09 +0000683 print """cl(ear) [bpnumber [bpnumber...]]
684 With a space separated list of breakpoint numbers, clear
685 those breakpoints. Without argument, clear all breaks (but
Guido van Rossum816a9fb1999-01-25 20:56:07 +0000686 first ask confirmation). With a filename:lineno argument,
687 clear all breaks at that line in that file.
Guido van Rossumb5699c71998-07-20 23:13:54 +0000688
Guido van Rossum2424f851998-09-11 22:50:09 +0000689 Note that the argument is different from previous versions of
690 the debugger (in python distributions 1.5.1 and before) where
Guido van Rossumb657c931999-01-28 14:38:32 +0000691 a linenumber was used instead of either filename:lineno or
692 breakpoint numbers."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000693
694 def help_tbreak(self):
695 print """tbreak same arguments as break, but breakpoint is
696 removed when first hit."""
697
698 def help_enable(self):
699 print """enable bpnumber [bpnumber ...]
700 Enables the breakpoints given as a space separated list of
701 bp numbers."""
702
703 def help_disable(self):
704 print """disable bpnumber [bpnumber ...]
705 Disables the breakpoints given as a space separated list of
706 bp numbers."""
707
708 def help_ignore(self):
709 print """ignore bpnumber count
710 Sets the ignore count for the given breakpoint number. A breakpoint
711 becomes active when the ignore count is zero. When non-zero, the
712 count is decremented each time the breakpoint is reached and the
713 breakpoint is not disabled and any associated condition evaluates
714 to true."""
715
716 def help_condition(self):
717 print """condition bpnumber str_condition
718 str_condition is a string specifying an expression which
719 must evaluate to true before the breakpoint is honored.
720 If str_condition is absent, any existing condition is removed;
721 i.e., the breakpoint is made unconditional."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000722
723 def help_step(self):
724 self.help_s()
725
726 def help_s(self):
727 print """s(tep)
728 Execute the current line, stop at the first possible occasion
729 (either in a function that is called or in the current function)."""
730
731 def help_next(self):
732 self.help_n()
733
734 def help_n(self):
735 print """n(ext)
736 Continue execution until the next line in the current function
737 is reached or it returns."""
738
739 def help_return(self):
740 self.help_r()
741
742 def help_r(self):
743 print """r(eturn)
744 Continue execution until the current function returns."""
745
746 def help_continue(self):
747 self.help_c()
748
749 def help_cont(self):
750 self.help_c()
751
752 def help_c(self):
753 print """c(ont(inue))
754 Continue execution, only stop when a breakpoint is encountered."""
755
756 def help_list(self):
757 self.help_l()
758
759 def help_l(self):
760 print """l(ist) [first [,last]]
761 List source code for the current file.
762 Without arguments, list 11 lines around the current line
763 or continue the previous listing.
764 With one argument, list 11 lines starting at that line.
765 With two arguments, list the given range;
766 if the second argument is less than the first, it is a count."""
767
768 def help_args(self):
769 self.help_a()
770
771 def help_a(self):
772 print """a(rgs)
Guido van Rossum46c86bb1998-02-25 20:50:32 +0000773 Print the arguments of the current function."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000774
775 def help_p(self):
776 print """p expression
777 Print the value of the expression."""
778
779 def help_exec(self):
780 print """(!) statement
781 Execute the (one-line) statement in the context of
782 the current stack frame.
783 The exclamation point can be omitted unless the first word
784 of the statement resembles a debugger command.
785 To assign to a global variable you must always prefix the
786 command with a 'global' command, e.g.:
787 (Pdb) global list_options; list_options = ['-l']
788 (Pdb)"""
789
790 def help_quit(self):
791 self.help_q()
792
793 def help_q(self):
794 print """q(uit) Quit from the debugger.
795 The program being executed is aborted."""
796
Guido van Rossum2424f851998-09-11 22:50:09 +0000797 def help_whatis(self):
798 print """whatis arg
799 Prints the type of the argument."""
800
801 def help_EOF(self):
802 print """EOF
803 Handles the receipt of EOF as a command."""
804
805 def help_alias(self):
806 print """alias [name [command [parameter parameter ...] ]]
807 Creates an alias called 'name' the executes 'command'. The command
808 must *not* be enclosed in quotes. Replaceable parameters are
809 indicated by %1, %2, and so on, while %* is replaced by all the
810 parameters. If no command is given, the current alias for name
811 is shown. If no name is given, all aliases are listed.
812
813 Aliases may be nested and can contain anything that can be
814 legally typed at the pdb prompt. Note! You *can* override
815 internal pdb commands with aliases! Those internal commands
816 are then hidden until the alias is removed. Aliasing is recursively
817 applied to the first word of the command line; all other words
818 in the line are left alone.
819
820 Some useful aliases (especially when placed in the .pdbrc file) are:
821
822 #Print instance variables (usage "pi classInst")
823 alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
824
825 #Print instance variables in self
826 alias ps pi self
827 """
828
829 def help_unalias(self):
830 print """unalias name
831 Deletes the specified alias."""
832
Guido van Rossumb6775db1994-08-01 11:34:53 +0000833 def help_pdb(self):
834 help()
835
Guido van Rossumb5699c71998-07-20 23:13:54 +0000836 # Helper function for break/clear parsing -- may be overridden
837
838 def lookupmodule(self, filename):
Guido van Rossum1f00eed1998-07-22 13:35:21 +0000839 root, ext = os.path.splitext(filename)
840 if ext == '':
841 filename = filename + '.py'
842 if os.path.isabs(filename):
843 return filename
Guido van Rossumb5699c71998-07-20 23:13:54 +0000844 for dirname in sys.path:
Guido van Rossum2424f851998-09-11 22:50:09 +0000845 while os.path.islink(dirname):
846 dirname = os.readlink(dirname)
Guido van Rossumb5699c71998-07-20 23:13:54 +0000847 fullname = os.path.join(dirname, filename)
848 if os.path.exists(fullname):
849 return fullname
Guido van Rossum2424f851998-09-11 22:50:09 +0000850 return None
Guido van Rossumb5699c71998-07-20 23:13:54 +0000851
Guido van Rossum35771131992-09-08 11:59:04 +0000852# Simplified interface
853
Guido van Rossum5e38b6f1995-02-27 13:13:40 +0000854def run(statement, globals=None, locals=None):
855 Pdb().run(statement, globals, locals)
856
857def runeval(expression, globals=None, locals=None):
858 return Pdb().runeval(expression, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000859
860def runctx(statement, globals, locals):
Guido van Rossum5e38b6f1995-02-27 13:13:40 +0000861 # B/W compatibility
862 run(statement, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000863
Guido van Rossum4e160981992-09-02 20:43:20 +0000864def runcall(*args):
Guido van Rossum5e38b6f1995-02-27 13:13:40 +0000865 return apply(Pdb().runcall, args)
Guido van Rossum4e160981992-09-02 20:43:20 +0000866
Guido van Rossumb6775db1994-08-01 11:34:53 +0000867def set_trace():
868 Pdb().set_trace()
Guido van Rossum35771131992-09-08 11:59:04 +0000869
870# Post-Mortem interface
871
872def post_mortem(t):
Guido van Rossum5ef74b81993-06-23 11:55:24 +0000873 p = Pdb()
Guido van Rossum35771131992-09-08 11:59:04 +0000874 p.reset()
875 while t.tb_next <> None: t = t.tb_next
876 p.interaction(t.tb_frame, t)
877
878def pm():
Guido van Rossum35771131992-09-08 11:59:04 +0000879 post_mortem(sys.last_traceback)
880
881
882# Main program for testing
883
Guido van Rossum23efba41992-01-27 16:58:47 +0000884TESTCMD = 'import x; x.main()'
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000885
Guido van Rossum921c8241992-01-10 14:54:42 +0000886def test():
Guido van Rossum23efba41992-01-27 16:58:47 +0000887 run(TESTCMD)
Guido van Rossume61fa0a1993-10-22 13:56:35 +0000888
889# print help
890def help():
891 for dirname in sys.path:
892 fullname = os.path.join(dirname, 'pdb.doc')
893 if os.path.exists(fullname):
894 sts = os.system('${PAGER-more} '+fullname)
895 if sts: print '*** Pager exit status:', sts
896 break
897 else:
898 print 'Sorry, can\'t find the help file "pdb.doc"',
899 print 'along the Python search path'
Guido van Rossumf17361d1996-07-30 16:28:13 +0000900
Guido van Rossumb5699c71998-07-20 23:13:54 +0000901mainmodule = ''
902mainpyfile = ''
903
Guido van Rossumf17361d1996-07-30 16:28:13 +0000904# When invoked as main program, invoke the debugger on a script
905if __name__=='__main__':
Guido van Rossumb5699c71998-07-20 23:13:54 +0000906 global mainmodule, mainpyfile
Guido van Rossumf17361d1996-07-30 16:28:13 +0000907 if not sys.argv[1:]:
908 print "usage: pdb.py scriptfile [arg] ..."
909 sys.exit(2)
910
Guido van Rossumb5699c71998-07-20 23:13:54 +0000911 mainpyfile = filename = sys.argv[1] # Get script filename
912 if not os.path.exists(filename):
913 print 'Error:', `filename`, 'does not exist'
914 sys.exit(1)
915 mainmodule = os.path.basename(filename)
Guido van Rossumec577d51996-09-10 17:39:34 +0000916 del sys.argv[0] # Hide "pdb.py" from argument list
917
918 # Insert script directory in front of module search path
919 sys.path.insert(0, os.path.dirname(filename))
Guido van Rossumf17361d1996-07-30 16:28:13 +0000920
Guido van Rossumc2047c11998-10-15 01:38:23 +0000921 run('execfile(' + `filename` + ')')