blob: 94518aebf65e5e15882c7b6d7d4d56213579266d [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
509 def do_quit(self, arg):
510 self.set_quit()
511 return 1
512 do_q = do_quit
Guido van Rossumd1c08f32002-04-15 00:48:24 +0000513 do_exit = do_quit
Tim Peters2344fae2001-01-15 00:50:52 +0000514
515 def do_args(self, arg):
516 f = self.curframe
517 co = f.f_code
518 dict = f.f_locals
519 n = co.co_argcount
520 if co.co_flags & 4: n = n+1
521 if co.co_flags & 8: n = n+1
522 for i in range(n):
523 name = co.co_varnames[i]
524 print name, '=',
Raymond Hettinger54f02222002-06-01 14:18:47 +0000525 if name in dict: print dict[name]
Tim Peters2344fae2001-01-15 00:50:52 +0000526 else: print "*** undefined ***"
527 do_a = do_args
Guido van Rossum2424f851998-09-11 22:50:09 +0000528
Tim Peters2344fae2001-01-15 00:50:52 +0000529 def do_retval(self, arg):
Raymond Hettinger54f02222002-06-01 14:18:47 +0000530 if '__return__' in self.curframe.f_locals:
Tim Peters2344fae2001-01-15 00:50:52 +0000531 print self.curframe.f_locals['__return__']
532 else:
533 print '*** Not yet returned!'
534 do_rv = do_retval
Guido van Rossum2424f851998-09-11 22:50:09 +0000535
Barry Warsaw210bd202002-11-05 22:40:20 +0000536 def _getval(self, arg):
Tim Peters2344fae2001-01-15 00:50:52 +0000537 try:
Barry Warsaw210bd202002-11-05 22:40:20 +0000538 return eval(arg, self.curframe.f_globals,
539 self.curframe.f_locals)
Tim Peters2344fae2001-01-15 00:50:52 +0000540 except:
541 t, v = sys.exc_info()[:2]
Barry Warsaw210bd202002-11-05 22:40:20 +0000542 if isinstance(t, str):
Tim Peters2344fae2001-01-15 00:50:52 +0000543 exc_type_name = t
544 else: exc_type_name = t.__name__
545 print '***', exc_type_name + ':', `v`
Barry Warsaw210bd202002-11-05 22:40:20 +0000546 raise
Guido van Rossum2424f851998-09-11 22:50:09 +0000547
Barry Warsaw210bd202002-11-05 22:40:20 +0000548 def do_p(self, arg):
549 try:
550 print repr(self._getval(arg))
551 except:
552 pass
553
554 def do_pp(self, arg):
555 try:
556 pprint.pprint(self._getval(arg))
557 except:
558 pass
Guido van Rossum2424f851998-09-11 22:50:09 +0000559
Tim Peters2344fae2001-01-15 00:50:52 +0000560 def do_list(self, arg):
561 self.lastcmd = 'list'
562 last = None
563 if arg:
564 try:
565 x = eval(arg, {}, {})
566 if type(x) == type(()):
567 first, last = x
568 first = int(first)
569 last = int(last)
570 if last < first:
571 # Assume it's a count
572 last = first + last
573 else:
574 first = max(1, int(x) - 5)
575 except:
576 print '*** Error in argument:', `arg`
577 return
578 elif self.lineno is None:
579 first = max(1, self.curframe.f_lineno - 5)
580 else:
581 first = self.lineno + 1
582 if last is None:
583 last = first + 10
584 filename = self.curframe.f_code.co_filename
585 breaklist = self.get_file_breaks(filename)
586 try:
587 for lineno in range(first, last+1):
588 line = linecache.getline(filename, lineno)
589 if not line:
590 print '[EOF]'
591 break
592 else:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000593 s = `lineno`.rjust(3)
Tim Peters2344fae2001-01-15 00:50:52 +0000594 if len(s) < 4: s = s + ' '
595 if lineno in breaklist: s = s + 'B'
596 else: s = s + ' '
597 if lineno == self.curframe.f_lineno:
598 s = s + '->'
599 print s + '\t' + line,
600 self.lineno = lineno
601 except KeyboardInterrupt:
602 pass
603 do_l = do_list
Guido van Rossum2424f851998-09-11 22:50:09 +0000604
Tim Peters2344fae2001-01-15 00:50:52 +0000605 def do_whatis(self, arg):
606 try:
607 value = eval(arg, self.curframe.f_globals,
608 self.curframe.f_locals)
609 except:
610 t, v = sys.exc_info()[:2]
611 if type(t) == type(''):
612 exc_type_name = t
613 else: exc_type_name = t.__name__
614 print '***', exc_type_name + ':', `v`
615 return
616 code = None
617 # Is it a function?
618 try: code = value.func_code
619 except: pass
620 if code:
621 print 'Function', code.co_name
622 return
623 # Is it an instance method?
624 try: code = value.im_func.func_code
625 except: pass
626 if code:
627 print 'Method', code.co_name
628 return
629 # None of the above...
630 print type(value)
Guido van Rossum8e2ec561993-07-29 09:37:38 +0000631
Tim Peters2344fae2001-01-15 00:50:52 +0000632 def do_alias(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000633 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000634 if len(args) == 0:
635 keys = self.aliases.keys()
636 keys.sort()
637 for alias in keys:
638 print "%s = %s" % (alias, self.aliases[alias])
639 return
Guido van Rossum08454592002-07-12 13:10:53 +0000640 if args[0] in self.aliases and len(args) == 1:
Tim Peters2344fae2001-01-15 00:50:52 +0000641 print "%s = %s" % (args[0], self.aliases[args[0]])
642 else:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000643 self.aliases[args[0]] = ' '.join(args[1:])
Guido van Rossum23efba41992-01-27 16:58:47 +0000644
Tim Peters2344fae2001-01-15 00:50:52 +0000645 def do_unalias(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000646 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000647 if len(args) == 0: return
Raymond Hettinger54f02222002-06-01 14:18:47 +0000648 if args[0] in self.aliases:
Tim Peters2344fae2001-01-15 00:50:52 +0000649 del self.aliases[args[0]]
Guido van Rossum00230781993-03-29 11:39:45 +0000650
Tim Peters2344fae2001-01-15 00:50:52 +0000651 # Print a traceback starting at the top stack frame.
652 # The most recently entered frame is printed last;
653 # this is different from dbx and gdb, but consistent with
654 # the Python interpreter's stack trace.
655 # It is also consistent with the up/down commands (which are
656 # compatible with dbx and gdb: up moves towards 'main()'
657 # and down moves towards the most recent stack frame).
Guido van Rossum2424f851998-09-11 22:50:09 +0000658
Tim Peters2344fae2001-01-15 00:50:52 +0000659 def print_stack_trace(self):
660 try:
661 for frame_lineno in self.stack:
662 self.print_stack_entry(frame_lineno)
663 except KeyboardInterrupt:
664 pass
Guido van Rossum2424f851998-09-11 22:50:09 +0000665
Tim Peters2344fae2001-01-15 00:50:52 +0000666 def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix):
667 frame, lineno = frame_lineno
668 if frame is self.curframe:
669 print '>',
670 else:
671 print ' ',
672 print self.format_stack_entry(frame_lineno, prompt_prefix)
Guido van Rossum2424f851998-09-11 22:50:09 +0000673
Guido van Rossum921c8241992-01-10 14:54:42 +0000674
Tim Peters2344fae2001-01-15 00:50:52 +0000675 # Help methods (derived from pdb.doc)
Guido van Rossum921c8241992-01-10 14:54:42 +0000676
Tim Peters2344fae2001-01-15 00:50:52 +0000677 def help_help(self):
678 self.help_h()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000679
Tim Peters2344fae2001-01-15 00:50:52 +0000680 def help_h(self):
681 print """h(elp)
682Without argument, print the list of available commands.
683With a command name as argument, print help about that command
684"help pdb" pipes the full documentation file to the $PAGER
685"help exec" gives help on the ! command"""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000686
Tim Peters2344fae2001-01-15 00:50:52 +0000687 def help_where(self):
688 self.help_w()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000689
Tim Peters2344fae2001-01-15 00:50:52 +0000690 def help_w(self):
691 print """w(here)
692Print a stack trace, with the most recent frame at the bottom.
693An arrow indicates the "current frame", which determines the
Guido van Rossum6bd68352001-01-20 17:57:37 +0000694context of most commands. 'bt' is an alias for this command."""
695
696 help_bt = help_w
Guido van Rossumb6775db1994-08-01 11:34:53 +0000697
Tim Peters2344fae2001-01-15 00:50:52 +0000698 def help_down(self):
699 self.help_d()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000700
Tim Peters2344fae2001-01-15 00:50:52 +0000701 def help_d(self):
702 print """d(own)
703Move the current frame one level down in the stack trace
704(to an older frame)."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000705
Tim Peters2344fae2001-01-15 00:50:52 +0000706 def help_up(self):
707 self.help_u()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000708
Tim Peters2344fae2001-01-15 00:50:52 +0000709 def help_u(self):
710 print """u(p)
711Move the current frame one level up in the stack trace
712(to a newer frame)."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000713
Tim Peters2344fae2001-01-15 00:50:52 +0000714 def help_break(self):
715 self.help_b()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000716
Tim Peters2344fae2001-01-15 00:50:52 +0000717 def help_b(self):
718 print """b(reak) ([file:]lineno | function) [, condition]
719With a line number argument, set a break there in the current
720file. With a function name, set a break at first executable line
721of that function. Without argument, list all breaks. If a second
722argument is present, it is a string specifying an expression
723which must evaluate to true before the breakpoint is honored.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000724
Tim Peters2344fae2001-01-15 00:50:52 +0000725The line number may be prefixed with a filename and a colon,
726to specify a breakpoint in another file (probably one that
727hasn't been loaded yet). The file is searched for on sys.path;
728the .py suffix may be omitted."""
Guido van Rossumb5699c71998-07-20 23:13:54 +0000729
Tim Peters2344fae2001-01-15 00:50:52 +0000730 def help_clear(self):
731 self.help_cl()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000732
Tim Peters2344fae2001-01-15 00:50:52 +0000733 def help_cl(self):
734 print "cl(ear) filename:lineno"
735 print """cl(ear) [bpnumber [bpnumber...]]
736With a space separated list of breakpoint numbers, clear
737those breakpoints. Without argument, clear all breaks (but
738first ask confirmation). With a filename:lineno argument,
739clear all breaks at that line in that file.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000740
Tim Peters2344fae2001-01-15 00:50:52 +0000741Note that the argument is different from previous versions of
742the debugger (in python distributions 1.5.1 and before) where
743a linenumber was used instead of either filename:lineno or
744breakpoint numbers."""
Guido van Rossumb5699c71998-07-20 23:13:54 +0000745
Tim Peters2344fae2001-01-15 00:50:52 +0000746 def help_tbreak(self):
747 print """tbreak same arguments as break, but breakpoint is
748removed when first hit."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000749
Tim Peters2344fae2001-01-15 00:50:52 +0000750 def help_enable(self):
751 print """enable bpnumber [bpnumber ...]
752Enables the breakpoints given as a space separated list of
753bp numbers."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000754
Tim Peters2344fae2001-01-15 00:50:52 +0000755 def help_disable(self):
756 print """disable bpnumber [bpnumber ...]
757Disables the breakpoints given as a space separated list of
758bp numbers."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000759
Tim Peters2344fae2001-01-15 00:50:52 +0000760 def help_ignore(self):
761 print """ignore bpnumber count
762Sets the ignore count for the given breakpoint number. A breakpoint
763becomes active when the ignore count is zero. When non-zero, the
764count is decremented each time the breakpoint is reached and the
765breakpoint is not disabled and any associated condition evaluates
766to true."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000767
Tim Peters2344fae2001-01-15 00:50:52 +0000768 def help_condition(self):
769 print """condition bpnumber str_condition
770str_condition is a string specifying an expression which
771must evaluate to true before the breakpoint is honored.
772If str_condition is absent, any existing condition is removed;
773i.e., the breakpoint is made unconditional."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000774
Tim Peters2344fae2001-01-15 00:50:52 +0000775 def help_step(self):
776 self.help_s()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000777
Tim Peters2344fae2001-01-15 00:50:52 +0000778 def help_s(self):
779 print """s(tep)
780Execute the current line, stop at the first possible occasion
781(either in a function that is called or in the current function)."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000782
Tim Peters2344fae2001-01-15 00:50:52 +0000783 def help_next(self):
784 self.help_n()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000785
Tim Peters2344fae2001-01-15 00:50:52 +0000786 def help_n(self):
787 print """n(ext)
788Continue execution until the next line in the current function
789is reached or it returns."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000790
Tim Peters2344fae2001-01-15 00:50:52 +0000791 def help_return(self):
792 self.help_r()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000793
Tim Peters2344fae2001-01-15 00:50:52 +0000794 def help_r(self):
795 print """r(eturn)
796Continue execution until the current function returns."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000797
Tim Peters2344fae2001-01-15 00:50:52 +0000798 def help_continue(self):
799 self.help_c()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000800
Tim Peters2344fae2001-01-15 00:50:52 +0000801 def help_cont(self):
802 self.help_c()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000803
Tim Peters2344fae2001-01-15 00:50:52 +0000804 def help_c(self):
805 print """c(ont(inue))
806Continue execution, only stop when a breakpoint is encountered."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000807
Tim Peters2344fae2001-01-15 00:50:52 +0000808 def help_list(self):
809 self.help_l()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000810
Tim Peters2344fae2001-01-15 00:50:52 +0000811 def help_l(self):
812 print """l(ist) [first [,last]]
813List source code for the current file.
814Without arguments, list 11 lines around the current line
815or continue the previous listing.
816With one argument, list 11 lines starting at that line.
817With two arguments, list the given range;
818if the second argument is less than the first, it is a count."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000819
Tim Peters2344fae2001-01-15 00:50:52 +0000820 def help_args(self):
821 self.help_a()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000822
Tim Peters2344fae2001-01-15 00:50:52 +0000823 def help_a(self):
824 print """a(rgs)
825Print the arguments of the current function."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000826
Tim Peters2344fae2001-01-15 00:50:52 +0000827 def help_p(self):
828 print """p expression
829Print the value of the expression."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000830
Barry Warsaw210bd202002-11-05 22:40:20 +0000831 def help_pp(self):
832 print """pp expression
833Pretty-print the value of the expression."""
834
Tim Peters2344fae2001-01-15 00:50:52 +0000835 def help_exec(self):
836 print """(!) statement
837Execute the (one-line) statement in the context of
838the current stack frame.
839The exclamation point can be omitted unless the first word
840of the statement resembles a debugger command.
841To assign to a global variable you must always prefix the
842command with a 'global' command, e.g.:
843(Pdb) global list_options; list_options = ['-l']
844(Pdb)"""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000845
Tim Peters2344fae2001-01-15 00:50:52 +0000846 def help_quit(self):
847 self.help_q()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000848
Tim Peters2344fae2001-01-15 00:50:52 +0000849 def help_q(self):
Guido van Rossumd1c08f32002-04-15 00:48:24 +0000850 print """q(uit) or exit - Quit from the debugger.
Tim Peters2344fae2001-01-15 00:50:52 +0000851The program being executed is aborted."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000852
Guido van Rossumd1c08f32002-04-15 00:48:24 +0000853 help_exit = help_q
854
Tim Peters2344fae2001-01-15 00:50:52 +0000855 def help_whatis(self):
856 print """whatis arg
857Prints the type of the argument."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000858
Tim Peters2344fae2001-01-15 00:50:52 +0000859 def help_EOF(self):
860 print """EOF
861Handles the receipt of EOF as a command."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000862
Tim Peters2344fae2001-01-15 00:50:52 +0000863 def help_alias(self):
864 print """alias [name [command [parameter parameter ...] ]]
865Creates an alias called 'name' the executes 'command'. The command
866must *not* be enclosed in quotes. Replaceable parameters are
867indicated by %1, %2, and so on, while %* is replaced by all the
868parameters. If no command is given, the current alias for name
869is shown. If no name is given, all aliases are listed.
Guido van Rossum2424f851998-09-11 22:50:09 +0000870
Tim Peters2344fae2001-01-15 00:50:52 +0000871Aliases may be nested and can contain anything that can be
872legally typed at the pdb prompt. Note! You *can* override
873internal pdb commands with aliases! Those internal commands
874are then hidden until the alias is removed. Aliasing is recursively
875applied to the first word of the command line; all other words
876in the line are left alone.
Guido van Rossum2424f851998-09-11 22:50:09 +0000877
Tim Peters2344fae2001-01-15 00:50:52 +0000878Some useful aliases (especially when placed in the .pdbrc file) are:
Guido van Rossum2424f851998-09-11 22:50:09 +0000879
Tim Peters2344fae2001-01-15 00:50:52 +0000880#Print instance variables (usage "pi classInst")
881alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
Guido van Rossum2424f851998-09-11 22:50:09 +0000882
Tim Peters2344fae2001-01-15 00:50:52 +0000883#Print instance variables in self
884alias ps pi self
885"""
Guido van Rossum2424f851998-09-11 22:50:09 +0000886
Tim Peters2344fae2001-01-15 00:50:52 +0000887 def help_unalias(self):
888 print """unalias name
889Deletes the specified alias."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000890
Tim Peters2344fae2001-01-15 00:50:52 +0000891 def help_pdb(self):
892 help()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000893
Tim Peters2344fae2001-01-15 00:50:52 +0000894 def lookupmodule(self, filename):
895 """Helper function for break/clear parsing -- may be overridden."""
896 root, ext = os.path.splitext(filename)
897 if ext == '':
898 filename = filename + '.py'
899 if os.path.isabs(filename):
900 return filename
901 for dirname in sys.path:
902 while os.path.islink(dirname):
903 dirname = os.readlink(dirname)
904 fullname = os.path.join(dirname, filename)
905 if os.path.exists(fullname):
906 return fullname
907 return None
Guido van Rossumb5699c71998-07-20 23:13:54 +0000908
Guido van Rossum35771131992-09-08 11:59:04 +0000909# Simplified interface
910
Guido van Rossum5e38b6f1995-02-27 13:13:40 +0000911def run(statement, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +0000912 Pdb().run(statement, globals, locals)
Guido van Rossum5e38b6f1995-02-27 13:13:40 +0000913
914def runeval(expression, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +0000915 return Pdb().runeval(expression, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000916
917def runctx(statement, globals, locals):
Tim Peters2344fae2001-01-15 00:50:52 +0000918 # B/W compatibility
919 run(statement, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000920
Guido van Rossum4e160981992-09-02 20:43:20 +0000921def runcall(*args):
Tim Peters2344fae2001-01-15 00:50:52 +0000922 return apply(Pdb().runcall, args)
Guido van Rossum4e160981992-09-02 20:43:20 +0000923
Guido van Rossumb6775db1994-08-01 11:34:53 +0000924def set_trace():
Tim Peters2344fae2001-01-15 00:50:52 +0000925 Pdb().set_trace()
Guido van Rossum35771131992-09-08 11:59:04 +0000926
927# Post-Mortem interface
928
929def post_mortem(t):
Tim Peters2344fae2001-01-15 00:50:52 +0000930 p = Pdb()
931 p.reset()
932 while t.tb_next is not None:
933 t = t.tb_next
934 p.interaction(t.tb_frame, t)
Guido van Rossum35771131992-09-08 11:59:04 +0000935
936def pm():
Tim Peters2344fae2001-01-15 00:50:52 +0000937 post_mortem(sys.last_traceback)
Guido van Rossum35771131992-09-08 11:59:04 +0000938
939
940# Main program for testing
941
Guido van Rossum23efba41992-01-27 16:58:47 +0000942TESTCMD = 'import x; x.main()'
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000943
Guido van Rossum921c8241992-01-10 14:54:42 +0000944def test():
Tim Peters2344fae2001-01-15 00:50:52 +0000945 run(TESTCMD)
Guido van Rossume61fa0a1993-10-22 13:56:35 +0000946
947# print help
948def help():
Tim Peters2344fae2001-01-15 00:50:52 +0000949 for dirname in sys.path:
950 fullname = os.path.join(dirname, 'pdb.doc')
951 if os.path.exists(fullname):
952 sts = os.system('${PAGER-more} '+fullname)
953 if sts: print '*** Pager exit status:', sts
954 break
955 else:
956 print 'Sorry, can\'t find the help file "pdb.doc"',
957 print 'along the Python search path'
Guido van Rossumf17361d1996-07-30 16:28:13 +0000958
Guido van Rossumb5699c71998-07-20 23:13:54 +0000959mainmodule = ''
960mainpyfile = ''
961
Guido van Rossumf17361d1996-07-30 16:28:13 +0000962# When invoked as main program, invoke the debugger on a script
963if __name__=='__main__':
Tim Peters2344fae2001-01-15 00:50:52 +0000964 if not sys.argv[1:]:
965 print "usage: pdb.py scriptfile [arg] ..."
966 sys.exit(2)
Guido van Rossumf17361d1996-07-30 16:28:13 +0000967
Tim Peters2344fae2001-01-15 00:50:52 +0000968 mainpyfile = filename = sys.argv[1] # Get script filename
969 if not os.path.exists(filename):
970 print 'Error:', `filename`, 'does not exist'
971 sys.exit(1)
972 mainmodule = os.path.basename(filename)
973 del sys.argv[0] # Hide "pdb.py" from argument list
Guido van Rossumec577d51996-09-10 17:39:34 +0000974
Tim Peters2344fae2001-01-15 00:50:52 +0000975 # Insert script directory in front of module search path
976 sys.path.insert(0, os.path.dirname(filename))
Guido van Rossumf17361d1996-07-30 16:28:13 +0000977
Tim Peters2344fae2001-01-15 00:50:52 +0000978 run('execfile(' + `filename` + ')')