blob: 1a57c85791a4e6791d3b5f78b8e0ccbc01a1e43e [file] [log] [blame]
Guido van Rossumf06ee5f1996-11-27 19:52:01 +00001#! /usr/bin/env python
Guido van Rossumf17361d1996-07-30 16:28:13 +00002
Guido van Rossum4b8c6ea2000-02-04 15:39:30 +00003"""A Python debugger."""
Guido van Rossum92df0c61992-01-14 18:30:15 +00004
Guido van Rossum23efba41992-01-27 16:58:47 +00005# (See pdb.doc for documentation.)
Guido van Rossum921c8241992-01-10 14:54:42 +00006
Guido van Rossum921c8241992-01-10 14:54:42 +00007import sys
8import linecache
Guido van Rossum23efba41992-01-27 16:58:47 +00009import cmd
10import bdb
Guido van Rossumef1b41b2002-09-10 21:57:14 +000011from repr import Repr
Guido van Rossumb5699c71998-07-20 23:13:54 +000012import os
Barry Warsaw2bee8fe1999-09-09 16:32:41 +000013import re
Barry Warsaw210bd202002-11-05 22:40:20 +000014import pprint
Barry Warsaw2bee8fe1999-09-09 16:32:41 +000015
Guido van Rossumef1b41b2002-09-10 21:57:14 +000016# Create a custom safe Repr instance and increase its maxstring.
17# The default of 30 truncates error messages too easily.
18_repr = Repr()
19_repr.maxstring = 200
20_saferepr = _repr.repr
21
Skip Montanaro352674d2001-02-07 23:14:30 +000022__all__ = ["run", "pm", "Pdb", "runeval", "runctx", "runcall", "set_trace",
23 "post_mortem", "help"]
24
Barry Warsaw2bee8fe1999-09-09 16:32:41 +000025def find_function(funcname, filename):
Tim Peters2344fae2001-01-15 00:50:52 +000026 cre = re.compile(r'def\s+%s\s*[(]' % funcname)
27 try:
28 fp = open(filename)
29 except IOError:
30 return None
31 # consumer of this info expects the first line to be 1
32 lineno = 1
33 answer = None
34 while 1:
35 line = fp.readline()
36 if line == '':
37 break
38 if cre.match(line):
39 answer = funcname, filename, lineno
40 break
41 lineno = lineno + 1
42 fp.close()
43 return answer
Guido van Rossum921c8241992-01-10 14:54:42 +000044
45
Guido van Rossuma558e371994-11-10 22:27:35 +000046# Interaction prompt line will separate file and call info from code
47# text using value of line_prefix string. A newline and arrow may
48# be to your liking. You can set it once pdb is imported using the
49# command "pdb.line_prefix = '\n% '".
Tim Peters2344fae2001-01-15 00:50:52 +000050# line_prefix = ': ' # Use this to get the old situation back
51line_prefix = '\n-> ' # Probably a better default
Guido van Rossuma558e371994-11-10 22:27:35 +000052
Guido van Rossum23efba41992-01-27 16:58:47 +000053class Pdb(bdb.Bdb, cmd.Cmd):
Guido van Rossum2424f851998-09-11 22:50:09 +000054
Tim Peters2344fae2001-01-15 00:50:52 +000055 def __init__(self):
56 bdb.Bdb.__init__(self)
57 cmd.Cmd.__init__(self)
58 self.prompt = '(Pdb) '
59 self.aliases = {}
60 # Try to load readline if it exists
61 try:
62 import readline
63 except ImportError:
64 pass
Guido van Rossum2424f851998-09-11 22:50:09 +000065
Tim Peters2344fae2001-01-15 00:50:52 +000066 # Read $HOME/.pdbrc and ./.pdbrc
67 self.rcLines = []
Raymond Hettinger54f02222002-06-01 14:18:47 +000068 if 'HOME' in os.environ:
Tim Peters2344fae2001-01-15 00:50:52 +000069 envHome = os.environ['HOME']
70 try:
71 rcFile = open(os.path.join(envHome, ".pdbrc"))
72 except IOError:
73 pass
74 else:
75 for line in rcFile.readlines():
76 self.rcLines.append(line)
77 rcFile.close()
78 try:
79 rcFile = open(".pdbrc")
80 except IOError:
81 pass
82 else:
83 for line in rcFile.readlines():
84 self.rcLines.append(line)
85 rcFile.close()
Guido van Rossum23efba41992-01-27 16:58:47 +000086
Tim Peters2344fae2001-01-15 00:50:52 +000087 def reset(self):
88 bdb.Bdb.reset(self)
89 self.forget()
Guido van Rossum23efba41992-01-27 16:58:47 +000090
Tim Peters2344fae2001-01-15 00:50:52 +000091 def forget(self):
92 self.lineno = None
93 self.stack = []
94 self.curindex = 0
95 self.curframe = None
Guido van Rossum2424f851998-09-11 22:50:09 +000096
Tim Peters2344fae2001-01-15 00:50:52 +000097 def setup(self, f, t):
98 self.forget()
99 self.stack, self.curindex = self.get_stack(f, t)
100 self.curframe = self.stack[self.curindex][0]
101 self.execRcLines()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000102
Tim Peters2344fae2001-01-15 00:50:52 +0000103 # Can be executed earlier than 'setup' if desired
104 def execRcLines(self):
105 if self.rcLines:
106 # Make local copy because of recursion
107 rcLines = self.rcLines
108 # executed only once
109 self.rcLines = []
110 for line in rcLines:
111 line = line[:-1]
Guido van Rossum08454592002-07-12 13:10:53 +0000112 if len(line) > 0 and line[0] != '#':
113 self.onecmd(line)
Guido van Rossum2424f851998-09-11 22:50:09 +0000114
Tim Peters280488b2002-08-23 18:19:30 +0000115 # Override Bdb methods
Michael W. Hudsondd32a912002-08-15 14:59:02 +0000116
117 def user_call(self, frame, argument_list):
118 """This method is called when there is the remote possibility
119 that we ever need to stop in this function."""
120 print '--Call--'
121 self.interaction(frame, None)
Guido van Rossum2424f851998-09-11 22:50:09 +0000122
Tim Peters2344fae2001-01-15 00:50:52 +0000123 def user_line(self, frame):
124 """This function is called when we stop or break at this line."""
125 self.interaction(frame, None)
Guido van Rossum9e1ee971997-07-11 13:43:53 +0000126
Tim Peters2344fae2001-01-15 00:50:52 +0000127 def user_return(self, frame, return_value):
128 """This function is called when a return trap is set here."""
129 frame.f_locals['__return__'] = return_value
130 print '--Return--'
131 self.interaction(frame, None)
Guido van Rossum2424f851998-09-11 22:50:09 +0000132
Tim Peters2344fae2001-01-15 00:50:52 +0000133 def user_exception(self, frame, (exc_type, exc_value, exc_traceback)):
134 """This function is called if an exception occurs,
135 but only if we are to stop at or just below this level."""
136 frame.f_locals['__exception__'] = exc_type, exc_value
137 if type(exc_type) == type(''):
138 exc_type_name = exc_type
139 else: exc_type_name = exc_type.__name__
Tim Peters6f8ee592001-02-09 23:28:07 +0000140 print exc_type_name + ':', _saferepr(exc_value)
Tim Peters2344fae2001-01-15 00:50:52 +0000141 self.interaction(frame, exc_traceback)
Guido van Rossum2424f851998-09-11 22:50:09 +0000142
Tim Peters2344fae2001-01-15 00:50:52 +0000143 # General interaction function
144
145 def interaction(self, frame, traceback):
146 self.setup(frame, traceback)
147 self.print_stack_entry(self.stack[self.curindex])
148 self.cmdloop()
149 self.forget()
150
151 def default(self, line):
152 if line[:1] == '!': line = line[1:]
153 locals = self.curframe.f_locals
154 globals = self.curframe.f_globals
155 try:
156 code = compile(line + '\n', '<stdin>', 'single')
157 exec code in globals, locals
158 except:
159 t, v = sys.exc_info()[:2]
160 if type(t) == type(''):
161 exc_type_name = t
162 else: exc_type_name = t.__name__
163 print '***', exc_type_name + ':', v
164
165 def precmd(self, line):
166 """Handle alias expansion and ';;' separator."""
Guido van Rossum08454592002-07-12 13:10:53 +0000167 if not line.strip():
Tim Peters2344fae2001-01-15 00:50:52 +0000168 return line
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000169 args = line.split()
Raymond Hettinger54f02222002-06-01 14:18:47 +0000170 while args[0] in self.aliases:
Tim Peters2344fae2001-01-15 00:50:52 +0000171 line = self.aliases[args[0]]
172 ii = 1
173 for tmpArg in args[1:]:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000174 line = line.replace("%" + str(ii),
Tim Peters2344fae2001-01-15 00:50:52 +0000175 tmpArg)
176 ii = ii + 1
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000177 line = line.replace("%*", ' '.join(args[1:]))
178 args = line.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000179 # split into ';;' separated commands
180 # unless it's an alias command
181 if args[0] != 'alias':
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000182 marker = line.find(';;')
Tim Peters2344fae2001-01-15 00:50:52 +0000183 if marker >= 0:
184 # queue up everything after marker
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000185 next = line[marker+2:].lstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000186 self.cmdqueue.append(next)
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000187 line = line[:marker].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000188 return line
189
190 # Command definitions, called by cmdloop()
191 # The argument is the remaining string on the command line
192 # Return true to exit from the command loop
193
194 do_h = cmd.Cmd.do_help
195
Tim Peters2344fae2001-01-15 00:50:52 +0000196 def do_break(self, arg, temporary = 0):
197 # break [ ([filename:]lineno | function) [, "condition"] ]
198 if not arg:
199 if self.breaks: # There's at least one
200 print "Num Type Disp Enb Where"
201 for bp in bdb.Breakpoint.bpbynumber:
202 if bp:
203 bp.bpprint()
204 return
205 # parse arguments; comma has lowest precedence
206 # and cannot occur in filename
207 filename = None
208 lineno = None
209 cond = None
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000210 comma = arg.find(',')
Tim Peters2344fae2001-01-15 00:50:52 +0000211 if comma > 0:
212 # parse stuff after comma: "condition"
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000213 cond = arg[comma+1:].lstrip()
214 arg = arg[:comma].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000215 # parse stuff before comma: [filename:]lineno | function
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000216 colon = arg.rfind(':')
Tim Peters2344fae2001-01-15 00:50:52 +0000217 if colon >= 0:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000218 filename = arg[:colon].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000219 f = self.lookupmodule(filename)
220 if not f:
221 print '*** ', `filename`,
222 print 'not found from sys.path'
223 return
224 else:
225 filename = f
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000226 arg = arg[colon+1:].lstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000227 try:
228 lineno = int(arg)
229 except ValueError, msg:
230 print '*** Bad lineno:', arg
231 return
232 else:
233 # no colon; can be lineno or function
234 try:
235 lineno = int(arg)
236 except ValueError:
237 try:
238 func = eval(arg,
239 self.curframe.f_globals,
240 self.curframe.f_locals)
241 except:
242 func = arg
243 try:
244 if hasattr(func, 'im_func'):
245 func = func.im_func
246 code = func.func_code
247 lineno = code.co_firstlineno
248 filename = code.co_filename
249 except:
250 # last thing to try
251 (ok, filename, ln) = self.lineinfo(arg)
252 if not ok:
253 print '*** The specified object',
254 print `arg`,
255 print 'is not a function'
256 print ('or was not found '
257 'along sys.path.')
258 return
259 lineno = int(ln)
260 if not filename:
261 filename = self.defaultFile()
262 # Check for reasonable breakpoint
263 line = self.checkline(filename, lineno)
264 if line:
265 # now set the break point
266 err = self.set_break(filename, line, temporary, cond)
267 if err: print '***', err
268 else:
269 bp = self.get_breaks(filename, line)[-1]
270 print "Breakpoint %d at %s:%d" % (bp.number,
271 bp.file,
272 bp.line)
273
274 # To be overridden in derived debuggers
275 def defaultFile(self):
276 """Produce a reasonable default."""
277 filename = self.curframe.f_code.co_filename
278 if filename == '<string>' and mainpyfile:
279 filename = mainpyfile
280 return filename
281
282 do_b = do_break
283
284 def do_tbreak(self, arg):
285 self.do_break(arg, 1)
286
287 def lineinfo(self, identifier):
288 failed = (None, None, None)
289 # Input is identifier, may be in single quotes
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000290 idstring = identifier.split("'")
Tim Peters2344fae2001-01-15 00:50:52 +0000291 if len(idstring) == 1:
292 # not in single quotes
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000293 id = idstring[0].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000294 elif len(idstring) == 3:
295 # quoted
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000296 id = idstring[1].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000297 else:
298 return failed
299 if id == '': return failed
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000300 parts = id.split('.')
Tim Peters2344fae2001-01-15 00:50:52 +0000301 # Protection for derived debuggers
302 if parts[0] == 'self':
303 del parts[0]
304 if len(parts) == 0:
305 return failed
306 # Best first guess at file to look at
307 fname = self.defaultFile()
308 if len(parts) == 1:
309 item = parts[0]
310 else:
311 # More than one part.
312 # First is module, second is method/class
313 f = self.lookupmodule(parts[0])
314 if f:
315 fname = f
316 item = parts[1]
317 answer = find_function(item, fname)
318 return answer or failed
319
320 def checkline(self, filename, lineno):
321 """Return line number of first line at or after input
322 argument such that if the input points to a 'def', the
323 returned line number is the first
324 non-blank/non-comment line to follow. If the input
325 points to a blank or comment line, return 0. At end
326 of file, also return 0."""
327
328 line = linecache.getline(filename, lineno)
329 if not line:
330 print 'End of file'
331 return 0
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000332 line = line.strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000333 # Don't allow setting breakpoint at a blank line
Guido van Rossum08454592002-07-12 13:10:53 +0000334 if (not line or (line[0] == '#') or
335 (line[:3] == '"""') or line[:3] == "'''"):
Tim Peters2344fae2001-01-15 00:50:52 +0000336 print '*** Blank or comment'
337 return 0
338 # When a file is read in and a breakpoint is at
339 # the 'def' statement, the system stops there at
340 # code parse time. We don't want that, so all breakpoints
341 # set at 'def' statements are moved one line onward
342 if line[:3] == 'def':
343 instr = ''
344 brackets = 0
345 while 1:
346 skipone = 0
347 for c in line:
348 if instr:
349 if skipone:
350 skipone = 0
351 elif c == '\\':
352 skipone = 1
353 elif c == instr:
354 instr = ''
355 elif c == '#':
356 break
357 elif c in ('"',"'"):
358 instr = c
359 elif c in ('(','{','['):
360 brackets = brackets + 1
361 elif c in (')','}',']'):
362 brackets = brackets - 1
363 lineno = lineno+1
364 line = linecache.getline(filename, lineno)
365 if not line:
366 print 'end of file'
367 return 0
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000368 line = line.strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000369 if not line: continue # Blank line
370 if brackets <= 0 and line[0] not in ('#','"',"'"):
371 break
372 return lineno
373
374 def do_enable(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000375 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000376 for i in args:
377 bp = bdb.Breakpoint.bpbynumber[int(i)]
378 if bp:
379 bp.enable()
380
381 def do_disable(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000382 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000383 for i in args:
384 bp = bdb.Breakpoint.bpbynumber[int(i)]
385 if bp:
386 bp.disable()
387
388 def do_condition(self, arg):
389 # arg is breakpoint number and condition
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000390 args = arg.split(' ', 1)
391 bpnum = int(args[0].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000392 try:
393 cond = args[1]
394 except:
395 cond = None
396 bp = bdb.Breakpoint.bpbynumber[bpnum]
397 if bp:
398 bp.cond = cond
399 if not cond:
400 print 'Breakpoint', bpnum,
401 print 'is now unconditional.'
402
403 def do_ignore(self,arg):
404 """arg is bp number followed by ignore count."""
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000405 args = arg.split()
406 bpnum = int(args[0].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000407 try:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000408 count = int(args[1].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000409 except:
410 count = 0
411 bp = bdb.Breakpoint.bpbynumber[bpnum]
412 if bp:
413 bp.ignore = count
Guido van Rossum08454592002-07-12 13:10:53 +0000414 if count > 0:
Tim Peters2344fae2001-01-15 00:50:52 +0000415 reply = 'Will ignore next '
Guido van Rossum08454592002-07-12 13:10:53 +0000416 if count > 1:
Tim Peters2344fae2001-01-15 00:50:52 +0000417 reply = reply + '%d crossings' % count
418 else:
419 reply = reply + '1 crossing'
420 print reply + ' of breakpoint %d.' % bpnum
421 else:
422 print 'Will stop next time breakpoint',
423 print bpnum, 'is reached.'
424
425 def do_clear(self, arg):
426 """Three possibilities, tried in this order:
427 clear -> clear all breaks, ask for confirmation
428 clear file:lineno -> clear all breaks at file:lineno
429 clear bpno bpno ... -> clear breakpoints by number"""
430 if not arg:
431 try:
432 reply = raw_input('Clear all breaks? ')
433 except EOFError:
434 reply = 'no'
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000435 reply = reply.strip().lower()
Tim Peters2344fae2001-01-15 00:50:52 +0000436 if reply in ('y', 'yes'):
437 self.clear_all_breaks()
438 return
439 if ':' in arg:
440 # Make sure it works for "clear C:\foo\bar.py:12"
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000441 i = arg.rfind(':')
Tim Peters2344fae2001-01-15 00:50:52 +0000442 filename = arg[:i]
443 arg = arg[i+1:]
444 try:
445 lineno = int(arg)
446 except:
447 err = "Invalid line number (%s)" % arg
448 else:
449 err = self.clear_break(filename, lineno)
450 if err: print '***', err
451 return
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000452 numberlist = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000453 for i in numberlist:
454 err = self.clear_bpbynumber(i)
455 if err:
456 print '***', err
457 else:
458 print 'Deleted breakpoint %s ' % (i,)
459 do_cl = do_clear # 'c' is already an abbreviation for 'continue'
460
461 def do_where(self, arg):
462 self.print_stack_trace()
463 do_w = do_where
Guido van Rossum6bd68352001-01-20 17:57:37 +0000464 do_bt = do_where
Tim Peters2344fae2001-01-15 00:50:52 +0000465
466 def do_up(self, arg):
467 if self.curindex == 0:
468 print '*** Oldest frame'
469 else:
470 self.curindex = self.curindex - 1
471 self.curframe = self.stack[self.curindex][0]
472 self.print_stack_entry(self.stack[self.curindex])
473 self.lineno = None
474 do_u = do_up
475
476 def do_down(self, arg):
477 if self.curindex + 1 == len(self.stack):
478 print '*** Newest frame'
479 else:
480 self.curindex = self.curindex + 1
481 self.curframe = self.stack[self.curindex][0]
482 self.print_stack_entry(self.stack[self.curindex])
483 self.lineno = None
484 do_d = do_down
485
486 def do_step(self, arg):
487 self.set_step()
488 return 1
489 do_s = do_step
490
491 def do_next(self, arg):
492 self.set_next(self.curframe)
493 return 1
494 do_n = do_next
495
496 def do_return(self, arg):
497 self.set_return(self.curframe)
498 return 1
499 do_r = do_return
500
501 def do_continue(self, arg):
502 self.set_continue()
503 return 1
504 do_c = do_cont = do_continue
505
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000506 def do_jump(self, arg):
507 if self.curindex + 1 != len(self.stack):
508 print "*** You can only jump within the bottom frame"
509 return
510 try:
511 arg = int(arg)
512 except ValueError:
513 print "*** The 'jump' command requires a line number."
514 else:
515 try:
516 # Do the jump, fix up our copy of the stack, and display the
517 # new position
518 self.curframe.f_lineno = arg
519 self.stack[self.curindex] = self.stack[self.curindex][0], arg
520 self.print_stack_entry(self.stack[self.curindex])
521 except ValueError, e:
522 print '*** Jump failed:', e
523 do_j = do_jump
524
Tim Peters2344fae2001-01-15 00:50:52 +0000525 def do_quit(self, arg):
526 self.set_quit()
527 return 1
528 do_q = do_quit
Guido van Rossumd1c08f32002-04-15 00:48:24 +0000529 do_exit = do_quit
Tim Peters2344fae2001-01-15 00:50:52 +0000530
Guido van Rossumeef26072003-01-13 21:13:55 +0000531 def do_EOF(self, arg):
532 print
533 self.set_quit()
534 return 1
535
Tim Peters2344fae2001-01-15 00:50:52 +0000536 def do_args(self, arg):
537 f = self.curframe
538 co = f.f_code
539 dict = f.f_locals
540 n = co.co_argcount
541 if co.co_flags & 4: n = n+1
542 if co.co_flags & 8: n = n+1
543 for i in range(n):
544 name = co.co_varnames[i]
545 print name, '=',
Raymond Hettinger54f02222002-06-01 14:18:47 +0000546 if name in dict: print dict[name]
Tim Peters2344fae2001-01-15 00:50:52 +0000547 else: print "*** undefined ***"
548 do_a = do_args
Guido van Rossum2424f851998-09-11 22:50:09 +0000549
Tim Peters2344fae2001-01-15 00:50:52 +0000550 def do_retval(self, arg):
Raymond Hettinger54f02222002-06-01 14:18:47 +0000551 if '__return__' in self.curframe.f_locals:
Tim Peters2344fae2001-01-15 00:50:52 +0000552 print self.curframe.f_locals['__return__']
553 else:
554 print '*** Not yet returned!'
555 do_rv = do_retval
Guido van Rossum2424f851998-09-11 22:50:09 +0000556
Barry Warsaw210bd202002-11-05 22:40:20 +0000557 def _getval(self, arg):
Tim Peters2344fae2001-01-15 00:50:52 +0000558 try:
Barry Warsaw210bd202002-11-05 22:40:20 +0000559 return eval(arg, self.curframe.f_globals,
560 self.curframe.f_locals)
Tim Peters2344fae2001-01-15 00:50:52 +0000561 except:
562 t, v = sys.exc_info()[:2]
Barry Warsaw210bd202002-11-05 22:40:20 +0000563 if isinstance(t, str):
Tim Peters2344fae2001-01-15 00:50:52 +0000564 exc_type_name = t
565 else: exc_type_name = t.__name__
566 print '***', exc_type_name + ':', `v`
Barry Warsaw210bd202002-11-05 22:40:20 +0000567 raise
Guido van Rossum2424f851998-09-11 22:50:09 +0000568
Barry Warsaw210bd202002-11-05 22:40:20 +0000569 def do_p(self, arg):
570 try:
571 print repr(self._getval(arg))
572 except:
573 pass
574
575 def do_pp(self, arg):
576 try:
577 pprint.pprint(self._getval(arg))
578 except:
579 pass
Guido van Rossum2424f851998-09-11 22:50:09 +0000580
Tim Peters2344fae2001-01-15 00:50:52 +0000581 def do_list(self, arg):
582 self.lastcmd = 'list'
583 last = None
584 if arg:
585 try:
586 x = eval(arg, {}, {})
587 if type(x) == type(()):
588 first, last = x
589 first = int(first)
590 last = int(last)
591 if last < first:
592 # Assume it's a count
593 last = first + last
594 else:
595 first = max(1, int(x) - 5)
596 except:
597 print '*** Error in argument:', `arg`
598 return
599 elif self.lineno is None:
600 first = max(1, self.curframe.f_lineno - 5)
601 else:
602 first = self.lineno + 1
603 if last is None:
604 last = first + 10
605 filename = self.curframe.f_code.co_filename
606 breaklist = self.get_file_breaks(filename)
607 try:
608 for lineno in range(first, last+1):
609 line = linecache.getline(filename, lineno)
610 if not line:
611 print '[EOF]'
612 break
613 else:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000614 s = `lineno`.rjust(3)
Tim Peters2344fae2001-01-15 00:50:52 +0000615 if len(s) < 4: s = s + ' '
616 if lineno in breaklist: s = s + 'B'
617 else: s = s + ' '
618 if lineno == self.curframe.f_lineno:
619 s = s + '->'
620 print s + '\t' + line,
621 self.lineno = lineno
622 except KeyboardInterrupt:
623 pass
624 do_l = do_list
Guido van Rossum2424f851998-09-11 22:50:09 +0000625
Tim Peters2344fae2001-01-15 00:50:52 +0000626 def do_whatis(self, arg):
627 try:
628 value = eval(arg, self.curframe.f_globals,
629 self.curframe.f_locals)
630 except:
631 t, v = sys.exc_info()[:2]
632 if type(t) == type(''):
633 exc_type_name = t
634 else: exc_type_name = t.__name__
635 print '***', exc_type_name + ':', `v`
636 return
637 code = None
638 # Is it a function?
639 try: code = value.func_code
640 except: pass
641 if code:
642 print 'Function', code.co_name
643 return
644 # Is it an instance method?
645 try: code = value.im_func.func_code
646 except: pass
647 if code:
648 print 'Method', code.co_name
649 return
650 # None of the above...
651 print type(value)
Guido van Rossum8e2ec561993-07-29 09:37:38 +0000652
Tim Peters2344fae2001-01-15 00:50:52 +0000653 def do_alias(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000654 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000655 if len(args) == 0:
656 keys = self.aliases.keys()
657 keys.sort()
658 for alias in keys:
659 print "%s = %s" % (alias, self.aliases[alias])
660 return
Guido van Rossum08454592002-07-12 13:10:53 +0000661 if args[0] in self.aliases and len(args) == 1:
Tim Peters2344fae2001-01-15 00:50:52 +0000662 print "%s = %s" % (args[0], self.aliases[args[0]])
663 else:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000664 self.aliases[args[0]] = ' '.join(args[1:])
Guido van Rossum23efba41992-01-27 16:58:47 +0000665
Tim Peters2344fae2001-01-15 00:50:52 +0000666 def do_unalias(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000667 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000668 if len(args) == 0: return
Raymond Hettinger54f02222002-06-01 14:18:47 +0000669 if args[0] in self.aliases:
Tim Peters2344fae2001-01-15 00:50:52 +0000670 del self.aliases[args[0]]
Guido van Rossum00230781993-03-29 11:39:45 +0000671
Tim Peters2344fae2001-01-15 00:50:52 +0000672 # Print a traceback starting at the top stack frame.
673 # The most recently entered frame is printed last;
674 # this is different from dbx and gdb, but consistent with
675 # the Python interpreter's stack trace.
676 # It is also consistent with the up/down commands (which are
677 # compatible with dbx and gdb: up moves towards 'main()'
678 # and down moves towards the most recent stack frame).
Guido van Rossum2424f851998-09-11 22:50:09 +0000679
Tim Peters2344fae2001-01-15 00:50:52 +0000680 def print_stack_trace(self):
681 try:
682 for frame_lineno in self.stack:
683 self.print_stack_entry(frame_lineno)
684 except KeyboardInterrupt:
685 pass
Guido van Rossum2424f851998-09-11 22:50:09 +0000686
Tim Peters2344fae2001-01-15 00:50:52 +0000687 def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix):
688 frame, lineno = frame_lineno
689 if frame is self.curframe:
690 print '>',
691 else:
692 print ' ',
693 print self.format_stack_entry(frame_lineno, prompt_prefix)
Guido van Rossum2424f851998-09-11 22:50:09 +0000694
Guido van Rossum921c8241992-01-10 14:54:42 +0000695
Tim Peters2344fae2001-01-15 00:50:52 +0000696 # Help methods (derived from pdb.doc)
Guido van Rossum921c8241992-01-10 14:54:42 +0000697
Tim Peters2344fae2001-01-15 00:50:52 +0000698 def help_help(self):
699 self.help_h()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000700
Tim Peters2344fae2001-01-15 00:50:52 +0000701 def help_h(self):
702 print """h(elp)
703Without argument, print the list of available commands.
704With a command name as argument, print help about that command
705"help pdb" pipes the full documentation file to the $PAGER
706"help exec" gives help on the ! command"""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000707
Tim Peters2344fae2001-01-15 00:50:52 +0000708 def help_where(self):
709 self.help_w()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000710
Tim Peters2344fae2001-01-15 00:50:52 +0000711 def help_w(self):
712 print """w(here)
713Print a stack trace, with the most recent frame at the bottom.
714An arrow indicates the "current frame", which determines the
Guido van Rossum6bd68352001-01-20 17:57:37 +0000715context of most commands. 'bt' is an alias for this command."""
716
717 help_bt = help_w
Guido van Rossumb6775db1994-08-01 11:34:53 +0000718
Tim Peters2344fae2001-01-15 00:50:52 +0000719 def help_down(self):
720 self.help_d()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000721
Tim Peters2344fae2001-01-15 00:50:52 +0000722 def help_d(self):
723 print """d(own)
724Move the current frame one level down in the stack trace
725(to an older frame)."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000726
Tim Peters2344fae2001-01-15 00:50:52 +0000727 def help_up(self):
728 self.help_u()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000729
Tim Peters2344fae2001-01-15 00:50:52 +0000730 def help_u(self):
731 print """u(p)
732Move the current frame one level up in the stack trace
733(to a newer frame)."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000734
Tim Peters2344fae2001-01-15 00:50:52 +0000735 def help_break(self):
736 self.help_b()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000737
Tim Peters2344fae2001-01-15 00:50:52 +0000738 def help_b(self):
739 print """b(reak) ([file:]lineno | function) [, condition]
740With a line number argument, set a break there in the current
741file. With a function name, set a break at first executable line
742of that function. Without argument, list all breaks. If a second
743argument is present, it is a string specifying an expression
744which must evaluate to true before the breakpoint is honored.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000745
Tim Peters2344fae2001-01-15 00:50:52 +0000746The line number may be prefixed with a filename and a colon,
747to specify a breakpoint in another file (probably one that
748hasn't been loaded yet). The file is searched for on sys.path;
749the .py suffix may be omitted."""
Guido van Rossumb5699c71998-07-20 23:13:54 +0000750
Tim Peters2344fae2001-01-15 00:50:52 +0000751 def help_clear(self):
752 self.help_cl()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000753
Tim Peters2344fae2001-01-15 00:50:52 +0000754 def help_cl(self):
755 print "cl(ear) filename:lineno"
756 print """cl(ear) [bpnumber [bpnumber...]]
757With a space separated list of breakpoint numbers, clear
758those breakpoints. Without argument, clear all breaks (but
759first ask confirmation). With a filename:lineno argument,
760clear all breaks at that line in that file.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000761
Tim Peters2344fae2001-01-15 00:50:52 +0000762Note that the argument is different from previous versions of
763the debugger (in python distributions 1.5.1 and before) where
764a linenumber was used instead of either filename:lineno or
765breakpoint numbers."""
Guido van Rossumb5699c71998-07-20 23:13:54 +0000766
Tim Peters2344fae2001-01-15 00:50:52 +0000767 def help_tbreak(self):
768 print """tbreak same arguments as break, but breakpoint is
769removed when first hit."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000770
Tim Peters2344fae2001-01-15 00:50:52 +0000771 def help_enable(self):
772 print """enable bpnumber [bpnumber ...]
773Enables the breakpoints given as a space separated list of
774bp numbers."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000775
Tim Peters2344fae2001-01-15 00:50:52 +0000776 def help_disable(self):
777 print """disable bpnumber [bpnumber ...]
778Disables the breakpoints given as a space separated list of
779bp numbers."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000780
Tim Peters2344fae2001-01-15 00:50:52 +0000781 def help_ignore(self):
782 print """ignore bpnumber count
783Sets the ignore count for the given breakpoint number. A breakpoint
784becomes active when the ignore count is zero. When non-zero, the
785count is decremented each time the breakpoint is reached and the
786breakpoint is not disabled and any associated condition evaluates
787to true."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000788
Tim Peters2344fae2001-01-15 00:50:52 +0000789 def help_condition(self):
790 print """condition bpnumber str_condition
791str_condition is a string specifying an expression which
792must evaluate to true before the breakpoint is honored.
793If str_condition is absent, any existing condition is removed;
794i.e., the breakpoint is made unconditional."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000795
Tim Peters2344fae2001-01-15 00:50:52 +0000796 def help_step(self):
797 self.help_s()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000798
Tim Peters2344fae2001-01-15 00:50:52 +0000799 def help_s(self):
800 print """s(tep)
801Execute the current line, stop at the first possible occasion
802(either in a function that is called or in the current function)."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000803
Tim Peters2344fae2001-01-15 00:50:52 +0000804 def help_next(self):
805 self.help_n()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000806
Tim Peters2344fae2001-01-15 00:50:52 +0000807 def help_n(self):
808 print """n(ext)
809Continue execution until the next line in the current function
810is reached or it returns."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000811
Tim Peters2344fae2001-01-15 00:50:52 +0000812 def help_return(self):
813 self.help_r()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000814
Tim Peters2344fae2001-01-15 00:50:52 +0000815 def help_r(self):
816 print """r(eturn)
817Continue execution until the current function returns."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000818
Tim Peters2344fae2001-01-15 00:50:52 +0000819 def help_continue(self):
820 self.help_c()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000821
Tim Peters2344fae2001-01-15 00:50:52 +0000822 def help_cont(self):
823 self.help_c()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000824
Tim Peters2344fae2001-01-15 00:50:52 +0000825 def help_c(self):
826 print """c(ont(inue))
827Continue execution, only stop when a breakpoint is encountered."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000828
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000829 def help_jump(self):
830 self.help_j()
831
832 def help_j(self):
833 print """j(ump) lineno
834Set the next line that will be executed."""
835
Tim Peters2344fae2001-01-15 00:50:52 +0000836 def help_list(self):
837 self.help_l()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000838
Tim Peters2344fae2001-01-15 00:50:52 +0000839 def help_l(self):
840 print """l(ist) [first [,last]]
841List source code for the current file.
842Without arguments, list 11 lines around the current line
843or continue the previous listing.
844With one argument, list 11 lines starting at that line.
845With two arguments, list the given range;
846if the second argument is less than the first, it is a count."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000847
Tim Peters2344fae2001-01-15 00:50:52 +0000848 def help_args(self):
849 self.help_a()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000850
Tim Peters2344fae2001-01-15 00:50:52 +0000851 def help_a(self):
852 print """a(rgs)
853Print the arguments of the current function."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000854
Tim Peters2344fae2001-01-15 00:50:52 +0000855 def help_p(self):
856 print """p expression
857Print the value of the expression."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000858
Barry Warsaw210bd202002-11-05 22:40:20 +0000859 def help_pp(self):
860 print """pp expression
861Pretty-print the value of the expression."""
862
Tim Peters2344fae2001-01-15 00:50:52 +0000863 def help_exec(self):
864 print """(!) statement
865Execute the (one-line) statement in the context of
866the current stack frame.
867The exclamation point can be omitted unless the first word
868of the statement resembles a debugger command.
869To assign to a global variable you must always prefix the
870command with a 'global' command, e.g.:
871(Pdb) global list_options; list_options = ['-l']
872(Pdb)"""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000873
Tim Peters2344fae2001-01-15 00:50:52 +0000874 def help_quit(self):
875 self.help_q()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000876
Tim Peters2344fae2001-01-15 00:50:52 +0000877 def help_q(self):
Guido van Rossumd1c08f32002-04-15 00:48:24 +0000878 print """q(uit) or exit - Quit from the debugger.
Tim Peters2344fae2001-01-15 00:50:52 +0000879The program being executed is aborted."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000880
Guido van Rossumd1c08f32002-04-15 00:48:24 +0000881 help_exit = help_q
882
Tim Peters2344fae2001-01-15 00:50:52 +0000883 def help_whatis(self):
884 print """whatis arg
885Prints the type of the argument."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000886
Tim Peters2344fae2001-01-15 00:50:52 +0000887 def help_EOF(self):
888 print """EOF
889Handles the receipt of EOF as a command."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000890
Tim Peters2344fae2001-01-15 00:50:52 +0000891 def help_alias(self):
892 print """alias [name [command [parameter parameter ...] ]]
893Creates an alias called 'name' the executes 'command'. The command
894must *not* be enclosed in quotes. Replaceable parameters are
895indicated by %1, %2, and so on, while %* is replaced by all the
896parameters. If no command is given, the current alias for name
897is shown. If no name is given, all aliases are listed.
Guido van Rossum2424f851998-09-11 22:50:09 +0000898
Tim Peters2344fae2001-01-15 00:50:52 +0000899Aliases may be nested and can contain anything that can be
900legally typed at the pdb prompt. Note! You *can* override
901internal pdb commands with aliases! Those internal commands
902are then hidden until the alias is removed. Aliasing is recursively
903applied to the first word of the command line; all other words
904in the line are left alone.
Guido van Rossum2424f851998-09-11 22:50:09 +0000905
Tim Peters2344fae2001-01-15 00:50:52 +0000906Some useful aliases (especially when placed in the .pdbrc file) are:
Guido van Rossum2424f851998-09-11 22:50:09 +0000907
Tim Peters2344fae2001-01-15 00:50:52 +0000908#Print instance variables (usage "pi classInst")
909alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
Guido van Rossum2424f851998-09-11 22:50:09 +0000910
Tim Peters2344fae2001-01-15 00:50:52 +0000911#Print instance variables in self
912alias ps pi self
913"""
Guido van Rossum2424f851998-09-11 22:50:09 +0000914
Tim Peters2344fae2001-01-15 00:50:52 +0000915 def help_unalias(self):
916 print """unalias name
917Deletes the specified alias."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000918
Tim Peters2344fae2001-01-15 00:50:52 +0000919 def help_pdb(self):
920 help()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000921
Tim Peters2344fae2001-01-15 00:50:52 +0000922 def lookupmodule(self, filename):
923 """Helper function for break/clear parsing -- may be overridden."""
924 root, ext = os.path.splitext(filename)
925 if ext == '':
926 filename = filename + '.py'
927 if os.path.isabs(filename):
928 return filename
929 for dirname in sys.path:
930 while os.path.islink(dirname):
931 dirname = os.readlink(dirname)
932 fullname = os.path.join(dirname, filename)
933 if os.path.exists(fullname):
934 return fullname
935 return None
Guido van Rossumb5699c71998-07-20 23:13:54 +0000936
Guido van Rossum35771131992-09-08 11:59:04 +0000937# Simplified interface
938
Guido van Rossum5e38b6f1995-02-27 13:13:40 +0000939def run(statement, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +0000940 Pdb().run(statement, globals, locals)
Guido van Rossum5e38b6f1995-02-27 13:13:40 +0000941
942def runeval(expression, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +0000943 return Pdb().runeval(expression, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000944
945def runctx(statement, globals, locals):
Tim Peters2344fae2001-01-15 00:50:52 +0000946 # B/W compatibility
947 run(statement, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000948
Guido van Rossum4e160981992-09-02 20:43:20 +0000949def runcall(*args):
Tim Peters2344fae2001-01-15 00:50:52 +0000950 return apply(Pdb().runcall, args)
Guido van Rossum4e160981992-09-02 20:43:20 +0000951
Guido van Rossumb6775db1994-08-01 11:34:53 +0000952def set_trace():
Tim Peters2344fae2001-01-15 00:50:52 +0000953 Pdb().set_trace()
Guido van Rossum35771131992-09-08 11:59:04 +0000954
955# Post-Mortem interface
956
957def post_mortem(t):
Tim Peters2344fae2001-01-15 00:50:52 +0000958 p = Pdb()
959 p.reset()
960 while t.tb_next is not None:
961 t = t.tb_next
962 p.interaction(t.tb_frame, t)
Guido van Rossum35771131992-09-08 11:59:04 +0000963
964def pm():
Tim Peters2344fae2001-01-15 00:50:52 +0000965 post_mortem(sys.last_traceback)
Guido van Rossum35771131992-09-08 11:59:04 +0000966
967
968# Main program for testing
969
Guido van Rossum23efba41992-01-27 16:58:47 +0000970TESTCMD = 'import x; x.main()'
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000971
Guido van Rossum921c8241992-01-10 14:54:42 +0000972def test():
Tim Peters2344fae2001-01-15 00:50:52 +0000973 run(TESTCMD)
Guido van Rossume61fa0a1993-10-22 13:56:35 +0000974
975# print help
976def help():
Tim Peters2344fae2001-01-15 00:50:52 +0000977 for dirname in sys.path:
978 fullname = os.path.join(dirname, 'pdb.doc')
979 if os.path.exists(fullname):
980 sts = os.system('${PAGER-more} '+fullname)
981 if sts: print '*** Pager exit status:', sts
982 break
983 else:
984 print 'Sorry, can\'t find the help file "pdb.doc"',
985 print 'along the Python search path'
Guido van Rossumf17361d1996-07-30 16:28:13 +0000986
Guido van Rossumb5699c71998-07-20 23:13:54 +0000987mainmodule = ''
988mainpyfile = ''
989
Guido van Rossumf17361d1996-07-30 16:28:13 +0000990# When invoked as main program, invoke the debugger on a script
991if __name__=='__main__':
Tim Peters2344fae2001-01-15 00:50:52 +0000992 if not sys.argv[1:]:
993 print "usage: pdb.py scriptfile [arg] ..."
994 sys.exit(2)
Guido van Rossumf17361d1996-07-30 16:28:13 +0000995
Tim Peters2344fae2001-01-15 00:50:52 +0000996 mainpyfile = filename = sys.argv[1] # Get script filename
997 if not os.path.exists(filename):
998 print 'Error:', `filename`, 'does not exist'
999 sys.exit(1)
1000 mainmodule = os.path.basename(filename)
1001 del sys.argv[0] # Hide "pdb.py" from argument list
Guido van Rossumec577d51996-09-10 17:39:34 +00001002
Tim Peters2344fae2001-01-15 00:50:52 +00001003 # Insert script directory in front of module search path
1004 sys.path.insert(0, os.path.dirname(filename))
Guido van Rossumf17361d1996-07-30 16:28:13 +00001005
Tim Peters2344fae2001-01-15 00:50:52 +00001006 run('execfile(' + `filename` + ')')