blob: 4b0516d28aefa4d0c706c9cb25d36a5d0906c87f [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
14
Guido van Rossumef1b41b2002-09-10 21:57:14 +000015# Create a custom safe Repr instance and increase its maxstring.
16# The default of 30 truncates error messages too easily.
17_repr = Repr()
18_repr.maxstring = 200
19_saferepr = _repr.repr
20
Skip Montanaro352674d2001-02-07 23:14:30 +000021__all__ = ["run", "pm", "Pdb", "runeval", "runctx", "runcall", "set_trace",
22 "post_mortem", "help"]
23
Barry Warsaw2bee8fe1999-09-09 16:32:41 +000024def find_function(funcname, filename):
Tim Peters2344fae2001-01-15 00:50:52 +000025 cre = re.compile(r'def\s+%s\s*[(]' % funcname)
26 try:
27 fp = open(filename)
28 except IOError:
29 return None
30 # consumer of this info expects the first line to be 1
31 lineno = 1
32 answer = None
33 while 1:
34 line = fp.readline()
35 if line == '':
36 break
37 if cre.match(line):
38 answer = funcname, filename, lineno
39 break
40 lineno = lineno + 1
41 fp.close()
42 return answer
Guido van Rossum921c8241992-01-10 14:54:42 +000043
44
Guido van Rossuma558e371994-11-10 22:27:35 +000045# Interaction prompt line will separate file and call info from code
46# text using value of line_prefix string. A newline and arrow may
47# be to your liking. You can set it once pdb is imported using the
48# command "pdb.line_prefix = '\n% '".
Tim Peters2344fae2001-01-15 00:50:52 +000049# line_prefix = ': ' # Use this to get the old situation back
50line_prefix = '\n-> ' # Probably a better default
Guido van Rossuma558e371994-11-10 22:27:35 +000051
Guido van Rossum23efba41992-01-27 16:58:47 +000052class Pdb(bdb.Bdb, cmd.Cmd):
Guido van Rossum2424f851998-09-11 22:50:09 +000053
Tim Peters2344fae2001-01-15 00:50:52 +000054 def __init__(self):
55 bdb.Bdb.__init__(self)
56 cmd.Cmd.__init__(self)
57 self.prompt = '(Pdb) '
58 self.aliases = {}
59 # Try to load readline if it exists
60 try:
61 import readline
62 except ImportError:
63 pass
Guido van Rossum2424f851998-09-11 22:50:09 +000064
Tim Peters2344fae2001-01-15 00:50:52 +000065 # Read $HOME/.pdbrc and ./.pdbrc
66 self.rcLines = []
Raymond Hettinger54f02222002-06-01 14:18:47 +000067 if 'HOME' in os.environ:
Tim Peters2344fae2001-01-15 00:50:52 +000068 envHome = os.environ['HOME']
69 try:
70 rcFile = open(os.path.join(envHome, ".pdbrc"))
71 except IOError:
72 pass
73 else:
74 for line in rcFile.readlines():
75 self.rcLines.append(line)
76 rcFile.close()
77 try:
78 rcFile = open(".pdbrc")
79 except IOError:
80 pass
81 else:
82 for line in rcFile.readlines():
83 self.rcLines.append(line)
84 rcFile.close()
Guido van Rossum23efba41992-01-27 16:58:47 +000085
Tim Peters2344fae2001-01-15 00:50:52 +000086 def reset(self):
87 bdb.Bdb.reset(self)
88 self.forget()
Guido van Rossum23efba41992-01-27 16:58:47 +000089
Tim Peters2344fae2001-01-15 00:50:52 +000090 def forget(self):
91 self.lineno = None
92 self.stack = []
93 self.curindex = 0
94 self.curframe = None
Guido van Rossum2424f851998-09-11 22:50:09 +000095
Tim Peters2344fae2001-01-15 00:50:52 +000096 def setup(self, f, t):
97 self.forget()
98 self.stack, self.curindex = self.get_stack(f, t)
99 self.curframe = self.stack[self.curindex][0]
100 self.execRcLines()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000101
Tim Peters2344fae2001-01-15 00:50:52 +0000102 # Can be executed earlier than 'setup' if desired
103 def execRcLines(self):
104 if self.rcLines:
105 # Make local copy because of recursion
106 rcLines = self.rcLines
107 # executed only once
108 self.rcLines = []
109 for line in rcLines:
110 line = line[:-1]
Guido van Rossum08454592002-07-12 13:10:53 +0000111 if len(line) > 0 and line[0] != '#':
112 self.onecmd(line)
Guido van Rossum2424f851998-09-11 22:50:09 +0000113
Tim Peters280488b2002-08-23 18:19:30 +0000114 # Override Bdb methods
Michael W. Hudsondd32a912002-08-15 14:59:02 +0000115
116 def user_call(self, frame, argument_list):
117 """This method is called when there is the remote possibility
118 that we ever need to stop in this function."""
119 print '--Call--'
120 self.interaction(frame, None)
Guido van Rossum2424f851998-09-11 22:50:09 +0000121
Tim Peters2344fae2001-01-15 00:50:52 +0000122 def user_line(self, frame):
123 """This function is called when we stop or break at this line."""
124 self.interaction(frame, None)
Guido van Rossum9e1ee971997-07-11 13:43:53 +0000125
Tim Peters2344fae2001-01-15 00:50:52 +0000126 def user_return(self, frame, return_value):
127 """This function is called when a return trap is set here."""
128 frame.f_locals['__return__'] = return_value
129 print '--Return--'
130 self.interaction(frame, None)
Guido van Rossum2424f851998-09-11 22:50:09 +0000131
Tim Peters2344fae2001-01-15 00:50:52 +0000132 def user_exception(self, frame, (exc_type, exc_value, exc_traceback)):
133 """This function is called if an exception occurs,
134 but only if we are to stop at or just below this level."""
135 frame.f_locals['__exception__'] = exc_type, exc_value
136 if type(exc_type) == type(''):
137 exc_type_name = exc_type
138 else: exc_type_name = exc_type.__name__
Tim Peters6f8ee592001-02-09 23:28:07 +0000139 print exc_type_name + ':', _saferepr(exc_value)
Tim Peters2344fae2001-01-15 00:50:52 +0000140 self.interaction(frame, exc_traceback)
Guido van Rossum2424f851998-09-11 22:50:09 +0000141
Tim Peters2344fae2001-01-15 00:50:52 +0000142 # General interaction function
143
144 def interaction(self, frame, traceback):
145 self.setup(frame, traceback)
146 self.print_stack_entry(self.stack[self.curindex])
147 self.cmdloop()
148 self.forget()
149
150 def default(self, line):
151 if line[:1] == '!': line = line[1:]
152 locals = self.curframe.f_locals
153 globals = self.curframe.f_globals
154 try:
155 code = compile(line + '\n', '<stdin>', 'single')
156 exec code in globals, locals
157 except:
158 t, v = sys.exc_info()[:2]
159 if type(t) == type(''):
160 exc_type_name = t
161 else: exc_type_name = t.__name__
162 print '***', exc_type_name + ':', v
163
164 def precmd(self, line):
165 """Handle alias expansion and ';;' separator."""
Guido van Rossum08454592002-07-12 13:10:53 +0000166 if not line.strip():
Tim Peters2344fae2001-01-15 00:50:52 +0000167 return line
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000168 args = line.split()
Raymond Hettinger54f02222002-06-01 14:18:47 +0000169 while args[0] in self.aliases:
Tim Peters2344fae2001-01-15 00:50:52 +0000170 line = self.aliases[args[0]]
171 ii = 1
172 for tmpArg in args[1:]:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000173 line = line.replace("%" + str(ii),
Tim Peters2344fae2001-01-15 00:50:52 +0000174 tmpArg)
175 ii = ii + 1
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000176 line = line.replace("%*", ' '.join(args[1:]))
177 args = line.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000178 # split into ';;' separated commands
179 # unless it's an alias command
180 if args[0] != 'alias':
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000181 marker = line.find(';;')
Tim Peters2344fae2001-01-15 00:50:52 +0000182 if marker >= 0:
183 # queue up everything after marker
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000184 next = line[marker+2:].lstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000185 self.cmdqueue.append(next)
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000186 line = line[:marker].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000187 return line
188
189 # Command definitions, called by cmdloop()
190 # The argument is the remaining string on the command line
191 # Return true to exit from the command loop
192
193 do_h = cmd.Cmd.do_help
194
195 def do_EOF(self, arg):
196 return 0 # Don't die on EOF
197
198 def do_break(self, arg, temporary = 0):
199 # break [ ([filename:]lineno | function) [, "condition"] ]
200 if not arg:
201 if self.breaks: # There's at least one
202 print "Num Type Disp Enb Where"
203 for bp in bdb.Breakpoint.bpbynumber:
204 if bp:
205 bp.bpprint()
206 return
207 # parse arguments; comma has lowest precedence
208 # and cannot occur in filename
209 filename = None
210 lineno = None
211 cond = None
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000212 comma = arg.find(',')
Tim Peters2344fae2001-01-15 00:50:52 +0000213 if comma > 0:
214 # parse stuff after comma: "condition"
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000215 cond = arg[comma+1:].lstrip()
216 arg = arg[:comma].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000217 # parse stuff before comma: [filename:]lineno | function
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000218 colon = arg.rfind(':')
Tim Peters2344fae2001-01-15 00:50:52 +0000219 if colon >= 0:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000220 filename = arg[:colon].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000221 f = self.lookupmodule(filename)
222 if not f:
223 print '*** ', `filename`,
224 print 'not found from sys.path'
225 return
226 else:
227 filename = f
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000228 arg = arg[colon+1:].lstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000229 try:
230 lineno = int(arg)
231 except ValueError, msg:
232 print '*** Bad lineno:', arg
233 return
234 else:
235 # no colon; can be lineno or function
236 try:
237 lineno = int(arg)
238 except ValueError:
239 try:
240 func = eval(arg,
241 self.curframe.f_globals,
242 self.curframe.f_locals)
243 except:
244 func = arg
245 try:
246 if hasattr(func, 'im_func'):
247 func = func.im_func
248 code = func.func_code
249 lineno = code.co_firstlineno
250 filename = code.co_filename
251 except:
252 # last thing to try
253 (ok, filename, ln) = self.lineinfo(arg)
254 if not ok:
255 print '*** The specified object',
256 print `arg`,
257 print 'is not a function'
258 print ('or was not found '
259 'along sys.path.')
260 return
261 lineno = int(ln)
262 if not filename:
263 filename = self.defaultFile()
264 # Check for reasonable breakpoint
265 line = self.checkline(filename, lineno)
266 if line:
267 # now set the break point
268 err = self.set_break(filename, line, temporary, cond)
269 if err: print '***', err
270 else:
271 bp = self.get_breaks(filename, line)[-1]
272 print "Breakpoint %d at %s:%d" % (bp.number,
273 bp.file,
274 bp.line)
275
276 # To be overridden in derived debuggers
277 def defaultFile(self):
278 """Produce a reasonable default."""
279 filename = self.curframe.f_code.co_filename
280 if filename == '<string>' and mainpyfile:
281 filename = mainpyfile
282 return filename
283
284 do_b = do_break
285
286 def do_tbreak(self, arg):
287 self.do_break(arg, 1)
288
289 def lineinfo(self, identifier):
290 failed = (None, None, None)
291 # Input is identifier, may be in single quotes
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000292 idstring = identifier.split("'")
Tim Peters2344fae2001-01-15 00:50:52 +0000293 if len(idstring) == 1:
294 # not in single quotes
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000295 id = idstring[0].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000296 elif len(idstring) == 3:
297 # quoted
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000298 id = idstring[1].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000299 else:
300 return failed
301 if id == '': return failed
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000302 parts = id.split('.')
Tim Peters2344fae2001-01-15 00:50:52 +0000303 # Protection for derived debuggers
304 if parts[0] == 'self':
305 del parts[0]
306 if len(parts) == 0:
307 return failed
308 # Best first guess at file to look at
309 fname = self.defaultFile()
310 if len(parts) == 1:
311 item = parts[0]
312 else:
313 # More than one part.
314 # First is module, second is method/class
315 f = self.lookupmodule(parts[0])
316 if f:
317 fname = f
318 item = parts[1]
319 answer = find_function(item, fname)
320 return answer or failed
321
322 def checkline(self, filename, lineno):
323 """Return line number of first line at or after input
324 argument such that if the input points to a 'def', the
325 returned line number is the first
326 non-blank/non-comment line to follow. If the input
327 points to a blank or comment line, return 0. At end
328 of file, also return 0."""
329
330 line = linecache.getline(filename, lineno)
331 if not line:
332 print 'End of file'
333 return 0
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000334 line = line.strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000335 # Don't allow setting breakpoint at a blank line
Guido van Rossum08454592002-07-12 13:10:53 +0000336 if (not line or (line[0] == '#') or
337 (line[:3] == '"""') or line[:3] == "'''"):
Tim Peters2344fae2001-01-15 00:50:52 +0000338 print '*** Blank or comment'
339 return 0
340 # When a file is read in and a breakpoint is at
341 # the 'def' statement, the system stops there at
342 # code parse time. We don't want that, so all breakpoints
343 # set at 'def' statements are moved one line onward
344 if line[:3] == 'def':
345 instr = ''
346 brackets = 0
347 while 1:
348 skipone = 0
349 for c in line:
350 if instr:
351 if skipone:
352 skipone = 0
353 elif c == '\\':
354 skipone = 1
355 elif c == instr:
356 instr = ''
357 elif c == '#':
358 break
359 elif c in ('"',"'"):
360 instr = c
361 elif c in ('(','{','['):
362 brackets = brackets + 1
363 elif c in (')','}',']'):
364 brackets = brackets - 1
365 lineno = lineno+1
366 line = linecache.getline(filename, lineno)
367 if not line:
368 print 'end of file'
369 return 0
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000370 line = line.strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000371 if not line: continue # Blank line
372 if brackets <= 0 and line[0] not in ('#','"',"'"):
373 break
374 return lineno
375
376 def do_enable(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000377 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000378 for i in args:
379 bp = bdb.Breakpoint.bpbynumber[int(i)]
380 if bp:
381 bp.enable()
382
383 def do_disable(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000384 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000385 for i in args:
386 bp = bdb.Breakpoint.bpbynumber[int(i)]
387 if bp:
388 bp.disable()
389
390 def do_condition(self, arg):
391 # arg is breakpoint number and condition
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000392 args = arg.split(' ', 1)
393 bpnum = int(args[0].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000394 try:
395 cond = args[1]
396 except:
397 cond = None
398 bp = bdb.Breakpoint.bpbynumber[bpnum]
399 if bp:
400 bp.cond = cond
401 if not cond:
402 print 'Breakpoint', bpnum,
403 print 'is now unconditional.'
404
405 def do_ignore(self,arg):
406 """arg is bp number followed by ignore count."""
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000407 args = arg.split()
408 bpnum = int(args[0].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000409 try:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000410 count = int(args[1].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000411 except:
412 count = 0
413 bp = bdb.Breakpoint.bpbynumber[bpnum]
414 if bp:
415 bp.ignore = count
Guido van Rossum08454592002-07-12 13:10:53 +0000416 if count > 0:
Tim Peters2344fae2001-01-15 00:50:52 +0000417 reply = 'Will ignore next '
Guido van Rossum08454592002-07-12 13:10:53 +0000418 if count > 1:
Tim Peters2344fae2001-01-15 00:50:52 +0000419 reply = reply + '%d crossings' % count
420 else:
421 reply = reply + '1 crossing'
422 print reply + ' of breakpoint %d.' % bpnum
423 else:
424 print 'Will stop next time breakpoint',
425 print bpnum, 'is reached.'
426
427 def do_clear(self, arg):
428 """Three possibilities, tried in this order:
429 clear -> clear all breaks, ask for confirmation
430 clear file:lineno -> clear all breaks at file:lineno
431 clear bpno bpno ... -> clear breakpoints by number"""
432 if not arg:
433 try:
434 reply = raw_input('Clear all breaks? ')
435 except EOFError:
436 reply = 'no'
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000437 reply = reply.strip().lower()
Tim Peters2344fae2001-01-15 00:50:52 +0000438 if reply in ('y', 'yes'):
439 self.clear_all_breaks()
440 return
441 if ':' in arg:
442 # Make sure it works for "clear C:\foo\bar.py:12"
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000443 i = arg.rfind(':')
Tim Peters2344fae2001-01-15 00:50:52 +0000444 filename = arg[:i]
445 arg = arg[i+1:]
446 try:
447 lineno = int(arg)
448 except:
449 err = "Invalid line number (%s)" % arg
450 else:
451 err = self.clear_break(filename, lineno)
452 if err: print '***', err
453 return
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000454 numberlist = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000455 for i in numberlist:
456 err = self.clear_bpbynumber(i)
457 if err:
458 print '***', err
459 else:
460 print 'Deleted breakpoint %s ' % (i,)
461 do_cl = do_clear # 'c' is already an abbreviation for 'continue'
462
463 def do_where(self, arg):
464 self.print_stack_trace()
465 do_w = do_where
Guido van Rossum6bd68352001-01-20 17:57:37 +0000466 do_bt = do_where
Tim Peters2344fae2001-01-15 00:50:52 +0000467
468 def do_up(self, arg):
469 if self.curindex == 0:
470 print '*** Oldest frame'
471 else:
472 self.curindex = self.curindex - 1
473 self.curframe = self.stack[self.curindex][0]
474 self.print_stack_entry(self.stack[self.curindex])
475 self.lineno = None
476 do_u = do_up
477
478 def do_down(self, arg):
479 if self.curindex + 1 == len(self.stack):
480 print '*** Newest frame'
481 else:
482 self.curindex = self.curindex + 1
483 self.curframe = self.stack[self.curindex][0]
484 self.print_stack_entry(self.stack[self.curindex])
485 self.lineno = None
486 do_d = do_down
487
488 def do_step(self, arg):
489 self.set_step()
490 return 1
491 do_s = do_step
492
493 def do_next(self, arg):
494 self.set_next(self.curframe)
495 return 1
496 do_n = do_next
497
498 def do_return(self, arg):
499 self.set_return(self.curframe)
500 return 1
501 do_r = do_return
502
503 def do_continue(self, arg):
504 self.set_continue()
505 return 1
506 do_c = do_cont = do_continue
507
508 def do_quit(self, arg):
509 self.set_quit()
510 return 1
511 do_q = do_quit
Guido van Rossumd1c08f32002-04-15 00:48:24 +0000512 do_exit = do_quit
Tim Peters2344fae2001-01-15 00:50:52 +0000513
514 def do_args(self, arg):
515 f = self.curframe
516 co = f.f_code
517 dict = f.f_locals
518 n = co.co_argcount
519 if co.co_flags & 4: n = n+1
520 if co.co_flags & 8: n = n+1
521 for i in range(n):
522 name = co.co_varnames[i]
523 print name, '=',
Raymond Hettinger54f02222002-06-01 14:18:47 +0000524 if name in dict: print dict[name]
Tim Peters2344fae2001-01-15 00:50:52 +0000525 else: print "*** undefined ***"
526 do_a = do_args
Guido van Rossum2424f851998-09-11 22:50:09 +0000527
Tim Peters2344fae2001-01-15 00:50:52 +0000528 def do_retval(self, arg):
Raymond Hettinger54f02222002-06-01 14:18:47 +0000529 if '__return__' in self.curframe.f_locals:
Tim Peters2344fae2001-01-15 00:50:52 +0000530 print self.curframe.f_locals['__return__']
531 else:
532 print '*** Not yet returned!'
533 do_rv = do_retval
Guido van Rossum2424f851998-09-11 22:50:09 +0000534
Tim Peters2344fae2001-01-15 00:50:52 +0000535 def do_p(self, arg):
536 try:
537 value = eval(arg, self.curframe.f_globals,
538 self.curframe.f_locals)
539 except:
540 t, v = sys.exc_info()[:2]
541 if type(t) == type(''):
542 exc_type_name = t
543 else: exc_type_name = t.__name__
544 print '***', exc_type_name + ':', `v`
545 return
Guido van Rossum2424f851998-09-11 22:50:09 +0000546
Tim Peters2344fae2001-01-15 00:50:52 +0000547 print `value`
Guido van Rossum2424f851998-09-11 22:50:09 +0000548
Tim Peters2344fae2001-01-15 00:50:52 +0000549 def do_list(self, arg):
550 self.lastcmd = 'list'
551 last = None
552 if arg:
553 try:
554 x = eval(arg, {}, {})
555 if type(x) == type(()):
556 first, last = x
557 first = int(first)
558 last = int(last)
559 if last < first:
560 # Assume it's a count
561 last = first + last
562 else:
563 first = max(1, int(x) - 5)
564 except:
565 print '*** Error in argument:', `arg`
566 return
567 elif self.lineno is None:
568 first = max(1, self.curframe.f_lineno - 5)
569 else:
570 first = self.lineno + 1
571 if last is None:
572 last = first + 10
573 filename = self.curframe.f_code.co_filename
574 breaklist = self.get_file_breaks(filename)
575 try:
576 for lineno in range(first, last+1):
577 line = linecache.getline(filename, lineno)
578 if not line:
579 print '[EOF]'
580 break
581 else:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000582 s = `lineno`.rjust(3)
Tim Peters2344fae2001-01-15 00:50:52 +0000583 if len(s) < 4: s = s + ' '
584 if lineno in breaklist: s = s + 'B'
585 else: s = s + ' '
586 if lineno == self.curframe.f_lineno:
587 s = s + '->'
588 print s + '\t' + line,
589 self.lineno = lineno
590 except KeyboardInterrupt:
591 pass
592 do_l = do_list
Guido van Rossum2424f851998-09-11 22:50:09 +0000593
Tim Peters2344fae2001-01-15 00:50:52 +0000594 def do_whatis(self, arg):
595 try:
596 value = eval(arg, self.curframe.f_globals,
597 self.curframe.f_locals)
598 except:
599 t, v = sys.exc_info()[:2]
600 if type(t) == type(''):
601 exc_type_name = t
602 else: exc_type_name = t.__name__
603 print '***', exc_type_name + ':', `v`
604 return
605 code = None
606 # Is it a function?
607 try: code = value.func_code
608 except: pass
609 if code:
610 print 'Function', code.co_name
611 return
612 # Is it an instance method?
613 try: code = value.im_func.func_code
614 except: pass
615 if code:
616 print 'Method', code.co_name
617 return
618 # None of the above...
619 print type(value)
Guido van Rossum8e2ec561993-07-29 09:37:38 +0000620
Tim Peters2344fae2001-01-15 00:50:52 +0000621 def do_alias(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000622 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000623 if len(args) == 0:
624 keys = self.aliases.keys()
625 keys.sort()
626 for alias in keys:
627 print "%s = %s" % (alias, self.aliases[alias])
628 return
Guido van Rossum08454592002-07-12 13:10:53 +0000629 if args[0] in self.aliases and len(args) == 1:
Tim Peters2344fae2001-01-15 00:50:52 +0000630 print "%s = %s" % (args[0], self.aliases[args[0]])
631 else:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000632 self.aliases[args[0]] = ' '.join(args[1:])
Guido van Rossum23efba41992-01-27 16:58:47 +0000633
Tim Peters2344fae2001-01-15 00:50:52 +0000634 def do_unalias(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000635 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000636 if len(args) == 0: return
Raymond Hettinger54f02222002-06-01 14:18:47 +0000637 if args[0] in self.aliases:
Tim Peters2344fae2001-01-15 00:50:52 +0000638 del self.aliases[args[0]]
Guido van Rossum00230781993-03-29 11:39:45 +0000639
Tim Peters2344fae2001-01-15 00:50:52 +0000640 # Print a traceback starting at the top stack frame.
641 # The most recently entered frame is printed last;
642 # this is different from dbx and gdb, but consistent with
643 # the Python interpreter's stack trace.
644 # It is also consistent with the up/down commands (which are
645 # compatible with dbx and gdb: up moves towards 'main()'
646 # and down moves towards the most recent stack frame).
Guido van Rossum2424f851998-09-11 22:50:09 +0000647
Tim Peters2344fae2001-01-15 00:50:52 +0000648 def print_stack_trace(self):
649 try:
650 for frame_lineno in self.stack:
651 self.print_stack_entry(frame_lineno)
652 except KeyboardInterrupt:
653 pass
Guido van Rossum2424f851998-09-11 22:50:09 +0000654
Tim Peters2344fae2001-01-15 00:50:52 +0000655 def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix):
656 frame, lineno = frame_lineno
657 if frame is self.curframe:
658 print '>',
659 else:
660 print ' ',
661 print self.format_stack_entry(frame_lineno, prompt_prefix)
Guido van Rossum2424f851998-09-11 22:50:09 +0000662
Guido van Rossum921c8241992-01-10 14:54:42 +0000663
Tim Peters2344fae2001-01-15 00:50:52 +0000664 # Help methods (derived from pdb.doc)
Guido van Rossum921c8241992-01-10 14:54:42 +0000665
Tim Peters2344fae2001-01-15 00:50:52 +0000666 def help_help(self):
667 self.help_h()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000668
Tim Peters2344fae2001-01-15 00:50:52 +0000669 def help_h(self):
670 print """h(elp)
671Without argument, print the list of available commands.
672With a command name as argument, print help about that command
673"help pdb" pipes the full documentation file to the $PAGER
674"help exec" gives help on the ! command"""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000675
Tim Peters2344fae2001-01-15 00:50:52 +0000676 def help_where(self):
677 self.help_w()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000678
Tim Peters2344fae2001-01-15 00:50:52 +0000679 def help_w(self):
680 print """w(here)
681Print a stack trace, with the most recent frame at the bottom.
682An arrow indicates the "current frame", which determines the
Guido van Rossum6bd68352001-01-20 17:57:37 +0000683context of most commands. 'bt' is an alias for this command."""
684
685 help_bt = help_w
Guido van Rossumb6775db1994-08-01 11:34:53 +0000686
Tim Peters2344fae2001-01-15 00:50:52 +0000687 def help_down(self):
688 self.help_d()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000689
Tim Peters2344fae2001-01-15 00:50:52 +0000690 def help_d(self):
691 print """d(own)
692Move the current frame one level down in the stack trace
693(to an older frame)."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000694
Tim Peters2344fae2001-01-15 00:50:52 +0000695 def help_up(self):
696 self.help_u()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000697
Tim Peters2344fae2001-01-15 00:50:52 +0000698 def help_u(self):
699 print """u(p)
700Move the current frame one level up in the stack trace
701(to a newer frame)."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000702
Tim Peters2344fae2001-01-15 00:50:52 +0000703 def help_break(self):
704 self.help_b()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000705
Tim Peters2344fae2001-01-15 00:50:52 +0000706 def help_b(self):
707 print """b(reak) ([file:]lineno | function) [, condition]
708With a line number argument, set a break there in the current
709file. With a function name, set a break at first executable line
710of that function. Without argument, list all breaks. If a second
711argument is present, it is a string specifying an expression
712which must evaluate to true before the breakpoint is honored.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000713
Tim Peters2344fae2001-01-15 00:50:52 +0000714The line number may be prefixed with a filename and a colon,
715to specify a breakpoint in another file (probably one that
716hasn't been loaded yet). The file is searched for on sys.path;
717the .py suffix may be omitted."""
Guido van Rossumb5699c71998-07-20 23:13:54 +0000718
Tim Peters2344fae2001-01-15 00:50:52 +0000719 def help_clear(self):
720 self.help_cl()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000721
Tim Peters2344fae2001-01-15 00:50:52 +0000722 def help_cl(self):
723 print "cl(ear) filename:lineno"
724 print """cl(ear) [bpnumber [bpnumber...]]
725With a space separated list of breakpoint numbers, clear
726those breakpoints. Without argument, clear all breaks (but
727first ask confirmation). With a filename:lineno argument,
728clear all breaks at that line in that file.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000729
Tim Peters2344fae2001-01-15 00:50:52 +0000730Note that the argument is different from previous versions of
731the debugger (in python distributions 1.5.1 and before) where
732a linenumber was used instead of either filename:lineno or
733breakpoint numbers."""
Guido van Rossumb5699c71998-07-20 23:13:54 +0000734
Tim Peters2344fae2001-01-15 00:50:52 +0000735 def help_tbreak(self):
736 print """tbreak same arguments as break, but breakpoint is
737removed when first hit."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000738
Tim Peters2344fae2001-01-15 00:50:52 +0000739 def help_enable(self):
740 print """enable bpnumber [bpnumber ...]
741Enables the breakpoints given as a space separated list of
742bp numbers."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000743
Tim Peters2344fae2001-01-15 00:50:52 +0000744 def help_disable(self):
745 print """disable bpnumber [bpnumber ...]
746Disables the breakpoints given as a space separated list of
747bp numbers."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000748
Tim Peters2344fae2001-01-15 00:50:52 +0000749 def help_ignore(self):
750 print """ignore bpnumber count
751Sets the ignore count for the given breakpoint number. A breakpoint
752becomes active when the ignore count is zero. When non-zero, the
753count is decremented each time the breakpoint is reached and the
754breakpoint is not disabled and any associated condition evaluates
755to true."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000756
Tim Peters2344fae2001-01-15 00:50:52 +0000757 def help_condition(self):
758 print """condition bpnumber str_condition
759str_condition is a string specifying an expression which
760must evaluate to true before the breakpoint is honored.
761If str_condition is absent, any existing condition is removed;
762i.e., the breakpoint is made unconditional."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000763
Tim Peters2344fae2001-01-15 00:50:52 +0000764 def help_step(self):
765 self.help_s()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000766
Tim Peters2344fae2001-01-15 00:50:52 +0000767 def help_s(self):
768 print """s(tep)
769Execute the current line, stop at the first possible occasion
770(either in a function that is called or in the current function)."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000771
Tim Peters2344fae2001-01-15 00:50:52 +0000772 def help_next(self):
773 self.help_n()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000774
Tim Peters2344fae2001-01-15 00:50:52 +0000775 def help_n(self):
776 print """n(ext)
777Continue execution until the next line in the current function
778is reached or it returns."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000779
Tim Peters2344fae2001-01-15 00:50:52 +0000780 def help_return(self):
781 self.help_r()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000782
Tim Peters2344fae2001-01-15 00:50:52 +0000783 def help_r(self):
784 print """r(eturn)
785Continue execution until the current function returns."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000786
Tim Peters2344fae2001-01-15 00:50:52 +0000787 def help_continue(self):
788 self.help_c()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000789
Tim Peters2344fae2001-01-15 00:50:52 +0000790 def help_cont(self):
791 self.help_c()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000792
Tim Peters2344fae2001-01-15 00:50:52 +0000793 def help_c(self):
794 print """c(ont(inue))
795Continue execution, only stop when a breakpoint is encountered."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000796
Tim Peters2344fae2001-01-15 00:50:52 +0000797 def help_list(self):
798 self.help_l()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000799
Tim Peters2344fae2001-01-15 00:50:52 +0000800 def help_l(self):
801 print """l(ist) [first [,last]]
802List source code for the current file.
803Without arguments, list 11 lines around the current line
804or continue the previous listing.
805With one argument, list 11 lines starting at that line.
806With two arguments, list the given range;
807if the second argument is less than the first, it is a count."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000808
Tim Peters2344fae2001-01-15 00:50:52 +0000809 def help_args(self):
810 self.help_a()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000811
Tim Peters2344fae2001-01-15 00:50:52 +0000812 def help_a(self):
813 print """a(rgs)
814Print the arguments of the current function."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000815
Tim Peters2344fae2001-01-15 00:50:52 +0000816 def help_p(self):
817 print """p expression
818Print the value of the expression."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000819
Tim Peters2344fae2001-01-15 00:50:52 +0000820 def help_exec(self):
821 print """(!) statement
822Execute the (one-line) statement in the context of
823the current stack frame.
824The exclamation point can be omitted unless the first word
825of the statement resembles a debugger command.
826To assign to a global variable you must always prefix the
827command with a 'global' command, e.g.:
828(Pdb) global list_options; list_options = ['-l']
829(Pdb)"""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000830
Tim Peters2344fae2001-01-15 00:50:52 +0000831 def help_quit(self):
832 self.help_q()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000833
Tim Peters2344fae2001-01-15 00:50:52 +0000834 def help_q(self):
Guido van Rossumd1c08f32002-04-15 00:48:24 +0000835 print """q(uit) or exit - Quit from the debugger.
Tim Peters2344fae2001-01-15 00:50:52 +0000836The program being executed is aborted."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000837
Guido van Rossumd1c08f32002-04-15 00:48:24 +0000838 help_exit = help_q
839
Tim Peters2344fae2001-01-15 00:50:52 +0000840 def help_whatis(self):
841 print """whatis arg
842Prints the type of the argument."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000843
Tim Peters2344fae2001-01-15 00:50:52 +0000844 def help_EOF(self):
845 print """EOF
846Handles the receipt of EOF as a command."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000847
Tim Peters2344fae2001-01-15 00:50:52 +0000848 def help_alias(self):
849 print """alias [name [command [parameter parameter ...] ]]
850Creates an alias called 'name' the executes 'command'. The command
851must *not* be enclosed in quotes. Replaceable parameters are
852indicated by %1, %2, and so on, while %* is replaced by all the
853parameters. If no command is given, the current alias for name
854is shown. If no name is given, all aliases are listed.
Guido van Rossum2424f851998-09-11 22:50:09 +0000855
Tim Peters2344fae2001-01-15 00:50:52 +0000856Aliases may be nested and can contain anything that can be
857legally typed at the pdb prompt. Note! You *can* override
858internal pdb commands with aliases! Those internal commands
859are then hidden until the alias is removed. Aliasing is recursively
860applied to the first word of the command line; all other words
861in the line are left alone.
Guido van Rossum2424f851998-09-11 22:50:09 +0000862
Tim Peters2344fae2001-01-15 00:50:52 +0000863Some useful aliases (especially when placed in the .pdbrc file) are:
Guido van Rossum2424f851998-09-11 22:50:09 +0000864
Tim Peters2344fae2001-01-15 00:50:52 +0000865#Print instance variables (usage "pi classInst")
866alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
Guido van Rossum2424f851998-09-11 22:50:09 +0000867
Tim Peters2344fae2001-01-15 00:50:52 +0000868#Print instance variables in self
869alias ps pi self
870"""
Guido van Rossum2424f851998-09-11 22:50:09 +0000871
Tim Peters2344fae2001-01-15 00:50:52 +0000872 def help_unalias(self):
873 print """unalias name
874Deletes the specified alias."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000875
Tim Peters2344fae2001-01-15 00:50:52 +0000876 def help_pdb(self):
877 help()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000878
Tim Peters2344fae2001-01-15 00:50:52 +0000879 def lookupmodule(self, filename):
880 """Helper function for break/clear parsing -- may be overridden."""
881 root, ext = os.path.splitext(filename)
882 if ext == '':
883 filename = filename + '.py'
884 if os.path.isabs(filename):
885 return filename
886 for dirname in sys.path:
887 while os.path.islink(dirname):
888 dirname = os.readlink(dirname)
889 fullname = os.path.join(dirname, filename)
890 if os.path.exists(fullname):
891 return fullname
892 return None
Guido van Rossumb5699c71998-07-20 23:13:54 +0000893
Guido van Rossum35771131992-09-08 11:59:04 +0000894# Simplified interface
895
Guido van Rossum5e38b6f1995-02-27 13:13:40 +0000896def run(statement, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +0000897 Pdb().run(statement, globals, locals)
Guido van Rossum5e38b6f1995-02-27 13:13:40 +0000898
899def runeval(expression, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +0000900 return Pdb().runeval(expression, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000901
902def runctx(statement, globals, locals):
Tim Peters2344fae2001-01-15 00:50:52 +0000903 # B/W compatibility
904 run(statement, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000905
Guido van Rossum4e160981992-09-02 20:43:20 +0000906def runcall(*args):
Tim Peters2344fae2001-01-15 00:50:52 +0000907 return apply(Pdb().runcall, args)
Guido van Rossum4e160981992-09-02 20:43:20 +0000908
Guido van Rossumb6775db1994-08-01 11:34:53 +0000909def set_trace():
Tim Peters2344fae2001-01-15 00:50:52 +0000910 Pdb().set_trace()
Guido van Rossum35771131992-09-08 11:59:04 +0000911
912# Post-Mortem interface
913
914def post_mortem(t):
Tim Peters2344fae2001-01-15 00:50:52 +0000915 p = Pdb()
916 p.reset()
917 while t.tb_next is not None:
918 t = t.tb_next
919 p.interaction(t.tb_frame, t)
Guido van Rossum35771131992-09-08 11:59:04 +0000920
921def pm():
Tim Peters2344fae2001-01-15 00:50:52 +0000922 post_mortem(sys.last_traceback)
Guido van Rossum35771131992-09-08 11:59:04 +0000923
924
925# Main program for testing
926
Guido van Rossum23efba41992-01-27 16:58:47 +0000927TESTCMD = 'import x; x.main()'
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000928
Guido van Rossum921c8241992-01-10 14:54:42 +0000929def test():
Tim Peters2344fae2001-01-15 00:50:52 +0000930 run(TESTCMD)
Guido van Rossume61fa0a1993-10-22 13:56:35 +0000931
932# print help
933def help():
Tim Peters2344fae2001-01-15 00:50:52 +0000934 for dirname in sys.path:
935 fullname = os.path.join(dirname, 'pdb.doc')
936 if os.path.exists(fullname):
937 sts = os.system('${PAGER-more} '+fullname)
938 if sts: print '*** Pager exit status:', sts
939 break
940 else:
941 print 'Sorry, can\'t find the help file "pdb.doc"',
942 print 'along the Python search path'
Guido van Rossumf17361d1996-07-30 16:28:13 +0000943
Guido van Rossumb5699c71998-07-20 23:13:54 +0000944mainmodule = ''
945mainpyfile = ''
946
Guido van Rossumf17361d1996-07-30 16:28:13 +0000947# When invoked as main program, invoke the debugger on a script
948if __name__=='__main__':
Tim Peters2344fae2001-01-15 00:50:52 +0000949 if not sys.argv[1:]:
950 print "usage: pdb.py scriptfile [arg] ..."
951 sys.exit(2)
Guido van Rossumf17361d1996-07-30 16:28:13 +0000952
Tim Peters2344fae2001-01-15 00:50:52 +0000953 mainpyfile = filename = sys.argv[1] # Get script filename
954 if not os.path.exists(filename):
955 print 'Error:', `filename`, 'does not exist'
956 sys.exit(1)
957 mainmodule = os.path.basename(filename)
958 del sys.argv[0] # Hide "pdb.py" from argument list
Guido van Rossumec577d51996-09-10 17:39:34 +0000959
Tim Peters2344fae2001-01-15 00:50:52 +0000960 # Insert script directory in front of module search path
961 sys.path.insert(0, os.path.dirname(filename))
Guido van Rossumf17361d1996-07-30 16:28:13 +0000962
Tim Peters2344fae2001-01-15 00:50:52 +0000963 run('execfile(' + `filename` + ')')