blob: 75f05560baf41aae159ce1dd49ec88904f9b6157 [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 = []
61 if os.environ.has_key('HOME'):
62 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]
105 if len (line) > 0 and line[0] != '#':
106 self.onecmd (line)
Guido van Rossum2424f851998-09-11 22:50:09 +0000107
Tim Peters2344fae2001-01-15 00:50:52 +0000108 # Override Bdb methods (except user_call, for now)
Guido van Rossum2424f851998-09-11 22:50:09 +0000109
Tim Peters2344fae2001-01-15 00:50:52 +0000110 def user_line(self, frame):
111 """This function is called when we stop or break at this line."""
112 self.interaction(frame, None)
Guido van Rossum9e1ee971997-07-11 13:43:53 +0000113
Tim Peters2344fae2001-01-15 00:50:52 +0000114 def user_return(self, frame, return_value):
115 """This function is called when a return trap is set here."""
116 frame.f_locals['__return__'] = return_value
117 print '--Return--'
118 self.interaction(frame, None)
Guido van Rossum2424f851998-09-11 22:50:09 +0000119
Tim Peters2344fae2001-01-15 00:50:52 +0000120 def user_exception(self, frame, (exc_type, exc_value, exc_traceback)):
121 """This function is called if an exception occurs,
122 but only if we are to stop at or just below this level."""
123 frame.f_locals['__exception__'] = exc_type, exc_value
124 if type(exc_type) == type(''):
125 exc_type_name = exc_type
126 else: exc_type_name = exc_type.__name__
Tim Peters6f8ee592001-02-09 23:28:07 +0000127 print exc_type_name + ':', _saferepr(exc_value)
Tim Peters2344fae2001-01-15 00:50:52 +0000128 self.interaction(frame, exc_traceback)
Guido van Rossum2424f851998-09-11 22:50:09 +0000129
Tim Peters2344fae2001-01-15 00:50:52 +0000130 # General interaction function
131
132 def interaction(self, frame, traceback):
133 self.setup(frame, traceback)
134 self.print_stack_entry(self.stack[self.curindex])
135 self.cmdloop()
136 self.forget()
137
138 def default(self, line):
139 if line[:1] == '!': line = line[1:]
140 locals = self.curframe.f_locals
141 globals = self.curframe.f_globals
142 try:
143 code = compile(line + '\n', '<stdin>', 'single')
144 exec code in globals, locals
145 except:
146 t, v = sys.exc_info()[:2]
147 if type(t) == type(''):
148 exc_type_name = t
149 else: exc_type_name = t.__name__
150 print '***', exc_type_name + ':', v
151
152 def precmd(self, line):
153 """Handle alias expansion and ';;' separator."""
154 if not line:
155 return line
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000156 args = line.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000157 while self.aliases.has_key(args[0]):
158 line = self.aliases[args[0]]
159 ii = 1
160 for tmpArg in args[1:]:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000161 line = line.replace("%" + str(ii),
Tim Peters2344fae2001-01-15 00:50:52 +0000162 tmpArg)
163 ii = ii + 1
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000164 line = line.replace("%*", ' '.join(args[1:]))
165 args = line.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000166 # split into ';;' separated commands
167 # unless it's an alias command
168 if args[0] != 'alias':
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000169 marker = line.find(';;')
Tim Peters2344fae2001-01-15 00:50:52 +0000170 if marker >= 0:
171 # queue up everything after marker
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000172 next = line[marker+2:].lstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000173 self.cmdqueue.append(next)
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000174 line = line[:marker].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000175 return line
176
177 # Command definitions, called by cmdloop()
178 # The argument is the remaining string on the command line
179 # Return true to exit from the command loop
180
181 do_h = cmd.Cmd.do_help
182
183 def do_EOF(self, arg):
184 return 0 # Don't die on EOF
185
186 def do_break(self, arg, temporary = 0):
187 # break [ ([filename:]lineno | function) [, "condition"] ]
188 if not arg:
189 if self.breaks: # There's at least one
190 print "Num Type Disp Enb Where"
191 for bp in bdb.Breakpoint.bpbynumber:
192 if bp:
193 bp.bpprint()
194 return
195 # parse arguments; comma has lowest precedence
196 # and cannot occur in filename
197 filename = None
198 lineno = None
199 cond = None
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000200 comma = arg.find(',')
Tim Peters2344fae2001-01-15 00:50:52 +0000201 if comma > 0:
202 # parse stuff after comma: "condition"
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000203 cond = arg[comma+1:].lstrip()
204 arg = arg[:comma].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000205 # parse stuff before comma: [filename:]lineno | function
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000206 colon = arg.rfind(':')
Tim Peters2344fae2001-01-15 00:50:52 +0000207 if colon >= 0:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000208 filename = arg[:colon].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000209 f = self.lookupmodule(filename)
210 if not f:
211 print '*** ', `filename`,
212 print 'not found from sys.path'
213 return
214 else:
215 filename = f
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000216 arg = arg[colon+1:].lstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000217 try:
218 lineno = int(arg)
219 except ValueError, msg:
220 print '*** Bad lineno:', arg
221 return
222 else:
223 # no colon; can be lineno or function
224 try:
225 lineno = int(arg)
226 except ValueError:
227 try:
228 func = eval(arg,
229 self.curframe.f_globals,
230 self.curframe.f_locals)
231 except:
232 func = arg
233 try:
234 if hasattr(func, 'im_func'):
235 func = func.im_func
236 code = func.func_code
237 lineno = code.co_firstlineno
238 filename = code.co_filename
239 except:
240 # last thing to try
241 (ok, filename, ln) = self.lineinfo(arg)
242 if not ok:
243 print '*** The specified object',
244 print `arg`,
245 print 'is not a function'
246 print ('or was not found '
247 'along sys.path.')
248 return
249 lineno = int(ln)
250 if not filename:
251 filename = self.defaultFile()
252 # Check for reasonable breakpoint
253 line = self.checkline(filename, lineno)
254 if line:
255 # now set the break point
256 err = self.set_break(filename, line, temporary, cond)
257 if err: print '***', err
258 else:
259 bp = self.get_breaks(filename, line)[-1]
260 print "Breakpoint %d at %s:%d" % (bp.number,
261 bp.file,
262 bp.line)
263
264 # To be overridden in derived debuggers
265 def defaultFile(self):
266 """Produce a reasonable default."""
267 filename = self.curframe.f_code.co_filename
268 if filename == '<string>' and mainpyfile:
269 filename = mainpyfile
270 return filename
271
272 do_b = do_break
273
274 def do_tbreak(self, arg):
275 self.do_break(arg, 1)
276
277 def lineinfo(self, identifier):
278 failed = (None, None, None)
279 # Input is identifier, may be in single quotes
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000280 idstring = identifier.split("'")
Tim Peters2344fae2001-01-15 00:50:52 +0000281 if len(idstring) == 1:
282 # not in single quotes
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000283 id = idstring[0].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000284 elif len(idstring) == 3:
285 # quoted
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000286 id = idstring[1].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000287 else:
288 return failed
289 if id == '': return failed
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000290 parts = id.split('.')
Tim Peters2344fae2001-01-15 00:50:52 +0000291 # Protection for derived debuggers
292 if parts[0] == 'self':
293 del parts[0]
294 if len(parts) == 0:
295 return failed
296 # Best first guess at file to look at
297 fname = self.defaultFile()
298 if len(parts) == 1:
299 item = parts[0]
300 else:
301 # More than one part.
302 # First is module, second is method/class
303 f = self.lookupmodule(parts[0])
304 if f:
305 fname = f
306 item = parts[1]
307 answer = find_function(item, fname)
308 return answer or failed
309
310 def checkline(self, filename, lineno):
311 """Return line number of first line at or after input
312 argument such that if the input points to a 'def', the
313 returned line number is the first
314 non-blank/non-comment line to follow. If the input
315 points to a blank or comment line, return 0. At end
316 of file, also return 0."""
317
318 line = linecache.getline(filename, lineno)
319 if not line:
320 print 'End of file'
321 return 0
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000322 line = line.strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000323 # Don't allow setting breakpoint at a blank line
324 if ( not line or (line[0] == '#') or
325 (line[:3] == '"""') or line[:3] == "'''" ):
326 print '*** Blank or comment'
327 return 0
328 # When a file is read in and a breakpoint is at
329 # the 'def' statement, the system stops there at
330 # code parse time. We don't want that, so all breakpoints
331 # set at 'def' statements are moved one line onward
332 if line[:3] == 'def':
333 instr = ''
334 brackets = 0
335 while 1:
336 skipone = 0
337 for c in line:
338 if instr:
339 if skipone:
340 skipone = 0
341 elif c == '\\':
342 skipone = 1
343 elif c == instr:
344 instr = ''
345 elif c == '#':
346 break
347 elif c in ('"',"'"):
348 instr = c
349 elif c in ('(','{','['):
350 brackets = brackets + 1
351 elif c in (')','}',']'):
352 brackets = brackets - 1
353 lineno = lineno+1
354 line = linecache.getline(filename, lineno)
355 if not line:
356 print 'end of file'
357 return 0
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000358 line = line.strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000359 if not line: continue # Blank line
360 if brackets <= 0 and line[0] not in ('#','"',"'"):
361 break
362 return lineno
363
364 def do_enable(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000365 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000366 for i in args:
367 bp = bdb.Breakpoint.bpbynumber[int(i)]
368 if bp:
369 bp.enable()
370
371 def do_disable(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000372 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000373 for i in args:
374 bp = bdb.Breakpoint.bpbynumber[int(i)]
375 if bp:
376 bp.disable()
377
378 def do_condition(self, arg):
379 # arg is breakpoint number and condition
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000380 args = arg.split(' ', 1)
381 bpnum = int(args[0].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000382 try:
383 cond = args[1]
384 except:
385 cond = None
386 bp = bdb.Breakpoint.bpbynumber[bpnum]
387 if bp:
388 bp.cond = cond
389 if not cond:
390 print 'Breakpoint', bpnum,
391 print 'is now unconditional.'
392
393 def do_ignore(self,arg):
394 """arg is bp number followed by ignore count."""
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000395 args = arg.split()
396 bpnum = int(args[0].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000397 try:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000398 count = int(args[1].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000399 except:
400 count = 0
401 bp = bdb.Breakpoint.bpbynumber[bpnum]
402 if bp:
403 bp.ignore = count
404 if (count > 0):
405 reply = 'Will ignore next '
406 if (count > 1):
407 reply = reply + '%d crossings' % count
408 else:
409 reply = reply + '1 crossing'
410 print reply + ' of breakpoint %d.' % bpnum
411 else:
412 print 'Will stop next time breakpoint',
413 print bpnum, 'is reached.'
414
415 def do_clear(self, arg):
416 """Three possibilities, tried in this order:
417 clear -> clear all breaks, ask for confirmation
418 clear file:lineno -> clear all breaks at file:lineno
419 clear bpno bpno ... -> clear breakpoints by number"""
420 if not arg:
421 try:
422 reply = raw_input('Clear all breaks? ')
423 except EOFError:
424 reply = 'no'
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000425 reply = reply.strip().lower()
Tim Peters2344fae2001-01-15 00:50:52 +0000426 if reply in ('y', 'yes'):
427 self.clear_all_breaks()
428 return
429 if ':' in arg:
430 # Make sure it works for "clear C:\foo\bar.py:12"
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000431 i = arg.rfind(':')
Tim Peters2344fae2001-01-15 00:50:52 +0000432 filename = arg[:i]
433 arg = arg[i+1:]
434 try:
435 lineno = int(arg)
436 except:
437 err = "Invalid line number (%s)" % arg
438 else:
439 err = self.clear_break(filename, lineno)
440 if err: print '***', err
441 return
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000442 numberlist = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000443 for i in numberlist:
444 err = self.clear_bpbynumber(i)
445 if err:
446 print '***', err
447 else:
448 print 'Deleted breakpoint %s ' % (i,)
449 do_cl = do_clear # 'c' is already an abbreviation for 'continue'
450
451 def do_where(self, arg):
452 self.print_stack_trace()
453 do_w = do_where
Guido van Rossum6bd68352001-01-20 17:57:37 +0000454 do_bt = do_where
Tim Peters2344fae2001-01-15 00:50:52 +0000455
456 def do_up(self, arg):
457 if self.curindex == 0:
458 print '*** Oldest frame'
459 else:
460 self.curindex = self.curindex - 1
461 self.curframe = self.stack[self.curindex][0]
462 self.print_stack_entry(self.stack[self.curindex])
463 self.lineno = None
464 do_u = do_up
465
466 def do_down(self, arg):
467 if self.curindex + 1 == len(self.stack):
468 print '*** Newest frame'
469 else:
470 self.curindex = self.curindex + 1
471 self.curframe = self.stack[self.curindex][0]
472 self.print_stack_entry(self.stack[self.curindex])
473 self.lineno = None
474 do_d = do_down
475
476 def do_step(self, arg):
477 self.set_step()
478 return 1
479 do_s = do_step
480
481 def do_next(self, arg):
482 self.set_next(self.curframe)
483 return 1
484 do_n = do_next
485
486 def do_return(self, arg):
487 self.set_return(self.curframe)
488 return 1
489 do_r = do_return
490
491 def do_continue(self, arg):
492 self.set_continue()
493 return 1
494 do_c = do_cont = do_continue
495
496 def do_quit(self, arg):
497 self.set_quit()
498 return 1
499 do_q = do_quit
Guido van Rossumd1c08f32002-04-15 00:48:24 +0000500 do_exit = do_quit
Tim Peters2344fae2001-01-15 00:50:52 +0000501
502 def do_args(self, arg):
503 f = self.curframe
504 co = f.f_code
505 dict = f.f_locals
506 n = co.co_argcount
507 if co.co_flags & 4: n = n+1
508 if co.co_flags & 8: n = n+1
509 for i in range(n):
510 name = co.co_varnames[i]
511 print name, '=',
512 if dict.has_key(name): print dict[name]
513 else: print "*** undefined ***"
514 do_a = do_args
Guido van Rossum2424f851998-09-11 22:50:09 +0000515
Tim Peters2344fae2001-01-15 00:50:52 +0000516 def do_retval(self, arg):
517 if self.curframe.f_locals.has_key('__return__'):
518 print self.curframe.f_locals['__return__']
519 else:
520 print '*** Not yet returned!'
521 do_rv = do_retval
Guido van Rossum2424f851998-09-11 22:50:09 +0000522
Tim Peters2344fae2001-01-15 00:50:52 +0000523 def do_p(self, arg):
524 try:
525 value = eval(arg, self.curframe.f_globals,
526 self.curframe.f_locals)
527 except:
528 t, v = sys.exc_info()[:2]
529 if type(t) == type(''):
530 exc_type_name = t
531 else: exc_type_name = t.__name__
532 print '***', exc_type_name + ':', `v`
533 return
Guido van Rossum2424f851998-09-11 22:50:09 +0000534
Tim Peters2344fae2001-01-15 00:50:52 +0000535 print `value`
Guido van Rossum2424f851998-09-11 22:50:09 +0000536
Tim Peters2344fae2001-01-15 00:50:52 +0000537 def do_list(self, arg):
538 self.lastcmd = 'list'
539 last = None
540 if arg:
541 try:
542 x = eval(arg, {}, {})
543 if type(x) == type(()):
544 first, last = x
545 first = int(first)
546 last = int(last)
547 if last < first:
548 # Assume it's a count
549 last = first + last
550 else:
551 first = max(1, int(x) - 5)
552 except:
553 print '*** Error in argument:', `arg`
554 return
555 elif self.lineno is None:
556 first = max(1, self.curframe.f_lineno - 5)
557 else:
558 first = self.lineno + 1
559 if last is None:
560 last = first + 10
561 filename = self.curframe.f_code.co_filename
562 breaklist = self.get_file_breaks(filename)
563 try:
564 for lineno in range(first, last+1):
565 line = linecache.getline(filename, lineno)
566 if not line:
567 print '[EOF]'
568 break
569 else:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000570 s = `lineno`.rjust(3)
Tim Peters2344fae2001-01-15 00:50:52 +0000571 if len(s) < 4: s = s + ' '
572 if lineno in breaklist: s = s + 'B'
573 else: s = s + ' '
574 if lineno == self.curframe.f_lineno:
575 s = s + '->'
576 print s + '\t' + line,
577 self.lineno = lineno
578 except KeyboardInterrupt:
579 pass
580 do_l = do_list
Guido van Rossum2424f851998-09-11 22:50:09 +0000581
Tim Peters2344fae2001-01-15 00:50:52 +0000582 def do_whatis(self, arg):
583 try:
584 value = eval(arg, self.curframe.f_globals,
585 self.curframe.f_locals)
586 except:
587 t, v = sys.exc_info()[:2]
588 if type(t) == type(''):
589 exc_type_name = t
590 else: exc_type_name = t.__name__
591 print '***', exc_type_name + ':', `v`
592 return
593 code = None
594 # Is it a function?
595 try: code = value.func_code
596 except: pass
597 if code:
598 print 'Function', code.co_name
599 return
600 # Is it an instance method?
601 try: code = value.im_func.func_code
602 except: pass
603 if code:
604 print 'Method', code.co_name
605 return
606 # None of the above...
607 print type(value)
Guido van Rossum8e2ec561993-07-29 09:37:38 +0000608
Tim Peters2344fae2001-01-15 00:50:52 +0000609 def do_alias(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000610 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000611 if len(args) == 0:
612 keys = self.aliases.keys()
613 keys.sort()
614 for alias in keys:
615 print "%s = %s" % (alias, self.aliases[alias])
616 return
617 if self.aliases.has_key(args[0]) and len (args) == 1:
618 print "%s = %s" % (args[0], self.aliases[args[0]])
619 else:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000620 self.aliases[args[0]] = ' '.join(args[1:])
Guido van Rossum23efba41992-01-27 16:58:47 +0000621
Tim Peters2344fae2001-01-15 00:50:52 +0000622 def do_unalias(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000623 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000624 if len(args) == 0: return
625 if self.aliases.has_key(args[0]):
626 del self.aliases[args[0]]
Guido van Rossum00230781993-03-29 11:39:45 +0000627
Tim Peters2344fae2001-01-15 00:50:52 +0000628 # Print a traceback starting at the top stack frame.
629 # The most recently entered frame is printed last;
630 # this is different from dbx and gdb, but consistent with
631 # the Python interpreter's stack trace.
632 # It is also consistent with the up/down commands (which are
633 # compatible with dbx and gdb: up moves towards 'main()'
634 # and down moves towards the most recent stack frame).
Guido van Rossum2424f851998-09-11 22:50:09 +0000635
Tim Peters2344fae2001-01-15 00:50:52 +0000636 def print_stack_trace(self):
637 try:
638 for frame_lineno in self.stack:
639 self.print_stack_entry(frame_lineno)
640 except KeyboardInterrupt:
641 pass
Guido van Rossum2424f851998-09-11 22:50:09 +0000642
Tim Peters2344fae2001-01-15 00:50:52 +0000643 def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix):
644 frame, lineno = frame_lineno
645 if frame is self.curframe:
646 print '>',
647 else:
648 print ' ',
649 print self.format_stack_entry(frame_lineno, prompt_prefix)
Guido van Rossum2424f851998-09-11 22:50:09 +0000650
Guido van Rossum921c8241992-01-10 14:54:42 +0000651
Tim Peters2344fae2001-01-15 00:50:52 +0000652 # Help methods (derived from pdb.doc)
Guido van Rossum921c8241992-01-10 14:54:42 +0000653
Tim Peters2344fae2001-01-15 00:50:52 +0000654 def help_help(self):
655 self.help_h()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000656
Tim Peters2344fae2001-01-15 00:50:52 +0000657 def help_h(self):
658 print """h(elp)
659Without argument, print the list of available commands.
660With a command name as argument, print help about that command
661"help pdb" pipes the full documentation file to the $PAGER
662"help exec" gives help on the ! command"""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000663
Tim Peters2344fae2001-01-15 00:50:52 +0000664 def help_where(self):
665 self.help_w()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000666
Tim Peters2344fae2001-01-15 00:50:52 +0000667 def help_w(self):
668 print """w(here)
669Print a stack trace, with the most recent frame at the bottom.
670An arrow indicates the "current frame", which determines the
Guido van Rossum6bd68352001-01-20 17:57:37 +0000671context of most commands. 'bt' is an alias for this command."""
672
673 help_bt = help_w
Guido van Rossumb6775db1994-08-01 11:34:53 +0000674
Tim Peters2344fae2001-01-15 00:50:52 +0000675 def help_down(self):
676 self.help_d()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000677
Tim Peters2344fae2001-01-15 00:50:52 +0000678 def help_d(self):
679 print """d(own)
680Move the current frame one level down in the stack trace
681(to an older frame)."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000682
Tim Peters2344fae2001-01-15 00:50:52 +0000683 def help_up(self):
684 self.help_u()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000685
Tim Peters2344fae2001-01-15 00:50:52 +0000686 def help_u(self):
687 print """u(p)
688Move the current frame one level up in the stack trace
689(to a newer frame)."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000690
Tim Peters2344fae2001-01-15 00:50:52 +0000691 def help_break(self):
692 self.help_b()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000693
Tim Peters2344fae2001-01-15 00:50:52 +0000694 def help_b(self):
695 print """b(reak) ([file:]lineno | function) [, condition]
696With a line number argument, set a break there in the current
697file. With a function name, set a break at first executable line
698of that function. Without argument, list all breaks. If a second
699argument is present, it is a string specifying an expression
700which must evaluate to true before the breakpoint is honored.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000701
Tim Peters2344fae2001-01-15 00:50:52 +0000702The line number may be prefixed with a filename and a colon,
703to specify a breakpoint in another file (probably one that
704hasn't been loaded yet). The file is searched for on sys.path;
705the .py suffix may be omitted."""
Guido van Rossumb5699c71998-07-20 23:13:54 +0000706
Tim Peters2344fae2001-01-15 00:50:52 +0000707 def help_clear(self):
708 self.help_cl()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000709
Tim Peters2344fae2001-01-15 00:50:52 +0000710 def help_cl(self):
711 print "cl(ear) filename:lineno"
712 print """cl(ear) [bpnumber [bpnumber...]]
713With a space separated list of breakpoint numbers, clear
714those breakpoints. Without argument, clear all breaks (but
715first ask confirmation). With a filename:lineno argument,
716clear all breaks at that line in that file.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000717
Tim Peters2344fae2001-01-15 00:50:52 +0000718Note that the argument is different from previous versions of
719the debugger (in python distributions 1.5.1 and before) where
720a linenumber was used instead of either filename:lineno or
721breakpoint numbers."""
Guido van Rossumb5699c71998-07-20 23:13:54 +0000722
Tim Peters2344fae2001-01-15 00:50:52 +0000723 def help_tbreak(self):
724 print """tbreak same arguments as break, but breakpoint is
725removed when first hit."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000726
Tim Peters2344fae2001-01-15 00:50:52 +0000727 def help_enable(self):
728 print """enable bpnumber [bpnumber ...]
729Enables the breakpoints given as a space separated list of
730bp numbers."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000731
Tim Peters2344fae2001-01-15 00:50:52 +0000732 def help_disable(self):
733 print """disable bpnumber [bpnumber ...]
734Disables the breakpoints given as a space separated list of
735bp numbers."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000736
Tim Peters2344fae2001-01-15 00:50:52 +0000737 def help_ignore(self):
738 print """ignore bpnumber count
739Sets the ignore count for the given breakpoint number. A breakpoint
740becomes active when the ignore count is zero. When non-zero, the
741count is decremented each time the breakpoint is reached and the
742breakpoint is not disabled and any associated condition evaluates
743to true."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000744
Tim Peters2344fae2001-01-15 00:50:52 +0000745 def help_condition(self):
746 print """condition bpnumber str_condition
747str_condition is a string specifying an expression which
748must evaluate to true before the breakpoint is honored.
749If str_condition is absent, any existing condition is removed;
750i.e., the breakpoint is made unconditional."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000751
Tim Peters2344fae2001-01-15 00:50:52 +0000752 def help_step(self):
753 self.help_s()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000754
Tim Peters2344fae2001-01-15 00:50:52 +0000755 def help_s(self):
756 print """s(tep)
757Execute the current line, stop at the first possible occasion
758(either in a function that is called or in the current function)."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000759
Tim Peters2344fae2001-01-15 00:50:52 +0000760 def help_next(self):
761 self.help_n()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000762
Tim Peters2344fae2001-01-15 00:50:52 +0000763 def help_n(self):
764 print """n(ext)
765Continue execution until the next line in the current function
766is reached or it returns."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000767
Tim Peters2344fae2001-01-15 00:50:52 +0000768 def help_return(self):
769 self.help_r()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000770
Tim Peters2344fae2001-01-15 00:50:52 +0000771 def help_r(self):
772 print """r(eturn)
773Continue execution until the current function returns."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000774
Tim Peters2344fae2001-01-15 00:50:52 +0000775 def help_continue(self):
776 self.help_c()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000777
Tim Peters2344fae2001-01-15 00:50:52 +0000778 def help_cont(self):
779 self.help_c()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000780
Tim Peters2344fae2001-01-15 00:50:52 +0000781 def help_c(self):
782 print """c(ont(inue))
783Continue execution, only stop when a breakpoint is encountered."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000784
Tim Peters2344fae2001-01-15 00:50:52 +0000785 def help_list(self):
786 self.help_l()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000787
Tim Peters2344fae2001-01-15 00:50:52 +0000788 def help_l(self):
789 print """l(ist) [first [,last]]
790List source code for the current file.
791Without arguments, list 11 lines around the current line
792or continue the previous listing.
793With one argument, list 11 lines starting at that line.
794With two arguments, list the given range;
795if the second argument is less than the first, it is a count."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000796
Tim Peters2344fae2001-01-15 00:50:52 +0000797 def help_args(self):
798 self.help_a()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000799
Tim Peters2344fae2001-01-15 00:50:52 +0000800 def help_a(self):
801 print """a(rgs)
802Print the arguments of the current function."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000803
Tim Peters2344fae2001-01-15 00:50:52 +0000804 def help_p(self):
805 print """p expression
806Print the value of the expression."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000807
Tim Peters2344fae2001-01-15 00:50:52 +0000808 def help_exec(self):
809 print """(!) statement
810Execute the (one-line) statement in the context of
811the current stack frame.
812The exclamation point can be omitted unless the first word
813of the statement resembles a debugger command.
814To assign to a global variable you must always prefix the
815command with a 'global' command, e.g.:
816(Pdb) global list_options; list_options = ['-l']
817(Pdb)"""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000818
Tim Peters2344fae2001-01-15 00:50:52 +0000819 def help_quit(self):
820 self.help_q()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000821
Tim Peters2344fae2001-01-15 00:50:52 +0000822 def help_q(self):
Guido van Rossumd1c08f32002-04-15 00:48:24 +0000823 print """q(uit) or exit - Quit from the debugger.
Tim Peters2344fae2001-01-15 00:50:52 +0000824The program being executed is aborted."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000825
Guido van Rossumd1c08f32002-04-15 00:48:24 +0000826 help_exit = help_q
827
Tim Peters2344fae2001-01-15 00:50:52 +0000828 def help_whatis(self):
829 print """whatis arg
830Prints the type of the argument."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000831
Tim Peters2344fae2001-01-15 00:50:52 +0000832 def help_EOF(self):
833 print """EOF
834Handles the receipt of EOF as a command."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000835
Tim Peters2344fae2001-01-15 00:50:52 +0000836 def help_alias(self):
837 print """alias [name [command [parameter parameter ...] ]]
838Creates an alias called 'name' the executes 'command'. The command
839must *not* be enclosed in quotes. Replaceable parameters are
840indicated by %1, %2, and so on, while %* is replaced by all the
841parameters. If no command is given, the current alias for name
842is shown. If no name is given, all aliases are listed.
Guido van Rossum2424f851998-09-11 22:50:09 +0000843
Tim Peters2344fae2001-01-15 00:50:52 +0000844Aliases may be nested and can contain anything that can be
845legally typed at the pdb prompt. Note! You *can* override
846internal pdb commands with aliases! Those internal commands
847are then hidden until the alias is removed. Aliasing is recursively
848applied to the first word of the command line; all other words
849in the line are left alone.
Guido van Rossum2424f851998-09-11 22:50:09 +0000850
Tim Peters2344fae2001-01-15 00:50:52 +0000851Some useful aliases (especially when placed in the .pdbrc file) are:
Guido van Rossum2424f851998-09-11 22:50:09 +0000852
Tim Peters2344fae2001-01-15 00:50:52 +0000853#Print instance variables (usage "pi classInst")
854alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
Guido van Rossum2424f851998-09-11 22:50:09 +0000855
Tim Peters2344fae2001-01-15 00:50:52 +0000856#Print instance variables in self
857alias ps pi self
858"""
Guido van Rossum2424f851998-09-11 22:50:09 +0000859
Tim Peters2344fae2001-01-15 00:50:52 +0000860 def help_unalias(self):
861 print """unalias name
862Deletes the specified alias."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000863
Tim Peters2344fae2001-01-15 00:50:52 +0000864 def help_pdb(self):
865 help()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000866
Tim Peters2344fae2001-01-15 00:50:52 +0000867 def lookupmodule(self, filename):
868 """Helper function for break/clear parsing -- may be overridden."""
869 root, ext = os.path.splitext(filename)
870 if ext == '':
871 filename = filename + '.py'
872 if os.path.isabs(filename):
873 return filename
874 for dirname in sys.path:
875 while os.path.islink(dirname):
876 dirname = os.readlink(dirname)
877 fullname = os.path.join(dirname, filename)
878 if os.path.exists(fullname):
879 return fullname
880 return None
Guido van Rossumb5699c71998-07-20 23:13:54 +0000881
Guido van Rossum35771131992-09-08 11:59:04 +0000882# Simplified interface
883
Guido van Rossum5e38b6f1995-02-27 13:13:40 +0000884def run(statement, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +0000885 Pdb().run(statement, globals, locals)
Guido van Rossum5e38b6f1995-02-27 13:13:40 +0000886
887def runeval(expression, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +0000888 return Pdb().runeval(expression, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000889
890def runctx(statement, globals, locals):
Tim Peters2344fae2001-01-15 00:50:52 +0000891 # B/W compatibility
892 run(statement, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000893
Guido van Rossum4e160981992-09-02 20:43:20 +0000894def runcall(*args):
Tim Peters2344fae2001-01-15 00:50:52 +0000895 return apply(Pdb().runcall, args)
Guido van Rossum4e160981992-09-02 20:43:20 +0000896
Guido van Rossumb6775db1994-08-01 11:34:53 +0000897def set_trace():
Tim Peters2344fae2001-01-15 00:50:52 +0000898 Pdb().set_trace()
Guido van Rossum35771131992-09-08 11:59:04 +0000899
900# Post-Mortem interface
901
902def post_mortem(t):
Tim Peters2344fae2001-01-15 00:50:52 +0000903 p = Pdb()
904 p.reset()
905 while t.tb_next is not None:
906 t = t.tb_next
907 p.interaction(t.tb_frame, t)
Guido van Rossum35771131992-09-08 11:59:04 +0000908
909def pm():
Tim Peters2344fae2001-01-15 00:50:52 +0000910 post_mortem(sys.last_traceback)
Guido van Rossum35771131992-09-08 11:59:04 +0000911
912
913# Main program for testing
914
Guido van Rossum23efba41992-01-27 16:58:47 +0000915TESTCMD = 'import x; x.main()'
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000916
Guido van Rossum921c8241992-01-10 14:54:42 +0000917def test():
Tim Peters2344fae2001-01-15 00:50:52 +0000918 run(TESTCMD)
Guido van Rossume61fa0a1993-10-22 13:56:35 +0000919
920# print help
921def help():
Tim Peters2344fae2001-01-15 00:50:52 +0000922 for dirname in sys.path:
923 fullname = os.path.join(dirname, 'pdb.doc')
924 if os.path.exists(fullname):
925 sts = os.system('${PAGER-more} '+fullname)
926 if sts: print '*** Pager exit status:', sts
927 break
928 else:
929 print 'Sorry, can\'t find the help file "pdb.doc"',
930 print 'along the Python search path'
Guido van Rossumf17361d1996-07-30 16:28:13 +0000931
Guido van Rossumb5699c71998-07-20 23:13:54 +0000932mainmodule = ''
933mainpyfile = ''
934
Guido van Rossumf17361d1996-07-30 16:28:13 +0000935# When invoked as main program, invoke the debugger on a script
936if __name__=='__main__':
Tim Peters2344fae2001-01-15 00:50:52 +0000937 if not sys.argv[1:]:
938 print "usage: pdb.py scriptfile [arg] ..."
939 sys.exit(2)
Guido van Rossumf17361d1996-07-30 16:28:13 +0000940
Tim Peters2344fae2001-01-15 00:50:52 +0000941 mainpyfile = filename = sys.argv[1] # Get script filename
942 if not os.path.exists(filename):
943 print 'Error:', `filename`, 'does not exist'
944 sys.exit(1)
945 mainmodule = os.path.basename(filename)
946 del sys.argv[0] # Hide "pdb.py" from argument list
Guido van Rossumec577d51996-09-10 17:39:34 +0000947
Tim Peters2344fae2001-01-15 00:50:52 +0000948 # Insert script directory in front of module search path
949 sys.path.insert(0, os.path.dirname(filename))
Guido van Rossumf17361d1996-07-30 16:28:13 +0000950
Tim Peters2344fae2001-01-15 00:50:52 +0000951 run('execfile(' + `filename` + ')')