blob: fffd0ad3b8ff6fd660ebdef54d75e0eb8d0f8c50 [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
196 def do_EOF(self, arg):
197 return 0 # Don't die on EOF
198
199 def do_break(self, arg, temporary = 0):
200 # break [ ([filename:]lineno | function) [, "condition"] ]
201 if not arg:
202 if self.breaks: # There's at least one
203 print "Num Type Disp Enb Where"
204 for bp in bdb.Breakpoint.bpbynumber:
205 if bp:
206 bp.bpprint()
207 return
208 # parse arguments; comma has lowest precedence
209 # and cannot occur in filename
210 filename = None
211 lineno = None
212 cond = None
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000213 comma = arg.find(',')
Tim Peters2344fae2001-01-15 00:50:52 +0000214 if comma > 0:
215 # parse stuff after comma: "condition"
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000216 cond = arg[comma+1:].lstrip()
217 arg = arg[:comma].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000218 # parse stuff before comma: [filename:]lineno | function
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000219 colon = arg.rfind(':')
Tim Peters2344fae2001-01-15 00:50:52 +0000220 if colon >= 0:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000221 filename = arg[:colon].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000222 f = self.lookupmodule(filename)
223 if not f:
224 print '*** ', `filename`,
225 print 'not found from sys.path'
226 return
227 else:
228 filename = f
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000229 arg = arg[colon+1:].lstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000230 try:
231 lineno = int(arg)
232 except ValueError, msg:
233 print '*** Bad lineno:', arg
234 return
235 else:
236 # no colon; can be lineno or function
237 try:
238 lineno = int(arg)
239 except ValueError:
240 try:
241 func = eval(arg,
242 self.curframe.f_globals,
243 self.curframe.f_locals)
244 except:
245 func = arg
246 try:
247 if hasattr(func, 'im_func'):
248 func = func.im_func
249 code = func.func_code
250 lineno = code.co_firstlineno
251 filename = code.co_filename
252 except:
253 # last thing to try
254 (ok, filename, ln) = self.lineinfo(arg)
255 if not ok:
256 print '*** The specified object',
257 print `arg`,
258 print 'is not a function'
259 print ('or was not found '
260 'along sys.path.')
261 return
262 lineno = int(ln)
263 if not filename:
264 filename = self.defaultFile()
265 # Check for reasonable breakpoint
266 line = self.checkline(filename, lineno)
267 if line:
268 # now set the break point
269 err = self.set_break(filename, line, temporary, cond)
270 if err: print '***', err
271 else:
272 bp = self.get_breaks(filename, line)[-1]
273 print "Breakpoint %d at %s:%d" % (bp.number,
274 bp.file,
275 bp.line)
276
277 # To be overridden in derived debuggers
278 def defaultFile(self):
279 """Produce a reasonable default."""
280 filename = self.curframe.f_code.co_filename
281 if filename == '<string>' and mainpyfile:
282 filename = mainpyfile
283 return filename
284
285 do_b = do_break
286
287 def do_tbreak(self, arg):
288 self.do_break(arg, 1)
289
290 def lineinfo(self, identifier):
291 failed = (None, None, None)
292 # Input is identifier, may be in single quotes
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000293 idstring = identifier.split("'")
Tim Peters2344fae2001-01-15 00:50:52 +0000294 if len(idstring) == 1:
295 # not in single quotes
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000296 id = idstring[0].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000297 elif len(idstring) == 3:
298 # quoted
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000299 id = idstring[1].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000300 else:
301 return failed
302 if id == '': return failed
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000303 parts = id.split('.')
Tim Peters2344fae2001-01-15 00:50:52 +0000304 # Protection for derived debuggers
305 if parts[0] == 'self':
306 del parts[0]
307 if len(parts) == 0:
308 return failed
309 # Best first guess at file to look at
310 fname = self.defaultFile()
311 if len(parts) == 1:
312 item = parts[0]
313 else:
314 # More than one part.
315 # First is module, second is method/class
316 f = self.lookupmodule(parts[0])
317 if f:
318 fname = f
319 item = parts[1]
320 answer = find_function(item, fname)
321 return answer or failed
322
323 def checkline(self, filename, lineno):
324 """Return line number of first line at or after input
325 argument such that if the input points to a 'def', the
326 returned line number is the first
327 non-blank/non-comment line to follow. If the input
328 points to a blank or comment line, return 0. At end
329 of file, also return 0."""
330
331 line = linecache.getline(filename, lineno)
332 if not line:
333 print 'End of file'
334 return 0
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000335 line = line.strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000336 # Don't allow setting breakpoint at a blank line
Guido van Rossum08454592002-07-12 13:10:53 +0000337 if (not line or (line[0] == '#') or
338 (line[:3] == '"""') or line[:3] == "'''"):
Tim Peters2344fae2001-01-15 00:50:52 +0000339 print '*** Blank or comment'
340 return 0
341 # When a file is read in and a breakpoint is at
342 # the 'def' statement, the system stops there at
343 # code parse time. We don't want that, so all breakpoints
344 # set at 'def' statements are moved one line onward
345 if line[:3] == 'def':
346 instr = ''
347 brackets = 0
348 while 1:
349 skipone = 0
350 for c in line:
351 if instr:
352 if skipone:
353 skipone = 0
354 elif c == '\\':
355 skipone = 1
356 elif c == instr:
357 instr = ''
358 elif c == '#':
359 break
360 elif c in ('"',"'"):
361 instr = c
362 elif c in ('(','{','['):
363 brackets = brackets + 1
364 elif c in (')','}',']'):
365 brackets = brackets - 1
366 lineno = lineno+1
367 line = linecache.getline(filename, lineno)
368 if not line:
369 print 'end of file'
370 return 0
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000371 line = line.strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000372 if not line: continue # Blank line
373 if brackets <= 0 and line[0] not in ('#','"',"'"):
374 break
375 return lineno
376
377 def do_enable(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000378 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000379 for i in args:
380 bp = bdb.Breakpoint.bpbynumber[int(i)]
381 if bp:
382 bp.enable()
383
384 def do_disable(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000385 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000386 for i in args:
387 bp = bdb.Breakpoint.bpbynumber[int(i)]
388 if bp:
389 bp.disable()
390
391 def do_condition(self, arg):
392 # arg is breakpoint number and condition
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000393 args = arg.split(' ', 1)
394 bpnum = int(args[0].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000395 try:
396 cond = args[1]
397 except:
398 cond = None
399 bp = bdb.Breakpoint.bpbynumber[bpnum]
400 if bp:
401 bp.cond = cond
402 if not cond:
403 print 'Breakpoint', bpnum,
404 print 'is now unconditional.'
405
406 def do_ignore(self,arg):
407 """arg is bp number followed by ignore count."""
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000408 args = arg.split()
409 bpnum = int(args[0].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000410 try:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000411 count = int(args[1].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000412 except:
413 count = 0
414 bp = bdb.Breakpoint.bpbynumber[bpnum]
415 if bp:
416 bp.ignore = count
Guido van Rossum08454592002-07-12 13:10:53 +0000417 if count > 0:
Tim Peters2344fae2001-01-15 00:50:52 +0000418 reply = 'Will ignore next '
Guido van Rossum08454592002-07-12 13:10:53 +0000419 if count > 1:
Tim Peters2344fae2001-01-15 00:50:52 +0000420 reply = reply + '%d crossings' % count
421 else:
422 reply = reply + '1 crossing'
423 print reply + ' of breakpoint %d.' % bpnum
424 else:
425 print 'Will stop next time breakpoint',
426 print bpnum, 'is reached.'
427
428 def do_clear(self, arg):
429 """Three possibilities, tried in this order:
430 clear -> clear all breaks, ask for confirmation
431 clear file:lineno -> clear all breaks at file:lineno
432 clear bpno bpno ... -> clear breakpoints by number"""
433 if not arg:
434 try:
435 reply = raw_input('Clear all breaks? ')
436 except EOFError:
437 reply = 'no'
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000438 reply = reply.strip().lower()
Tim Peters2344fae2001-01-15 00:50:52 +0000439 if reply in ('y', 'yes'):
440 self.clear_all_breaks()
441 return
442 if ':' in arg:
443 # Make sure it works for "clear C:\foo\bar.py:12"
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000444 i = arg.rfind(':')
Tim Peters2344fae2001-01-15 00:50:52 +0000445 filename = arg[:i]
446 arg = arg[i+1:]
447 try:
448 lineno = int(arg)
449 except:
450 err = "Invalid line number (%s)" % arg
451 else:
452 err = self.clear_break(filename, lineno)
453 if err: print '***', err
454 return
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000455 numberlist = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000456 for i in numberlist:
457 err = self.clear_bpbynumber(i)
458 if err:
459 print '***', err
460 else:
461 print 'Deleted breakpoint %s ' % (i,)
462 do_cl = do_clear # 'c' is already an abbreviation for 'continue'
463
464 def do_where(self, arg):
465 self.print_stack_trace()
466 do_w = do_where
Guido van Rossum6bd68352001-01-20 17:57:37 +0000467 do_bt = do_where
Tim Peters2344fae2001-01-15 00:50:52 +0000468
469 def do_up(self, arg):
470 if self.curindex == 0:
471 print '*** Oldest frame'
472 else:
473 self.curindex = self.curindex - 1
474 self.curframe = self.stack[self.curindex][0]
475 self.print_stack_entry(self.stack[self.curindex])
476 self.lineno = None
477 do_u = do_up
478
479 def do_down(self, arg):
480 if self.curindex + 1 == len(self.stack):
481 print '*** Newest frame'
482 else:
483 self.curindex = self.curindex + 1
484 self.curframe = self.stack[self.curindex][0]
485 self.print_stack_entry(self.stack[self.curindex])
486 self.lineno = None
487 do_d = do_down
488
489 def do_step(self, arg):
490 self.set_step()
491 return 1
492 do_s = do_step
493
494 def do_next(self, arg):
495 self.set_next(self.curframe)
496 return 1
497 do_n = do_next
498
499 def do_return(self, arg):
500 self.set_return(self.curframe)
501 return 1
502 do_r = do_return
503
504 def do_continue(self, arg):
505 self.set_continue()
506 return 1
507 do_c = do_cont = do_continue
508
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000509 def do_jump(self, arg):
510 if self.curindex + 1 != len(self.stack):
511 print "*** You can only jump within the bottom frame"
512 return
513 try:
514 arg = int(arg)
515 except ValueError:
516 print "*** The 'jump' command requires a line number."
517 else:
518 try:
519 # Do the jump, fix up our copy of the stack, and display the
520 # new position
521 self.curframe.f_lineno = arg
522 self.stack[self.curindex] = self.stack[self.curindex][0], arg
523 self.print_stack_entry(self.stack[self.curindex])
524 except ValueError, e:
525 print '*** Jump failed:', e
526 do_j = do_jump
527
Tim Peters2344fae2001-01-15 00:50:52 +0000528 def do_quit(self, arg):
529 self.set_quit()
530 return 1
531 do_q = do_quit
Guido van Rossumd1c08f32002-04-15 00:48:24 +0000532 do_exit = do_quit
Tim Peters2344fae2001-01-15 00:50:52 +0000533
534 def do_args(self, arg):
535 f = self.curframe
536 co = f.f_code
537 dict = f.f_locals
538 n = co.co_argcount
539 if co.co_flags & 4: n = n+1
540 if co.co_flags & 8: n = n+1
541 for i in range(n):
542 name = co.co_varnames[i]
543 print name, '=',
Raymond Hettinger54f02222002-06-01 14:18:47 +0000544 if name in dict: print dict[name]
Tim Peters2344fae2001-01-15 00:50:52 +0000545 else: print "*** undefined ***"
546 do_a = do_args
Guido van Rossum2424f851998-09-11 22:50:09 +0000547
Tim Peters2344fae2001-01-15 00:50:52 +0000548 def do_retval(self, arg):
Raymond Hettinger54f02222002-06-01 14:18:47 +0000549 if '__return__' in self.curframe.f_locals:
Tim Peters2344fae2001-01-15 00:50:52 +0000550 print self.curframe.f_locals['__return__']
551 else:
552 print '*** Not yet returned!'
553 do_rv = do_retval
Guido van Rossum2424f851998-09-11 22:50:09 +0000554
Barry Warsaw210bd202002-11-05 22:40:20 +0000555 def _getval(self, arg):
Tim Peters2344fae2001-01-15 00:50:52 +0000556 try:
Barry Warsaw210bd202002-11-05 22:40:20 +0000557 return eval(arg, self.curframe.f_globals,
558 self.curframe.f_locals)
Tim Peters2344fae2001-01-15 00:50:52 +0000559 except:
560 t, v = sys.exc_info()[:2]
Barry Warsaw210bd202002-11-05 22:40:20 +0000561 if isinstance(t, str):
Tim Peters2344fae2001-01-15 00:50:52 +0000562 exc_type_name = t
563 else: exc_type_name = t.__name__
564 print '***', exc_type_name + ':', `v`
Barry Warsaw210bd202002-11-05 22:40:20 +0000565 raise
Guido van Rossum2424f851998-09-11 22:50:09 +0000566
Barry Warsaw210bd202002-11-05 22:40:20 +0000567 def do_p(self, arg):
568 try:
569 print repr(self._getval(arg))
570 except:
571 pass
572
573 def do_pp(self, arg):
574 try:
575 pprint.pprint(self._getval(arg))
576 except:
577 pass
Guido van Rossum2424f851998-09-11 22:50:09 +0000578
Tim Peters2344fae2001-01-15 00:50:52 +0000579 def do_list(self, arg):
580 self.lastcmd = 'list'
581 last = None
582 if arg:
583 try:
584 x = eval(arg, {}, {})
585 if type(x) == type(()):
586 first, last = x
587 first = int(first)
588 last = int(last)
589 if last < first:
590 # Assume it's a count
591 last = first + last
592 else:
593 first = max(1, int(x) - 5)
594 except:
595 print '*** Error in argument:', `arg`
596 return
597 elif self.lineno is None:
598 first = max(1, self.curframe.f_lineno - 5)
599 else:
600 first = self.lineno + 1
601 if last is None:
602 last = first + 10
603 filename = self.curframe.f_code.co_filename
604 breaklist = self.get_file_breaks(filename)
605 try:
606 for lineno in range(first, last+1):
607 line = linecache.getline(filename, lineno)
608 if not line:
609 print '[EOF]'
610 break
611 else:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000612 s = `lineno`.rjust(3)
Tim Peters2344fae2001-01-15 00:50:52 +0000613 if len(s) < 4: s = s + ' '
614 if lineno in breaklist: s = s + 'B'
615 else: s = s + ' '
616 if lineno == self.curframe.f_lineno:
617 s = s + '->'
618 print s + '\t' + line,
619 self.lineno = lineno
620 except KeyboardInterrupt:
621 pass
622 do_l = do_list
Guido van Rossum2424f851998-09-11 22:50:09 +0000623
Tim Peters2344fae2001-01-15 00:50:52 +0000624 def do_whatis(self, arg):
625 try:
626 value = eval(arg, self.curframe.f_globals,
627 self.curframe.f_locals)
628 except:
629 t, v = sys.exc_info()[:2]
630 if type(t) == type(''):
631 exc_type_name = t
632 else: exc_type_name = t.__name__
633 print '***', exc_type_name + ':', `v`
634 return
635 code = None
636 # Is it a function?
637 try: code = value.func_code
638 except: pass
639 if code:
640 print 'Function', code.co_name
641 return
642 # Is it an instance method?
643 try: code = value.im_func.func_code
644 except: pass
645 if code:
646 print 'Method', code.co_name
647 return
648 # None of the above...
649 print type(value)
Guido van Rossum8e2ec561993-07-29 09:37:38 +0000650
Tim Peters2344fae2001-01-15 00:50:52 +0000651 def do_alias(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000652 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000653 if len(args) == 0:
654 keys = self.aliases.keys()
655 keys.sort()
656 for alias in keys:
657 print "%s = %s" % (alias, self.aliases[alias])
658 return
Guido van Rossum08454592002-07-12 13:10:53 +0000659 if args[0] in self.aliases and len(args) == 1:
Tim Peters2344fae2001-01-15 00:50:52 +0000660 print "%s = %s" % (args[0], self.aliases[args[0]])
661 else:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000662 self.aliases[args[0]] = ' '.join(args[1:])
Guido van Rossum23efba41992-01-27 16:58:47 +0000663
Tim Peters2344fae2001-01-15 00:50:52 +0000664 def do_unalias(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000665 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000666 if len(args) == 0: return
Raymond Hettinger54f02222002-06-01 14:18:47 +0000667 if args[0] in self.aliases:
Tim Peters2344fae2001-01-15 00:50:52 +0000668 del self.aliases[args[0]]
Guido van Rossum00230781993-03-29 11:39:45 +0000669
Tim Peters2344fae2001-01-15 00:50:52 +0000670 # Print a traceback starting at the top stack frame.
671 # The most recently entered frame is printed last;
672 # this is different from dbx and gdb, but consistent with
673 # the Python interpreter's stack trace.
674 # It is also consistent with the up/down commands (which are
675 # compatible with dbx and gdb: up moves towards 'main()'
676 # and down moves towards the most recent stack frame).
Guido van Rossum2424f851998-09-11 22:50:09 +0000677
Tim Peters2344fae2001-01-15 00:50:52 +0000678 def print_stack_trace(self):
679 try:
680 for frame_lineno in self.stack:
681 self.print_stack_entry(frame_lineno)
682 except KeyboardInterrupt:
683 pass
Guido van Rossum2424f851998-09-11 22:50:09 +0000684
Tim Peters2344fae2001-01-15 00:50:52 +0000685 def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix):
686 frame, lineno = frame_lineno
687 if frame is self.curframe:
688 print '>',
689 else:
690 print ' ',
691 print self.format_stack_entry(frame_lineno, prompt_prefix)
Guido van Rossum2424f851998-09-11 22:50:09 +0000692
Guido van Rossum921c8241992-01-10 14:54:42 +0000693
Tim Peters2344fae2001-01-15 00:50:52 +0000694 # Help methods (derived from pdb.doc)
Guido van Rossum921c8241992-01-10 14:54:42 +0000695
Tim Peters2344fae2001-01-15 00:50:52 +0000696 def help_help(self):
697 self.help_h()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000698
Tim Peters2344fae2001-01-15 00:50:52 +0000699 def help_h(self):
700 print """h(elp)
701Without argument, print the list of available commands.
702With a command name as argument, print help about that command
703"help pdb" pipes the full documentation file to the $PAGER
704"help exec" gives help on the ! command"""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000705
Tim Peters2344fae2001-01-15 00:50:52 +0000706 def help_where(self):
707 self.help_w()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000708
Tim Peters2344fae2001-01-15 00:50:52 +0000709 def help_w(self):
710 print """w(here)
711Print a stack trace, with the most recent frame at the bottom.
712An arrow indicates the "current frame", which determines the
Guido van Rossum6bd68352001-01-20 17:57:37 +0000713context of most commands. 'bt' is an alias for this command."""
714
715 help_bt = help_w
Guido van Rossumb6775db1994-08-01 11:34:53 +0000716
Tim Peters2344fae2001-01-15 00:50:52 +0000717 def help_down(self):
718 self.help_d()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000719
Tim Peters2344fae2001-01-15 00:50:52 +0000720 def help_d(self):
721 print """d(own)
722Move the current frame one level down in the stack trace
723(to an older frame)."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000724
Tim Peters2344fae2001-01-15 00:50:52 +0000725 def help_up(self):
726 self.help_u()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000727
Tim Peters2344fae2001-01-15 00:50:52 +0000728 def help_u(self):
729 print """u(p)
730Move the current frame one level up in the stack trace
731(to a newer frame)."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000732
Tim Peters2344fae2001-01-15 00:50:52 +0000733 def help_break(self):
734 self.help_b()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000735
Tim Peters2344fae2001-01-15 00:50:52 +0000736 def help_b(self):
737 print """b(reak) ([file:]lineno | function) [, condition]
738With a line number argument, set a break there in the current
739file. With a function name, set a break at first executable line
740of that function. Without argument, list all breaks. If a second
741argument is present, it is a string specifying an expression
742which must evaluate to true before the breakpoint is honored.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000743
Tim Peters2344fae2001-01-15 00:50:52 +0000744The line number may be prefixed with a filename and a colon,
745to specify a breakpoint in another file (probably one that
746hasn't been loaded yet). The file is searched for on sys.path;
747the .py suffix may be omitted."""
Guido van Rossumb5699c71998-07-20 23:13:54 +0000748
Tim Peters2344fae2001-01-15 00:50:52 +0000749 def help_clear(self):
750 self.help_cl()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000751
Tim Peters2344fae2001-01-15 00:50:52 +0000752 def help_cl(self):
753 print "cl(ear) filename:lineno"
754 print """cl(ear) [bpnumber [bpnumber...]]
755With a space separated list of breakpoint numbers, clear
756those breakpoints. Without argument, clear all breaks (but
757first ask confirmation). With a filename:lineno argument,
758clear all breaks at that line in that file.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000759
Tim Peters2344fae2001-01-15 00:50:52 +0000760Note that the argument is different from previous versions of
761the debugger (in python distributions 1.5.1 and before) where
762a linenumber was used instead of either filename:lineno or
763breakpoint numbers."""
Guido van Rossumb5699c71998-07-20 23:13:54 +0000764
Tim Peters2344fae2001-01-15 00:50:52 +0000765 def help_tbreak(self):
766 print """tbreak same arguments as break, but breakpoint is
767removed when first hit."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000768
Tim Peters2344fae2001-01-15 00:50:52 +0000769 def help_enable(self):
770 print """enable bpnumber [bpnumber ...]
771Enables the breakpoints given as a space separated list of
772bp numbers."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000773
Tim Peters2344fae2001-01-15 00:50:52 +0000774 def help_disable(self):
775 print """disable bpnumber [bpnumber ...]
776Disables the breakpoints given as a space separated list of
777bp numbers."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000778
Tim Peters2344fae2001-01-15 00:50:52 +0000779 def help_ignore(self):
780 print """ignore bpnumber count
781Sets the ignore count for the given breakpoint number. A breakpoint
782becomes active when the ignore count is zero. When non-zero, the
783count is decremented each time the breakpoint is reached and the
784breakpoint is not disabled and any associated condition evaluates
785to true."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000786
Tim Peters2344fae2001-01-15 00:50:52 +0000787 def help_condition(self):
788 print """condition bpnumber str_condition
789str_condition is a string specifying an expression which
790must evaluate to true before the breakpoint is honored.
791If str_condition is absent, any existing condition is removed;
792i.e., the breakpoint is made unconditional."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000793
Tim Peters2344fae2001-01-15 00:50:52 +0000794 def help_step(self):
795 self.help_s()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000796
Tim Peters2344fae2001-01-15 00:50:52 +0000797 def help_s(self):
798 print """s(tep)
799Execute the current line, stop at the first possible occasion
800(either in a function that is called or in the current function)."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000801
Tim Peters2344fae2001-01-15 00:50:52 +0000802 def help_next(self):
803 self.help_n()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000804
Tim Peters2344fae2001-01-15 00:50:52 +0000805 def help_n(self):
806 print """n(ext)
807Continue execution until the next line in the current function
808is reached or it returns."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000809
Tim Peters2344fae2001-01-15 00:50:52 +0000810 def help_return(self):
811 self.help_r()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000812
Tim Peters2344fae2001-01-15 00:50:52 +0000813 def help_r(self):
814 print """r(eturn)
815Continue execution until the current function returns."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000816
Tim Peters2344fae2001-01-15 00:50:52 +0000817 def help_continue(self):
818 self.help_c()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000819
Tim Peters2344fae2001-01-15 00:50:52 +0000820 def help_cont(self):
821 self.help_c()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000822
Tim Peters2344fae2001-01-15 00:50:52 +0000823 def help_c(self):
824 print """c(ont(inue))
825Continue execution, only stop when a breakpoint is encountered."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000826
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000827 def help_jump(self):
828 self.help_j()
829
830 def help_j(self):
831 print """j(ump) lineno
832Set the next line that will be executed."""
833
Tim Peters2344fae2001-01-15 00:50:52 +0000834 def help_list(self):
835 self.help_l()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000836
Tim Peters2344fae2001-01-15 00:50:52 +0000837 def help_l(self):
838 print """l(ist) [first [,last]]
839List source code for the current file.
840Without arguments, list 11 lines around the current line
841or continue the previous listing.
842With one argument, list 11 lines starting at that line.
843With two arguments, list the given range;
844if the second argument is less than the first, it is a count."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000845
Tim Peters2344fae2001-01-15 00:50:52 +0000846 def help_args(self):
847 self.help_a()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000848
Tim Peters2344fae2001-01-15 00:50:52 +0000849 def help_a(self):
850 print """a(rgs)
851Print the arguments of the current function."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000852
Tim Peters2344fae2001-01-15 00:50:52 +0000853 def help_p(self):
854 print """p expression
855Print the value of the expression."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000856
Barry Warsaw210bd202002-11-05 22:40:20 +0000857 def help_pp(self):
858 print """pp expression
859Pretty-print the value of the expression."""
860
Tim Peters2344fae2001-01-15 00:50:52 +0000861 def help_exec(self):
862 print """(!) statement
863Execute the (one-line) statement in the context of
864the current stack frame.
865The exclamation point can be omitted unless the first word
866of the statement resembles a debugger command.
867To assign to a global variable you must always prefix the
868command with a 'global' command, e.g.:
869(Pdb) global list_options; list_options = ['-l']
870(Pdb)"""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000871
Tim Peters2344fae2001-01-15 00:50:52 +0000872 def help_quit(self):
873 self.help_q()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000874
Tim Peters2344fae2001-01-15 00:50:52 +0000875 def help_q(self):
Guido van Rossumd1c08f32002-04-15 00:48:24 +0000876 print """q(uit) or exit - Quit from the debugger.
Tim Peters2344fae2001-01-15 00:50:52 +0000877The program being executed is aborted."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000878
Guido van Rossumd1c08f32002-04-15 00:48:24 +0000879 help_exit = help_q
880
Tim Peters2344fae2001-01-15 00:50:52 +0000881 def help_whatis(self):
882 print """whatis arg
883Prints the type of the argument."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000884
Tim Peters2344fae2001-01-15 00:50:52 +0000885 def help_EOF(self):
886 print """EOF
887Handles the receipt of EOF as a command."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000888
Tim Peters2344fae2001-01-15 00:50:52 +0000889 def help_alias(self):
890 print """alias [name [command [parameter parameter ...] ]]
891Creates an alias called 'name' the executes 'command'. The command
892must *not* be enclosed in quotes. Replaceable parameters are
893indicated by %1, %2, and so on, while %* is replaced by all the
894parameters. If no command is given, the current alias for name
895is shown. If no name is given, all aliases are listed.
Guido van Rossum2424f851998-09-11 22:50:09 +0000896
Tim Peters2344fae2001-01-15 00:50:52 +0000897Aliases may be nested and can contain anything that can be
898legally typed at the pdb prompt. Note! You *can* override
899internal pdb commands with aliases! Those internal commands
900are then hidden until the alias is removed. Aliasing is recursively
901applied to the first word of the command line; all other words
902in the line are left alone.
Guido van Rossum2424f851998-09-11 22:50:09 +0000903
Tim Peters2344fae2001-01-15 00:50:52 +0000904Some useful aliases (especially when placed in the .pdbrc file) are:
Guido van Rossum2424f851998-09-11 22:50:09 +0000905
Tim Peters2344fae2001-01-15 00:50:52 +0000906#Print instance variables (usage "pi classInst")
907alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
Guido van Rossum2424f851998-09-11 22:50:09 +0000908
Tim Peters2344fae2001-01-15 00:50:52 +0000909#Print instance variables in self
910alias ps pi self
911"""
Guido van Rossum2424f851998-09-11 22:50:09 +0000912
Tim Peters2344fae2001-01-15 00:50:52 +0000913 def help_unalias(self):
914 print """unalias name
915Deletes the specified alias."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000916
Tim Peters2344fae2001-01-15 00:50:52 +0000917 def help_pdb(self):
918 help()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000919
Tim Peters2344fae2001-01-15 00:50:52 +0000920 def lookupmodule(self, filename):
921 """Helper function for break/clear parsing -- may be overridden."""
922 root, ext = os.path.splitext(filename)
923 if ext == '':
924 filename = filename + '.py'
925 if os.path.isabs(filename):
926 return filename
927 for dirname in sys.path:
928 while os.path.islink(dirname):
929 dirname = os.readlink(dirname)
930 fullname = os.path.join(dirname, filename)
931 if os.path.exists(fullname):
932 return fullname
933 return None
Guido van Rossumb5699c71998-07-20 23:13:54 +0000934
Guido van Rossum35771131992-09-08 11:59:04 +0000935# Simplified interface
936
Guido van Rossum5e38b6f1995-02-27 13:13:40 +0000937def run(statement, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +0000938 Pdb().run(statement, globals, locals)
Guido van Rossum5e38b6f1995-02-27 13:13:40 +0000939
940def runeval(expression, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +0000941 return Pdb().runeval(expression, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000942
943def runctx(statement, globals, locals):
Tim Peters2344fae2001-01-15 00:50:52 +0000944 # B/W compatibility
945 run(statement, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000946
Guido van Rossum4e160981992-09-02 20:43:20 +0000947def runcall(*args):
Tim Peters2344fae2001-01-15 00:50:52 +0000948 return apply(Pdb().runcall, args)
Guido van Rossum4e160981992-09-02 20:43:20 +0000949
Guido van Rossumb6775db1994-08-01 11:34:53 +0000950def set_trace():
Tim Peters2344fae2001-01-15 00:50:52 +0000951 Pdb().set_trace()
Guido van Rossum35771131992-09-08 11:59:04 +0000952
953# Post-Mortem interface
954
955def post_mortem(t):
Tim Peters2344fae2001-01-15 00:50:52 +0000956 p = Pdb()
957 p.reset()
958 while t.tb_next is not None:
959 t = t.tb_next
960 p.interaction(t.tb_frame, t)
Guido van Rossum35771131992-09-08 11:59:04 +0000961
962def pm():
Tim Peters2344fae2001-01-15 00:50:52 +0000963 post_mortem(sys.last_traceback)
Guido van Rossum35771131992-09-08 11:59:04 +0000964
965
966# Main program for testing
967
Guido van Rossum23efba41992-01-27 16:58:47 +0000968TESTCMD = 'import x; x.main()'
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000969
Guido van Rossum921c8241992-01-10 14:54:42 +0000970def test():
Tim Peters2344fae2001-01-15 00:50:52 +0000971 run(TESTCMD)
Guido van Rossume61fa0a1993-10-22 13:56:35 +0000972
973# print help
974def help():
Tim Peters2344fae2001-01-15 00:50:52 +0000975 for dirname in sys.path:
976 fullname = os.path.join(dirname, 'pdb.doc')
977 if os.path.exists(fullname):
978 sts = os.system('${PAGER-more} '+fullname)
979 if sts: print '*** Pager exit status:', sts
980 break
981 else:
982 print 'Sorry, can\'t find the help file "pdb.doc"',
983 print 'along the Python search path'
Guido van Rossumf17361d1996-07-30 16:28:13 +0000984
Guido van Rossumb5699c71998-07-20 23:13:54 +0000985mainmodule = ''
986mainpyfile = ''
987
Guido van Rossumf17361d1996-07-30 16:28:13 +0000988# When invoked as main program, invoke the debugger on a script
989if __name__=='__main__':
Tim Peters2344fae2001-01-15 00:50:52 +0000990 if not sys.argv[1:]:
991 print "usage: pdb.py scriptfile [arg] ..."
992 sys.exit(2)
Guido van Rossumf17361d1996-07-30 16:28:13 +0000993
Tim Peters2344fae2001-01-15 00:50:52 +0000994 mainpyfile = filename = sys.argv[1] # Get script filename
995 if not os.path.exists(filename):
996 print 'Error:', `filename`, 'does not exist'
997 sys.exit(1)
998 mainmodule = os.path.basename(filename)
999 del sys.argv[0] # Hide "pdb.py" from argument list
Guido van Rossumec577d51996-09-10 17:39:34 +00001000
Tim Peters2344fae2001-01-15 00:50:52 +00001001 # Insert script directory in front of module search path
1002 sys.path.insert(0, os.path.dirname(filename))
Guido van Rossumf17361d1996-07-30 16:28:13 +00001003
Tim Peters2344fae2001-01-15 00:50:52 +00001004 run('execfile(' + `filename` + ')')