blob: 2a8a9e3fd568794aa058005f433fadea74f4868c [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
Tim Peters6f8ee592001-02-09 23:28:07 +000011from repr import repr as _saferepr
Guido van Rossumb5699c71998-07-20 23:13:54 +000012import os
Barry Warsaw2bee8fe1999-09-09 16:32:41 +000013import re
14
Skip Montanaro352674d2001-02-07 23:14:30 +000015__all__ = ["run", "pm", "Pdb", "runeval", "runctx", "runcall", "set_trace",
16 "post_mortem", "help"]
17
Barry Warsaw2bee8fe1999-09-09 16:32:41 +000018def find_function(funcname, filename):
Tim Peters2344fae2001-01-15 00:50:52 +000019 cre = re.compile(r'def\s+%s\s*[(]' % funcname)
20 try:
21 fp = open(filename)
22 except IOError:
23 return None
24 # consumer of this info expects the first line to be 1
25 lineno = 1
26 answer = None
27 while 1:
28 line = fp.readline()
29 if line == '':
30 break
31 if cre.match(line):
32 answer = funcname, filename, lineno
33 break
34 lineno = lineno + 1
35 fp.close()
36 return answer
Guido van Rossum921c8241992-01-10 14:54:42 +000037
38
Guido van Rossuma558e371994-11-10 22:27:35 +000039# Interaction prompt line will separate file and call info from code
40# text using value of line_prefix string. A newline and arrow may
41# be to your liking. You can set it once pdb is imported using the
42# command "pdb.line_prefix = '\n% '".
Tim Peters2344fae2001-01-15 00:50:52 +000043# line_prefix = ': ' # Use this to get the old situation back
44line_prefix = '\n-> ' # Probably a better default
Guido van Rossuma558e371994-11-10 22:27:35 +000045
Guido van Rossum23efba41992-01-27 16:58:47 +000046class Pdb(bdb.Bdb, cmd.Cmd):
Guido van Rossum2424f851998-09-11 22:50:09 +000047
Tim Peters2344fae2001-01-15 00:50:52 +000048 def __init__(self):
49 bdb.Bdb.__init__(self)
50 cmd.Cmd.__init__(self)
51 self.prompt = '(Pdb) '
52 self.aliases = {}
53 # Try to load readline if it exists
54 try:
55 import readline
56 except ImportError:
57 pass
Guido van Rossum2424f851998-09-11 22:50:09 +000058
Tim Peters2344fae2001-01-15 00:50:52 +000059 # Read $HOME/.pdbrc and ./.pdbrc
60 self.rcLines = []
Raymond Hettinger54f02222002-06-01 14:18:47 +000061 if 'HOME' in os.environ:
Tim Peters2344fae2001-01-15 00:50:52 +000062 envHome = os.environ['HOME']
63 try:
64 rcFile = open(os.path.join(envHome, ".pdbrc"))
65 except IOError:
66 pass
67 else:
68 for line in rcFile.readlines():
69 self.rcLines.append(line)
70 rcFile.close()
71 try:
72 rcFile = open(".pdbrc")
73 except IOError:
74 pass
75 else:
76 for line in rcFile.readlines():
77 self.rcLines.append(line)
78 rcFile.close()
Guido van Rossum23efba41992-01-27 16:58:47 +000079
Tim Peters2344fae2001-01-15 00:50:52 +000080 def reset(self):
81 bdb.Bdb.reset(self)
82 self.forget()
Guido van Rossum23efba41992-01-27 16:58:47 +000083
Tim Peters2344fae2001-01-15 00:50:52 +000084 def forget(self):
85 self.lineno = None
86 self.stack = []
87 self.curindex = 0
88 self.curframe = None
Guido van Rossum2424f851998-09-11 22:50:09 +000089
Tim Peters2344fae2001-01-15 00:50:52 +000090 def setup(self, f, t):
91 self.forget()
92 self.stack, self.curindex = self.get_stack(f, t)
93 self.curframe = self.stack[self.curindex][0]
94 self.execRcLines()
Guido van Rossumb6775db1994-08-01 11:34:53 +000095
Tim Peters2344fae2001-01-15 00:50:52 +000096 # Can be executed earlier than 'setup' if desired
97 def execRcLines(self):
98 if self.rcLines:
99 # Make local copy because of recursion
100 rcLines = self.rcLines
101 # executed only once
102 self.rcLines = []
103 for line in rcLines:
104 line = line[:-1]
Guido van Rossum08454592002-07-12 13:10:53 +0000105 if len(line) > 0 and line[0] != '#':
106 self.onecmd(line)
Guido van Rossum2424f851998-09-11 22:50:09 +0000107
Tim Peters280488b2002-08-23 18:19:30 +0000108 # Override Bdb methods
Michael W. Hudsondd32a912002-08-15 14:59:02 +0000109
110 def user_call(self, frame, argument_list):
111 """This method is called when there is the remote possibility
112 that we ever need to stop in this function."""
113 print '--Call--'
114 self.interaction(frame, None)
Guido van Rossum2424f851998-09-11 22:50:09 +0000115
Tim Peters2344fae2001-01-15 00:50:52 +0000116 def user_line(self, frame):
117 """This function is called when we stop or break at this line."""
118 self.interaction(frame, None)
Guido van Rossum9e1ee971997-07-11 13:43:53 +0000119
Tim Peters2344fae2001-01-15 00:50:52 +0000120 def user_return(self, frame, return_value):
121 """This function is called when a return trap is set here."""
122 frame.f_locals['__return__'] = return_value
123 print '--Return--'
124 self.interaction(frame, None)
Guido van Rossum2424f851998-09-11 22:50:09 +0000125
Tim Peters2344fae2001-01-15 00:50:52 +0000126 def user_exception(self, frame, (exc_type, exc_value, exc_traceback)):
127 """This function is called if an exception occurs,
128 but only if we are to stop at or just below this level."""
129 frame.f_locals['__exception__'] = exc_type, exc_value
130 if type(exc_type) == type(''):
131 exc_type_name = exc_type
132 else: exc_type_name = exc_type.__name__
Tim Peters6f8ee592001-02-09 23:28:07 +0000133 print exc_type_name + ':', _saferepr(exc_value)
Tim Peters2344fae2001-01-15 00:50:52 +0000134 self.interaction(frame, exc_traceback)
Guido van Rossum2424f851998-09-11 22:50:09 +0000135
Tim Peters2344fae2001-01-15 00:50:52 +0000136 # General interaction function
137
138 def interaction(self, frame, traceback):
139 self.setup(frame, traceback)
140 self.print_stack_entry(self.stack[self.curindex])
141 self.cmdloop()
142 self.forget()
143
144 def default(self, line):
145 if line[:1] == '!': line = line[1:]
146 locals = self.curframe.f_locals
147 globals = self.curframe.f_globals
148 try:
149 code = compile(line + '\n', '<stdin>', 'single')
150 exec code in globals, locals
151 except:
152 t, v = sys.exc_info()[:2]
153 if type(t) == type(''):
154 exc_type_name = t
155 else: exc_type_name = t.__name__
156 print '***', exc_type_name + ':', v
157
158 def precmd(self, line):
159 """Handle alias expansion and ';;' separator."""
Guido van Rossum08454592002-07-12 13:10:53 +0000160 if not line.strip():
Tim Peters2344fae2001-01-15 00:50:52 +0000161 return line
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000162 args = line.split()
Raymond Hettinger54f02222002-06-01 14:18:47 +0000163 while args[0] in self.aliases:
Tim Peters2344fae2001-01-15 00:50:52 +0000164 line = self.aliases[args[0]]
165 ii = 1
166 for tmpArg in args[1:]:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000167 line = line.replace("%" + str(ii),
Tim Peters2344fae2001-01-15 00:50:52 +0000168 tmpArg)
169 ii = ii + 1
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000170 line = line.replace("%*", ' '.join(args[1:]))
171 args = line.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000172 # split into ';;' separated commands
173 # unless it's an alias command
174 if args[0] != 'alias':
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000175 marker = line.find(';;')
Tim Peters2344fae2001-01-15 00:50:52 +0000176 if marker >= 0:
177 # queue up everything after marker
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000178 next = line[marker+2:].lstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000179 self.cmdqueue.append(next)
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000180 line = line[:marker].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000181 return line
182
183 # Command definitions, called by cmdloop()
184 # The argument is the remaining string on the command line
185 # Return true to exit from the command loop
186
187 do_h = cmd.Cmd.do_help
188
189 def do_EOF(self, arg):
190 return 0 # Don't die on EOF
191
192 def do_break(self, arg, temporary = 0):
193 # break [ ([filename:]lineno | function) [, "condition"] ]
194 if not arg:
195 if self.breaks: # There's at least one
196 print "Num Type Disp Enb Where"
197 for bp in bdb.Breakpoint.bpbynumber:
198 if bp:
199 bp.bpprint()
200 return
201 # parse arguments; comma has lowest precedence
202 # and cannot occur in filename
203 filename = None
204 lineno = None
205 cond = None
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000206 comma = arg.find(',')
Tim Peters2344fae2001-01-15 00:50:52 +0000207 if comma > 0:
208 # parse stuff after comma: "condition"
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000209 cond = arg[comma+1:].lstrip()
210 arg = arg[:comma].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000211 # parse stuff before comma: [filename:]lineno | function
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000212 colon = arg.rfind(':')
Tim Peters2344fae2001-01-15 00:50:52 +0000213 if colon >= 0:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000214 filename = arg[:colon].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000215 f = self.lookupmodule(filename)
216 if not f:
217 print '*** ', `filename`,
218 print 'not found from sys.path'
219 return
220 else:
221 filename = f
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000222 arg = arg[colon+1:].lstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000223 try:
224 lineno = int(arg)
225 except ValueError, msg:
226 print '*** Bad lineno:', arg
227 return
228 else:
229 # no colon; can be lineno or function
230 try:
231 lineno = int(arg)
232 except ValueError:
233 try:
234 func = eval(arg,
235 self.curframe.f_globals,
236 self.curframe.f_locals)
237 except:
238 func = arg
239 try:
240 if hasattr(func, 'im_func'):
241 func = func.im_func
242 code = func.func_code
243 lineno = code.co_firstlineno
244 filename = code.co_filename
245 except:
246 # last thing to try
247 (ok, filename, ln) = self.lineinfo(arg)
248 if not ok:
249 print '*** The specified object',
250 print `arg`,
251 print 'is not a function'
252 print ('or was not found '
253 'along sys.path.')
254 return
255 lineno = int(ln)
256 if not filename:
257 filename = self.defaultFile()
258 # Check for reasonable breakpoint
259 line = self.checkline(filename, lineno)
260 if line:
261 # now set the break point
262 err = self.set_break(filename, line, temporary, cond)
263 if err: print '***', err
264 else:
265 bp = self.get_breaks(filename, line)[-1]
266 print "Breakpoint %d at %s:%d" % (bp.number,
267 bp.file,
268 bp.line)
269
270 # To be overridden in derived debuggers
271 def defaultFile(self):
272 """Produce a reasonable default."""
273 filename = self.curframe.f_code.co_filename
274 if filename == '<string>' and mainpyfile:
275 filename = mainpyfile
276 return filename
277
278 do_b = do_break
279
280 def do_tbreak(self, arg):
281 self.do_break(arg, 1)
282
283 def lineinfo(self, identifier):
284 failed = (None, None, None)
285 # Input is identifier, may be in single quotes
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000286 idstring = identifier.split("'")
Tim Peters2344fae2001-01-15 00:50:52 +0000287 if len(idstring) == 1:
288 # not in single quotes
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000289 id = idstring[0].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000290 elif len(idstring) == 3:
291 # quoted
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000292 id = idstring[1].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000293 else:
294 return failed
295 if id == '': return failed
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000296 parts = id.split('.')
Tim Peters2344fae2001-01-15 00:50:52 +0000297 # Protection for derived debuggers
298 if parts[0] == 'self':
299 del parts[0]
300 if len(parts) == 0:
301 return failed
302 # Best first guess at file to look at
303 fname = self.defaultFile()
304 if len(parts) == 1:
305 item = parts[0]
306 else:
307 # More than one part.
308 # First is module, second is method/class
309 f = self.lookupmodule(parts[0])
310 if f:
311 fname = f
312 item = parts[1]
313 answer = find_function(item, fname)
314 return answer or failed
315
316 def checkline(self, filename, lineno):
317 """Return line number of first line at or after input
318 argument such that if the input points to a 'def', the
319 returned line number is the first
320 non-blank/non-comment line to follow. If the input
321 points to a blank or comment line, return 0. At end
322 of file, also return 0."""
323
324 line = linecache.getline(filename, lineno)
325 if not line:
326 print 'End of file'
327 return 0
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000328 line = line.strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000329 # Don't allow setting breakpoint at a blank line
Guido van Rossum08454592002-07-12 13:10:53 +0000330 if (not line or (line[0] == '#') or
331 (line[:3] == '"""') or line[:3] == "'''"):
Tim Peters2344fae2001-01-15 00:50:52 +0000332 print '*** Blank or comment'
333 return 0
334 # When a file is read in and a breakpoint is at
335 # the 'def' statement, the system stops there at
336 # code parse time. We don't want that, so all breakpoints
337 # set at 'def' statements are moved one line onward
338 if line[:3] == 'def':
339 instr = ''
340 brackets = 0
341 while 1:
342 skipone = 0
343 for c in line:
344 if instr:
345 if skipone:
346 skipone = 0
347 elif c == '\\':
348 skipone = 1
349 elif c == instr:
350 instr = ''
351 elif c == '#':
352 break
353 elif c in ('"',"'"):
354 instr = c
355 elif c in ('(','{','['):
356 brackets = brackets + 1
357 elif c in (')','}',']'):
358 brackets = brackets - 1
359 lineno = lineno+1
360 line = linecache.getline(filename, lineno)
361 if not line:
362 print 'end of file'
363 return 0
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000364 line = line.strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000365 if not line: continue # Blank line
366 if brackets <= 0 and line[0] not in ('#','"',"'"):
367 break
368 return lineno
369
370 def do_enable(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000371 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000372 for i in args:
373 bp = bdb.Breakpoint.bpbynumber[int(i)]
374 if bp:
375 bp.enable()
376
377 def do_disable(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.disable()
383
384 def do_condition(self, arg):
385 # arg is breakpoint number and condition
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000386 args = arg.split(' ', 1)
387 bpnum = int(args[0].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000388 try:
389 cond = args[1]
390 except:
391 cond = None
392 bp = bdb.Breakpoint.bpbynumber[bpnum]
393 if bp:
394 bp.cond = cond
395 if not cond:
396 print 'Breakpoint', bpnum,
397 print 'is now unconditional.'
398
399 def do_ignore(self,arg):
400 """arg is bp number followed by ignore count."""
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000401 args = arg.split()
402 bpnum = int(args[0].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000403 try:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000404 count = int(args[1].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000405 except:
406 count = 0
407 bp = bdb.Breakpoint.bpbynumber[bpnum]
408 if bp:
409 bp.ignore = count
Guido van Rossum08454592002-07-12 13:10:53 +0000410 if count > 0:
Tim Peters2344fae2001-01-15 00:50:52 +0000411 reply = 'Will ignore next '
Guido van Rossum08454592002-07-12 13:10:53 +0000412 if count > 1:
Tim Peters2344fae2001-01-15 00:50:52 +0000413 reply = reply + '%d crossings' % count
414 else:
415 reply = reply + '1 crossing'
416 print reply + ' of breakpoint %d.' % bpnum
417 else:
418 print 'Will stop next time breakpoint',
419 print bpnum, 'is reached.'
420
421 def do_clear(self, arg):
422 """Three possibilities, tried in this order:
423 clear -> clear all breaks, ask for confirmation
424 clear file:lineno -> clear all breaks at file:lineno
425 clear bpno bpno ... -> clear breakpoints by number"""
426 if not arg:
427 try:
428 reply = raw_input('Clear all breaks? ')
429 except EOFError:
430 reply = 'no'
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000431 reply = reply.strip().lower()
Tim Peters2344fae2001-01-15 00:50:52 +0000432 if reply in ('y', 'yes'):
433 self.clear_all_breaks()
434 return
435 if ':' in arg:
436 # Make sure it works for "clear C:\foo\bar.py:12"
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000437 i = arg.rfind(':')
Tim Peters2344fae2001-01-15 00:50:52 +0000438 filename = arg[:i]
439 arg = arg[i+1:]
440 try:
441 lineno = int(arg)
442 except:
443 err = "Invalid line number (%s)" % arg
444 else:
445 err = self.clear_break(filename, lineno)
446 if err: print '***', err
447 return
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000448 numberlist = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000449 for i in numberlist:
450 err = self.clear_bpbynumber(i)
451 if err:
452 print '***', err
453 else:
454 print 'Deleted breakpoint %s ' % (i,)
455 do_cl = do_clear # 'c' is already an abbreviation for 'continue'
456
457 def do_where(self, arg):
458 self.print_stack_trace()
459 do_w = do_where
Guido van Rossum6bd68352001-01-20 17:57:37 +0000460 do_bt = do_where
Tim Peters2344fae2001-01-15 00:50:52 +0000461
462 def do_up(self, arg):
463 if self.curindex == 0:
464 print '*** Oldest frame'
465 else:
466 self.curindex = self.curindex - 1
467 self.curframe = self.stack[self.curindex][0]
468 self.print_stack_entry(self.stack[self.curindex])
469 self.lineno = None
470 do_u = do_up
471
472 def do_down(self, arg):
473 if self.curindex + 1 == len(self.stack):
474 print '*** Newest frame'
475 else:
476 self.curindex = self.curindex + 1
477 self.curframe = self.stack[self.curindex][0]
478 self.print_stack_entry(self.stack[self.curindex])
479 self.lineno = None
480 do_d = do_down
481
482 def do_step(self, arg):
483 self.set_step()
484 return 1
485 do_s = do_step
486
487 def do_next(self, arg):
488 self.set_next(self.curframe)
489 return 1
490 do_n = do_next
491
492 def do_return(self, arg):
493 self.set_return(self.curframe)
494 return 1
495 do_r = do_return
496
497 def do_continue(self, arg):
498 self.set_continue()
499 return 1
500 do_c = do_cont = do_continue
501
502 def do_quit(self, arg):
503 self.set_quit()
504 return 1
505 do_q = do_quit
Guido van Rossumd1c08f32002-04-15 00:48:24 +0000506 do_exit = do_quit
Tim Peters2344fae2001-01-15 00:50:52 +0000507
508 def do_args(self, arg):
509 f = self.curframe
510 co = f.f_code
511 dict = f.f_locals
512 n = co.co_argcount
513 if co.co_flags & 4: n = n+1
514 if co.co_flags & 8: n = n+1
515 for i in range(n):
516 name = co.co_varnames[i]
517 print name, '=',
Raymond Hettinger54f02222002-06-01 14:18:47 +0000518 if name in dict: print dict[name]
Tim Peters2344fae2001-01-15 00:50:52 +0000519 else: print "*** undefined ***"
520 do_a = do_args
Guido van Rossum2424f851998-09-11 22:50:09 +0000521
Tim Peters2344fae2001-01-15 00:50:52 +0000522 def do_retval(self, arg):
Raymond Hettinger54f02222002-06-01 14:18:47 +0000523 if '__return__' in self.curframe.f_locals:
Tim Peters2344fae2001-01-15 00:50:52 +0000524 print self.curframe.f_locals['__return__']
525 else:
526 print '*** Not yet returned!'
527 do_rv = do_retval
Guido van Rossum2424f851998-09-11 22:50:09 +0000528
Tim Peters2344fae2001-01-15 00:50:52 +0000529 def do_p(self, arg):
530 try:
531 value = eval(arg, self.curframe.f_globals,
532 self.curframe.f_locals)
533 except:
534 t, v = sys.exc_info()[:2]
535 if type(t) == type(''):
536 exc_type_name = t
537 else: exc_type_name = t.__name__
538 print '***', exc_type_name + ':', `v`
539 return
Guido van Rossum2424f851998-09-11 22:50:09 +0000540
Tim Peters2344fae2001-01-15 00:50:52 +0000541 print `value`
Guido van Rossum2424f851998-09-11 22:50:09 +0000542
Tim Peters2344fae2001-01-15 00:50:52 +0000543 def do_list(self, arg):
544 self.lastcmd = 'list'
545 last = None
546 if arg:
547 try:
548 x = eval(arg, {}, {})
549 if type(x) == type(()):
550 first, last = x
551 first = int(first)
552 last = int(last)
553 if last < first:
554 # Assume it's a count
555 last = first + last
556 else:
557 first = max(1, int(x) - 5)
558 except:
559 print '*** Error in argument:', `arg`
560 return
561 elif self.lineno is None:
562 first = max(1, self.curframe.f_lineno - 5)
563 else:
564 first = self.lineno + 1
565 if last is None:
566 last = first + 10
567 filename = self.curframe.f_code.co_filename
568 breaklist = self.get_file_breaks(filename)
569 try:
570 for lineno in range(first, last+1):
571 line = linecache.getline(filename, lineno)
572 if not line:
573 print '[EOF]'
574 break
575 else:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000576 s = `lineno`.rjust(3)
Tim Peters2344fae2001-01-15 00:50:52 +0000577 if len(s) < 4: s = s + ' '
578 if lineno in breaklist: s = s + 'B'
579 else: s = s + ' '
580 if lineno == self.curframe.f_lineno:
581 s = s + '->'
582 print s + '\t' + line,
583 self.lineno = lineno
584 except KeyboardInterrupt:
585 pass
586 do_l = do_list
Guido van Rossum2424f851998-09-11 22:50:09 +0000587
Tim Peters2344fae2001-01-15 00:50:52 +0000588 def do_whatis(self, arg):
589 try:
590 value = eval(arg, self.curframe.f_globals,
591 self.curframe.f_locals)
592 except:
593 t, v = sys.exc_info()[:2]
594 if type(t) == type(''):
595 exc_type_name = t
596 else: exc_type_name = t.__name__
597 print '***', exc_type_name + ':', `v`
598 return
599 code = None
600 # Is it a function?
601 try: code = value.func_code
602 except: pass
603 if code:
604 print 'Function', code.co_name
605 return
606 # Is it an instance method?
607 try: code = value.im_func.func_code
608 except: pass
609 if code:
610 print 'Method', code.co_name
611 return
612 # None of the above...
613 print type(value)
Guido van Rossum8e2ec561993-07-29 09:37:38 +0000614
Tim Peters2344fae2001-01-15 00:50:52 +0000615 def do_alias(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000616 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000617 if len(args) == 0:
618 keys = self.aliases.keys()
619 keys.sort()
620 for alias in keys:
621 print "%s = %s" % (alias, self.aliases[alias])
622 return
Guido van Rossum08454592002-07-12 13:10:53 +0000623 if args[0] in self.aliases and len(args) == 1:
Tim Peters2344fae2001-01-15 00:50:52 +0000624 print "%s = %s" % (args[0], self.aliases[args[0]])
625 else:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000626 self.aliases[args[0]] = ' '.join(args[1:])
Guido van Rossum23efba41992-01-27 16:58:47 +0000627
Tim Peters2344fae2001-01-15 00:50:52 +0000628 def do_unalias(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000629 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000630 if len(args) == 0: return
Raymond Hettinger54f02222002-06-01 14:18:47 +0000631 if args[0] in self.aliases:
Tim Peters2344fae2001-01-15 00:50:52 +0000632 del self.aliases[args[0]]
Guido van Rossum00230781993-03-29 11:39:45 +0000633
Tim Peters2344fae2001-01-15 00:50:52 +0000634 # Print a traceback starting at the top stack frame.
635 # The most recently entered frame is printed last;
636 # this is different from dbx and gdb, but consistent with
637 # the Python interpreter's stack trace.
638 # It is also consistent with the up/down commands (which are
639 # compatible with dbx and gdb: up moves towards 'main()'
640 # and down moves towards the most recent stack frame).
Guido van Rossum2424f851998-09-11 22:50:09 +0000641
Tim Peters2344fae2001-01-15 00:50:52 +0000642 def print_stack_trace(self):
643 try:
644 for frame_lineno in self.stack:
645 self.print_stack_entry(frame_lineno)
646 except KeyboardInterrupt:
647 pass
Guido van Rossum2424f851998-09-11 22:50:09 +0000648
Tim Peters2344fae2001-01-15 00:50:52 +0000649 def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix):
650 frame, lineno = frame_lineno
651 if frame is self.curframe:
652 print '>',
653 else:
654 print ' ',
655 print self.format_stack_entry(frame_lineno, prompt_prefix)
Guido van Rossum2424f851998-09-11 22:50:09 +0000656
Guido van Rossum921c8241992-01-10 14:54:42 +0000657
Tim Peters2344fae2001-01-15 00:50:52 +0000658 # Help methods (derived from pdb.doc)
Guido van Rossum921c8241992-01-10 14:54:42 +0000659
Tim Peters2344fae2001-01-15 00:50:52 +0000660 def help_help(self):
661 self.help_h()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000662
Tim Peters2344fae2001-01-15 00:50:52 +0000663 def help_h(self):
664 print """h(elp)
665Without argument, print the list of available commands.
666With a command name as argument, print help about that command
667"help pdb" pipes the full documentation file to the $PAGER
668"help exec" gives help on the ! command"""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000669
Tim Peters2344fae2001-01-15 00:50:52 +0000670 def help_where(self):
671 self.help_w()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000672
Tim Peters2344fae2001-01-15 00:50:52 +0000673 def help_w(self):
674 print """w(here)
675Print a stack trace, with the most recent frame at the bottom.
676An arrow indicates the "current frame", which determines the
Guido van Rossum6bd68352001-01-20 17:57:37 +0000677context of most commands. 'bt' is an alias for this command."""
678
679 help_bt = help_w
Guido van Rossumb6775db1994-08-01 11:34:53 +0000680
Tim Peters2344fae2001-01-15 00:50:52 +0000681 def help_down(self):
682 self.help_d()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000683
Tim Peters2344fae2001-01-15 00:50:52 +0000684 def help_d(self):
685 print """d(own)
686Move the current frame one level down in the stack trace
687(to an older frame)."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000688
Tim Peters2344fae2001-01-15 00:50:52 +0000689 def help_up(self):
690 self.help_u()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000691
Tim Peters2344fae2001-01-15 00:50:52 +0000692 def help_u(self):
693 print """u(p)
694Move the current frame one level up in the stack trace
695(to a newer frame)."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000696
Tim Peters2344fae2001-01-15 00:50:52 +0000697 def help_break(self):
698 self.help_b()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000699
Tim Peters2344fae2001-01-15 00:50:52 +0000700 def help_b(self):
701 print """b(reak) ([file:]lineno | function) [, condition]
702With a line number argument, set a break there in the current
703file. With a function name, set a break at first executable line
704of that function. Without argument, list all breaks. If a second
705argument is present, it is a string specifying an expression
706which must evaluate to true before the breakpoint is honored.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000707
Tim Peters2344fae2001-01-15 00:50:52 +0000708The line number may be prefixed with a filename and a colon,
709to specify a breakpoint in another file (probably one that
710hasn't been loaded yet). The file is searched for on sys.path;
711the .py suffix may be omitted."""
Guido van Rossumb5699c71998-07-20 23:13:54 +0000712
Tim Peters2344fae2001-01-15 00:50:52 +0000713 def help_clear(self):
714 self.help_cl()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000715
Tim Peters2344fae2001-01-15 00:50:52 +0000716 def help_cl(self):
717 print "cl(ear) filename:lineno"
718 print """cl(ear) [bpnumber [bpnumber...]]
719With a space separated list of breakpoint numbers, clear
720those breakpoints. Without argument, clear all breaks (but
721first ask confirmation). With a filename:lineno argument,
722clear all breaks at that line in that file.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000723
Tim Peters2344fae2001-01-15 00:50:52 +0000724Note that the argument is different from previous versions of
725the debugger (in python distributions 1.5.1 and before) where
726a linenumber was used instead of either filename:lineno or
727breakpoint numbers."""
Guido van Rossumb5699c71998-07-20 23:13:54 +0000728
Tim Peters2344fae2001-01-15 00:50:52 +0000729 def help_tbreak(self):
730 print """tbreak same arguments as break, but breakpoint is
731removed when first hit."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000732
Tim Peters2344fae2001-01-15 00:50:52 +0000733 def help_enable(self):
734 print """enable bpnumber [bpnumber ...]
735Enables the breakpoints given as a space separated list of
736bp numbers."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000737
Tim Peters2344fae2001-01-15 00:50:52 +0000738 def help_disable(self):
739 print """disable bpnumber [bpnumber ...]
740Disables the breakpoints given as a space separated list of
741bp numbers."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000742
Tim Peters2344fae2001-01-15 00:50:52 +0000743 def help_ignore(self):
744 print """ignore bpnumber count
745Sets the ignore count for the given breakpoint number. A breakpoint
746becomes active when the ignore count is zero. When non-zero, the
747count is decremented each time the breakpoint is reached and the
748breakpoint is not disabled and any associated condition evaluates
749to true."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000750
Tim Peters2344fae2001-01-15 00:50:52 +0000751 def help_condition(self):
752 print """condition bpnumber str_condition
753str_condition is a string specifying an expression which
754must evaluate to true before the breakpoint is honored.
755If str_condition is absent, any existing condition is removed;
756i.e., the breakpoint is made unconditional."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000757
Tim Peters2344fae2001-01-15 00:50:52 +0000758 def help_step(self):
759 self.help_s()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000760
Tim Peters2344fae2001-01-15 00:50:52 +0000761 def help_s(self):
762 print """s(tep)
763Execute the current line, stop at the first possible occasion
764(either in a function that is called or in the current function)."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000765
Tim Peters2344fae2001-01-15 00:50:52 +0000766 def help_next(self):
767 self.help_n()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000768
Tim Peters2344fae2001-01-15 00:50:52 +0000769 def help_n(self):
770 print """n(ext)
771Continue execution until the next line in the current function
772is reached or it returns."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000773
Tim Peters2344fae2001-01-15 00:50:52 +0000774 def help_return(self):
775 self.help_r()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000776
Tim Peters2344fae2001-01-15 00:50:52 +0000777 def help_r(self):
778 print """r(eturn)
779Continue execution until the current function returns."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000780
Tim Peters2344fae2001-01-15 00:50:52 +0000781 def help_continue(self):
782 self.help_c()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000783
Tim Peters2344fae2001-01-15 00:50:52 +0000784 def help_cont(self):
785 self.help_c()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000786
Tim Peters2344fae2001-01-15 00:50:52 +0000787 def help_c(self):
788 print """c(ont(inue))
789Continue execution, only stop when a breakpoint is encountered."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000790
Tim Peters2344fae2001-01-15 00:50:52 +0000791 def help_list(self):
792 self.help_l()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000793
Tim Peters2344fae2001-01-15 00:50:52 +0000794 def help_l(self):
795 print """l(ist) [first [,last]]
796List source code for the current file.
797Without arguments, list 11 lines around the current line
798or continue the previous listing.
799With one argument, list 11 lines starting at that line.
800With two arguments, list the given range;
801if the second argument is less than the first, it is a count."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000802
Tim Peters2344fae2001-01-15 00:50:52 +0000803 def help_args(self):
804 self.help_a()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000805
Tim Peters2344fae2001-01-15 00:50:52 +0000806 def help_a(self):
807 print """a(rgs)
808Print the arguments of the current function."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000809
Tim Peters2344fae2001-01-15 00:50:52 +0000810 def help_p(self):
811 print """p expression
812Print the value of the expression."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000813
Tim Peters2344fae2001-01-15 00:50:52 +0000814 def help_exec(self):
815 print """(!) statement
816Execute the (one-line) statement in the context of
817the current stack frame.
818The exclamation point can be omitted unless the first word
819of the statement resembles a debugger command.
820To assign to a global variable you must always prefix the
821command with a 'global' command, e.g.:
822(Pdb) global list_options; list_options = ['-l']
823(Pdb)"""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000824
Tim Peters2344fae2001-01-15 00:50:52 +0000825 def help_quit(self):
826 self.help_q()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000827
Tim Peters2344fae2001-01-15 00:50:52 +0000828 def help_q(self):
Guido van Rossumd1c08f32002-04-15 00:48:24 +0000829 print """q(uit) or exit - Quit from the debugger.
Tim Peters2344fae2001-01-15 00:50:52 +0000830The program being executed is aborted."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000831
Guido van Rossumd1c08f32002-04-15 00:48:24 +0000832 help_exit = help_q
833
Tim Peters2344fae2001-01-15 00:50:52 +0000834 def help_whatis(self):
835 print """whatis arg
836Prints the type of the argument."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000837
Tim Peters2344fae2001-01-15 00:50:52 +0000838 def help_EOF(self):
839 print """EOF
840Handles the receipt of EOF as a command."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000841
Tim Peters2344fae2001-01-15 00:50:52 +0000842 def help_alias(self):
843 print """alias [name [command [parameter parameter ...] ]]
844Creates an alias called 'name' the executes 'command'. The command
845must *not* be enclosed in quotes. Replaceable parameters are
846indicated by %1, %2, and so on, while %* is replaced by all the
847parameters. If no command is given, the current alias for name
848is shown. If no name is given, all aliases are listed.
Guido van Rossum2424f851998-09-11 22:50:09 +0000849
Tim Peters2344fae2001-01-15 00:50:52 +0000850Aliases may be nested and can contain anything that can be
851legally typed at the pdb prompt. Note! You *can* override
852internal pdb commands with aliases! Those internal commands
853are then hidden until the alias is removed. Aliasing is recursively
854applied to the first word of the command line; all other words
855in the line are left alone.
Guido van Rossum2424f851998-09-11 22:50:09 +0000856
Tim Peters2344fae2001-01-15 00:50:52 +0000857Some useful aliases (especially when placed in the .pdbrc file) are:
Guido van Rossum2424f851998-09-11 22:50:09 +0000858
Tim Peters2344fae2001-01-15 00:50:52 +0000859#Print instance variables (usage "pi classInst")
860alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
Guido van Rossum2424f851998-09-11 22:50:09 +0000861
Tim Peters2344fae2001-01-15 00:50:52 +0000862#Print instance variables in self
863alias ps pi self
864"""
Guido van Rossum2424f851998-09-11 22:50:09 +0000865
Tim Peters2344fae2001-01-15 00:50:52 +0000866 def help_unalias(self):
867 print """unalias name
868Deletes the specified alias."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000869
Tim Peters2344fae2001-01-15 00:50:52 +0000870 def help_pdb(self):
871 help()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000872
Tim Peters2344fae2001-01-15 00:50:52 +0000873 def lookupmodule(self, filename):
874 """Helper function for break/clear parsing -- may be overridden."""
875 root, ext = os.path.splitext(filename)
876 if ext == '':
877 filename = filename + '.py'
878 if os.path.isabs(filename):
879 return filename
880 for dirname in sys.path:
881 while os.path.islink(dirname):
882 dirname = os.readlink(dirname)
883 fullname = os.path.join(dirname, filename)
884 if os.path.exists(fullname):
885 return fullname
886 return None
Guido van Rossumb5699c71998-07-20 23:13:54 +0000887
Guido van Rossum35771131992-09-08 11:59:04 +0000888# Simplified interface
889
Guido van Rossum5e38b6f1995-02-27 13:13:40 +0000890def run(statement, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +0000891 Pdb().run(statement, globals, locals)
Guido van Rossum5e38b6f1995-02-27 13:13:40 +0000892
893def runeval(expression, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +0000894 return Pdb().runeval(expression, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000895
896def runctx(statement, globals, locals):
Tim Peters2344fae2001-01-15 00:50:52 +0000897 # B/W compatibility
898 run(statement, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000899
Guido van Rossum4e160981992-09-02 20:43:20 +0000900def runcall(*args):
Tim Peters2344fae2001-01-15 00:50:52 +0000901 return apply(Pdb().runcall, args)
Guido van Rossum4e160981992-09-02 20:43:20 +0000902
Guido van Rossumb6775db1994-08-01 11:34:53 +0000903def set_trace():
Tim Peters2344fae2001-01-15 00:50:52 +0000904 Pdb().set_trace()
Guido van Rossum35771131992-09-08 11:59:04 +0000905
906# Post-Mortem interface
907
908def post_mortem(t):
Tim Peters2344fae2001-01-15 00:50:52 +0000909 p = Pdb()
910 p.reset()
911 while t.tb_next is not None:
912 t = t.tb_next
913 p.interaction(t.tb_frame, t)
Guido van Rossum35771131992-09-08 11:59:04 +0000914
915def pm():
Tim Peters2344fae2001-01-15 00:50:52 +0000916 post_mortem(sys.last_traceback)
Guido van Rossum35771131992-09-08 11:59:04 +0000917
918
919# Main program for testing
920
Guido van Rossum23efba41992-01-27 16:58:47 +0000921TESTCMD = 'import x; x.main()'
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000922
Guido van Rossum921c8241992-01-10 14:54:42 +0000923def test():
Tim Peters2344fae2001-01-15 00:50:52 +0000924 run(TESTCMD)
Guido van Rossume61fa0a1993-10-22 13:56:35 +0000925
926# print help
927def help():
Tim Peters2344fae2001-01-15 00:50:52 +0000928 for dirname in sys.path:
929 fullname = os.path.join(dirname, 'pdb.doc')
930 if os.path.exists(fullname):
931 sts = os.system('${PAGER-more} '+fullname)
932 if sts: print '*** Pager exit status:', sts
933 break
934 else:
935 print 'Sorry, can\'t find the help file "pdb.doc"',
936 print 'along the Python search path'
Guido van Rossumf17361d1996-07-30 16:28:13 +0000937
Guido van Rossumb5699c71998-07-20 23:13:54 +0000938mainmodule = ''
939mainpyfile = ''
940
Guido van Rossumf17361d1996-07-30 16:28:13 +0000941# When invoked as main program, invoke the debugger on a script
942if __name__=='__main__':
Tim Peters2344fae2001-01-15 00:50:52 +0000943 if not sys.argv[1:]:
944 print "usage: pdb.py scriptfile [arg] ..."
945 sys.exit(2)
Guido van Rossumf17361d1996-07-30 16:28:13 +0000946
Tim Peters2344fae2001-01-15 00:50:52 +0000947 mainpyfile = filename = sys.argv[1] # Get script filename
948 if not os.path.exists(filename):
949 print 'Error:', `filename`, 'does not exist'
950 sys.exit(1)
951 mainmodule = os.path.basename(filename)
952 del sys.argv[0] # Hide "pdb.py" from argument list
Guido van Rossumec577d51996-09-10 17:39:34 +0000953
Tim Peters2344fae2001-01-15 00:50:52 +0000954 # Insert script directory in front of module search path
955 sys.path.insert(0, os.path.dirname(filename))
Guido van Rossumf17361d1996-07-30 16:28:13 +0000956
Tim Peters2344fae2001-01-15 00:50:52 +0000957 run('execfile(' + `filename` + ')')