blob: 6e074a981c72f1e3c2223c7ee58d19e4a94f9053 [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
7import string
8import sys
9import linecache
Guido van Rossum23efba41992-01-27 16:58:47 +000010import cmd
11import bdb
12import repr
Guido van Rossumb5699c71998-07-20 23:13:54 +000013import os
Barry Warsaw2bee8fe1999-09-09 16:32:41 +000014import re
15
Skip Montanaro352674d2001-02-07 23:14:30 +000016__all__ = ["run", "pm", "Pdb", "runeval", "runctx", "runcall", "set_trace",
17 "post_mortem", "help"]
18
Barry Warsaw2bee8fe1999-09-09 16:32:41 +000019def find_function(funcname, filename):
Tim Peters2344fae2001-01-15 00:50:52 +000020 cre = re.compile(r'def\s+%s\s*[(]' % funcname)
21 try:
22 fp = open(filename)
23 except IOError:
24 return None
25 # consumer of this info expects the first line to be 1
26 lineno = 1
27 answer = None
28 while 1:
29 line = fp.readline()
30 if line == '':
31 break
32 if cre.match(line):
33 answer = funcname, filename, lineno
34 break
35 lineno = lineno + 1
36 fp.close()
37 return answer
Guido van Rossum921c8241992-01-10 14:54:42 +000038
39
Guido van Rossuma558e371994-11-10 22:27:35 +000040# Interaction prompt line will separate file and call info from code
41# text using value of line_prefix string. A newline and arrow may
42# be to your liking. You can set it once pdb is imported using the
43# command "pdb.line_prefix = '\n% '".
Tim Peters2344fae2001-01-15 00:50:52 +000044# line_prefix = ': ' # Use this to get the old situation back
45line_prefix = '\n-> ' # Probably a better default
Guido van Rossuma558e371994-11-10 22:27:35 +000046
Guido van Rossum23efba41992-01-27 16:58:47 +000047class Pdb(bdb.Bdb, cmd.Cmd):
Guido van Rossum2424f851998-09-11 22:50:09 +000048
Tim Peters2344fae2001-01-15 00:50:52 +000049 def __init__(self):
50 bdb.Bdb.__init__(self)
51 cmd.Cmd.__init__(self)
52 self.prompt = '(Pdb) '
53 self.aliases = {}
54 # Try to load readline if it exists
55 try:
56 import readline
57 except ImportError:
58 pass
Guido van Rossum2424f851998-09-11 22:50:09 +000059
Tim Peters2344fae2001-01-15 00:50:52 +000060 # Read $HOME/.pdbrc and ./.pdbrc
61 self.rcLines = []
62 if os.environ.has_key('HOME'):
63 envHome = os.environ['HOME']
64 try:
65 rcFile = open(os.path.join(envHome, ".pdbrc"))
66 except IOError:
67 pass
68 else:
69 for line in rcFile.readlines():
70 self.rcLines.append(line)
71 rcFile.close()
72 try:
73 rcFile = open(".pdbrc")
74 except IOError:
75 pass
76 else:
77 for line in rcFile.readlines():
78 self.rcLines.append(line)
79 rcFile.close()
Guido van Rossum23efba41992-01-27 16:58:47 +000080
Tim Peters2344fae2001-01-15 00:50:52 +000081 def reset(self):
82 bdb.Bdb.reset(self)
83 self.forget()
Guido van Rossum23efba41992-01-27 16:58:47 +000084
Tim Peters2344fae2001-01-15 00:50:52 +000085 def forget(self):
86 self.lineno = None
87 self.stack = []
88 self.curindex = 0
89 self.curframe = None
Guido van Rossum2424f851998-09-11 22:50:09 +000090
Tim Peters2344fae2001-01-15 00:50:52 +000091 def setup(self, f, t):
92 self.forget()
93 self.stack, self.curindex = self.get_stack(f, t)
94 self.curframe = self.stack[self.curindex][0]
95 self.execRcLines()
Guido van Rossumb6775db1994-08-01 11:34:53 +000096
Tim Peters2344fae2001-01-15 00:50:52 +000097 # Can be executed earlier than 'setup' if desired
98 def execRcLines(self):
99 if self.rcLines:
100 # Make local copy because of recursion
101 rcLines = self.rcLines
102 # executed only once
103 self.rcLines = []
104 for line in rcLines:
105 line = line[:-1]
106 if len (line) > 0 and line[0] != '#':
107 self.onecmd (line)
Guido van Rossum2424f851998-09-11 22:50:09 +0000108
Tim Peters2344fae2001-01-15 00:50:52 +0000109 # Override Bdb methods (except user_call, for now)
Guido van Rossum2424f851998-09-11 22:50:09 +0000110
Tim Peters2344fae2001-01-15 00:50:52 +0000111 def user_line(self, frame):
112 """This function is called when we stop or break at this line."""
113 self.interaction(frame, None)
Guido van Rossum9e1ee971997-07-11 13:43:53 +0000114
Tim Peters2344fae2001-01-15 00:50:52 +0000115 def user_return(self, frame, return_value):
116 """This function is called when a return trap is set here."""
117 frame.f_locals['__return__'] = return_value
118 print '--Return--'
119 self.interaction(frame, None)
Guido van Rossum2424f851998-09-11 22:50:09 +0000120
Tim Peters2344fae2001-01-15 00:50:52 +0000121 def user_exception(self, frame, (exc_type, exc_value, exc_traceback)):
122 """This function is called if an exception occurs,
123 but only if we are to stop at or just below this level."""
124 frame.f_locals['__exception__'] = exc_type, exc_value
125 if type(exc_type) == type(''):
126 exc_type_name = exc_type
127 else: exc_type_name = exc_type.__name__
128 print exc_type_name + ':', repr.repr(exc_value)
129 self.interaction(frame, exc_traceback)
Guido van Rossum2424f851998-09-11 22:50:09 +0000130
Tim Peters2344fae2001-01-15 00:50:52 +0000131 # General interaction function
132
133 def interaction(self, frame, traceback):
134 self.setup(frame, traceback)
135 self.print_stack_entry(self.stack[self.curindex])
136 self.cmdloop()
137 self.forget()
138
139 def default(self, line):
140 if line[:1] == '!': line = line[1:]
141 locals = self.curframe.f_locals
142 globals = self.curframe.f_globals
143 try:
144 code = compile(line + '\n', '<stdin>', 'single')
145 exec code in globals, locals
146 except:
147 t, v = sys.exc_info()[:2]
148 if type(t) == type(''):
149 exc_type_name = t
150 else: exc_type_name = t.__name__
151 print '***', exc_type_name + ':', v
152
153 def precmd(self, line):
154 """Handle alias expansion and ';;' separator."""
155 if not line:
156 return line
157 args = string.split(line)
158 while self.aliases.has_key(args[0]):
159 line = self.aliases[args[0]]
160 ii = 1
161 for tmpArg in args[1:]:
162 line = string.replace(line, "%" + str(ii),
163 tmpArg)
164 ii = ii + 1
165 line = string.replace(line, "%*",
166 string.join(args[1:], ' '))
167 args = string.split(line)
168 # split into ';;' separated commands
169 # unless it's an alias command
170 if args[0] != 'alias':
171 marker = string.find(line, ';;')
172 if marker >= 0:
173 # queue up everything after marker
174 next = string.lstrip(line[marker+2:])
175 self.cmdqueue.append(next)
176 line = string.rstrip(line[:marker])
177 return line
178
179 # Command definitions, called by cmdloop()
180 # The argument is the remaining string on the command line
181 # Return true to exit from the command loop
182
183 do_h = cmd.Cmd.do_help
184
185 def do_EOF(self, arg):
186 return 0 # Don't die on EOF
187
188 def do_break(self, arg, temporary = 0):
189 # break [ ([filename:]lineno | function) [, "condition"] ]
190 if not arg:
191 if self.breaks: # There's at least one
192 print "Num Type Disp Enb Where"
193 for bp in bdb.Breakpoint.bpbynumber:
194 if bp:
195 bp.bpprint()
196 return
197 # parse arguments; comma has lowest precedence
198 # and cannot occur in filename
199 filename = None
200 lineno = None
201 cond = None
202 comma = string.find(arg, ',')
203 if comma > 0:
204 # parse stuff after comma: "condition"
205 cond = string.lstrip(arg[comma+1:])
206 arg = string.rstrip(arg[:comma])
207 # parse stuff before comma: [filename:]lineno | function
208 colon = string.rfind(arg, ':')
209 if colon >= 0:
210 filename = string.rstrip(arg[:colon])
211 f = self.lookupmodule(filename)
212 if not f:
213 print '*** ', `filename`,
214 print 'not found from sys.path'
215 return
216 else:
217 filename = f
218 arg = string.lstrip(arg[colon+1:])
219 try:
220 lineno = int(arg)
221 except ValueError, msg:
222 print '*** Bad lineno:', arg
223 return
224 else:
225 # no colon; can be lineno or function
226 try:
227 lineno = int(arg)
228 except ValueError:
229 try:
230 func = eval(arg,
231 self.curframe.f_globals,
232 self.curframe.f_locals)
233 except:
234 func = arg
235 try:
236 if hasattr(func, 'im_func'):
237 func = func.im_func
238 code = func.func_code
239 lineno = code.co_firstlineno
240 filename = code.co_filename
241 except:
242 # last thing to try
243 (ok, filename, ln) = self.lineinfo(arg)
244 if not ok:
245 print '*** The specified object',
246 print `arg`,
247 print 'is not a function'
248 print ('or was not found '
249 'along sys.path.')
250 return
251 lineno = int(ln)
252 if not filename:
253 filename = self.defaultFile()
254 # Check for reasonable breakpoint
255 line = self.checkline(filename, lineno)
256 if line:
257 # now set the break point
258 err = self.set_break(filename, line, temporary, cond)
259 if err: print '***', err
260 else:
261 bp = self.get_breaks(filename, line)[-1]
262 print "Breakpoint %d at %s:%d" % (bp.number,
263 bp.file,
264 bp.line)
265
266 # To be overridden in derived debuggers
267 def defaultFile(self):
268 """Produce a reasonable default."""
269 filename = self.curframe.f_code.co_filename
270 if filename == '<string>' and mainpyfile:
271 filename = mainpyfile
272 return filename
273
274 do_b = do_break
275
276 def do_tbreak(self, arg):
277 self.do_break(arg, 1)
278
279 def lineinfo(self, identifier):
280 failed = (None, None, None)
281 # Input is identifier, may be in single quotes
282 idstring = string.split(identifier, "'")
283 if len(idstring) == 1:
284 # not in single quotes
285 id = string.strip(idstring[0])
286 elif len(idstring) == 3:
287 # quoted
288 id = string.strip(idstring[1])
289 else:
290 return failed
291 if id == '': return failed
292 parts = string.split(id, '.')
293 # Protection for derived debuggers
294 if parts[0] == 'self':
295 del parts[0]
296 if len(parts) == 0:
297 return failed
298 # Best first guess at file to look at
299 fname = self.defaultFile()
300 if len(parts) == 1:
301 item = parts[0]
302 else:
303 # More than one part.
304 # First is module, second is method/class
305 f = self.lookupmodule(parts[0])
306 if f:
307 fname = f
308 item = parts[1]
309 answer = find_function(item, fname)
310 return answer or failed
311
312 def checkline(self, filename, lineno):
313 """Return line number of first line at or after input
314 argument such that if the input points to a 'def', the
315 returned line number is the first
316 non-blank/non-comment line to follow. If the input
317 points to a blank or comment line, return 0. At end
318 of file, also return 0."""
319
320 line = linecache.getline(filename, lineno)
321 if not line:
322 print 'End of file'
323 return 0
324 line = string.strip(line)
325 # Don't allow setting breakpoint at a blank line
326 if ( not line or (line[0] == '#') or
327 (line[:3] == '"""') or line[:3] == "'''" ):
328 print '*** Blank or comment'
329 return 0
330 # When a file is read in and a breakpoint is at
331 # the 'def' statement, the system stops there at
332 # code parse time. We don't want that, so all breakpoints
333 # set at 'def' statements are moved one line onward
334 if line[:3] == 'def':
335 instr = ''
336 brackets = 0
337 while 1:
338 skipone = 0
339 for c in line:
340 if instr:
341 if skipone:
342 skipone = 0
343 elif c == '\\':
344 skipone = 1
345 elif c == instr:
346 instr = ''
347 elif c == '#':
348 break
349 elif c in ('"',"'"):
350 instr = c
351 elif c in ('(','{','['):
352 brackets = brackets + 1
353 elif c in (')','}',']'):
354 brackets = brackets - 1
355 lineno = lineno+1
356 line = linecache.getline(filename, lineno)
357 if not line:
358 print 'end of file'
359 return 0
360 line = string.strip(line)
361 if not line: continue # Blank line
362 if brackets <= 0 and line[0] not in ('#','"',"'"):
363 break
364 return lineno
365
366 def do_enable(self, arg):
367 args = string.split(arg)
368 for i in args:
369 bp = bdb.Breakpoint.bpbynumber[int(i)]
370 if bp:
371 bp.enable()
372
373 def do_disable(self, arg):
374 args = string.split(arg)
375 for i in args:
376 bp = bdb.Breakpoint.bpbynumber[int(i)]
377 if bp:
378 bp.disable()
379
380 def do_condition(self, arg):
381 # arg is breakpoint number and condition
382 args = string.split(arg, ' ', 1)
383 bpnum = int(string.strip(args[0]))
384 try:
385 cond = args[1]
386 except:
387 cond = None
388 bp = bdb.Breakpoint.bpbynumber[bpnum]
389 if bp:
390 bp.cond = cond
391 if not cond:
392 print 'Breakpoint', bpnum,
393 print 'is now unconditional.'
394
395 def do_ignore(self,arg):
396 """arg is bp number followed by ignore count."""
397 args = string.split(arg)
398 bpnum = int(string.strip(args[0]))
399 try:
400 count = int(string.strip(args[1]))
401 except:
402 count = 0
403 bp = bdb.Breakpoint.bpbynumber[bpnum]
404 if bp:
405 bp.ignore = count
406 if (count > 0):
407 reply = 'Will ignore next '
408 if (count > 1):
409 reply = reply + '%d crossings' % count
410 else:
411 reply = reply + '1 crossing'
412 print reply + ' of breakpoint %d.' % bpnum
413 else:
414 print 'Will stop next time breakpoint',
415 print bpnum, 'is reached.'
416
417 def do_clear(self, arg):
418 """Three possibilities, tried in this order:
419 clear -> clear all breaks, ask for confirmation
420 clear file:lineno -> clear all breaks at file:lineno
421 clear bpno bpno ... -> clear breakpoints by number"""
422 if not arg:
423 try:
424 reply = raw_input('Clear all breaks? ')
425 except EOFError:
426 reply = 'no'
427 reply = string.lower(string.strip(reply))
428 if reply in ('y', 'yes'):
429 self.clear_all_breaks()
430 return
431 if ':' in arg:
432 # Make sure it works for "clear C:\foo\bar.py:12"
433 i = string.rfind(arg, ':')
434 filename = arg[:i]
435 arg = arg[i+1:]
436 try:
437 lineno = int(arg)
438 except:
439 err = "Invalid line number (%s)" % arg
440 else:
441 err = self.clear_break(filename, lineno)
442 if err: print '***', err
443 return
444 numberlist = string.split(arg)
445 for i in numberlist:
446 err = self.clear_bpbynumber(i)
447 if err:
448 print '***', err
449 else:
450 print 'Deleted breakpoint %s ' % (i,)
451 do_cl = do_clear # 'c' is already an abbreviation for 'continue'
452
453 def do_where(self, arg):
454 self.print_stack_trace()
455 do_w = do_where
Guido van Rossum6bd68352001-01-20 17:57:37 +0000456 do_bt = do_where
Tim Peters2344fae2001-01-15 00:50:52 +0000457
458 def do_up(self, arg):
459 if self.curindex == 0:
460 print '*** Oldest frame'
461 else:
462 self.curindex = self.curindex - 1
463 self.curframe = self.stack[self.curindex][0]
464 self.print_stack_entry(self.stack[self.curindex])
465 self.lineno = None
466 do_u = do_up
467
468 def do_down(self, arg):
469 if self.curindex + 1 == len(self.stack):
470 print '*** Newest frame'
471 else:
472 self.curindex = self.curindex + 1
473 self.curframe = self.stack[self.curindex][0]
474 self.print_stack_entry(self.stack[self.curindex])
475 self.lineno = None
476 do_d = do_down
477
478 def do_step(self, arg):
479 self.set_step()
480 return 1
481 do_s = do_step
482
483 def do_next(self, arg):
484 self.set_next(self.curframe)
485 return 1
486 do_n = do_next
487
488 def do_return(self, arg):
489 self.set_return(self.curframe)
490 return 1
491 do_r = do_return
492
493 def do_continue(self, arg):
494 self.set_continue()
495 return 1
496 do_c = do_cont = do_continue
497
498 def do_quit(self, arg):
499 self.set_quit()
500 return 1
501 do_q = do_quit
502
503 def do_args(self, arg):
504 f = self.curframe
505 co = f.f_code
506 dict = f.f_locals
507 n = co.co_argcount
508 if co.co_flags & 4: n = n+1
509 if co.co_flags & 8: n = n+1
510 for i in range(n):
511 name = co.co_varnames[i]
512 print name, '=',
513 if dict.has_key(name): print dict[name]
514 else: print "*** undefined ***"
515 do_a = do_args
Guido van Rossum2424f851998-09-11 22:50:09 +0000516
Tim Peters2344fae2001-01-15 00:50:52 +0000517 def do_retval(self, arg):
518 if self.curframe.f_locals.has_key('__return__'):
519 print self.curframe.f_locals['__return__']
520 else:
521 print '*** Not yet returned!'
522 do_rv = do_retval
Guido van Rossum2424f851998-09-11 22:50:09 +0000523
Tim Peters2344fae2001-01-15 00:50:52 +0000524 def do_p(self, arg):
525 try:
526 value = eval(arg, self.curframe.f_globals,
527 self.curframe.f_locals)
528 except:
529 t, v = sys.exc_info()[:2]
530 if type(t) == type(''):
531 exc_type_name = t
532 else: exc_type_name = t.__name__
533 print '***', exc_type_name + ':', `v`
534 return
Guido van Rossum2424f851998-09-11 22:50:09 +0000535
Tim Peters2344fae2001-01-15 00:50:52 +0000536 print `value`
Guido van Rossum2424f851998-09-11 22:50:09 +0000537
Tim Peters2344fae2001-01-15 00:50:52 +0000538 def do_list(self, arg):
539 self.lastcmd = 'list'
540 last = None
541 if arg:
542 try:
543 x = eval(arg, {}, {})
544 if type(x) == type(()):
545 first, last = x
546 first = int(first)
547 last = int(last)
548 if last < first:
549 # Assume it's a count
550 last = first + last
551 else:
552 first = max(1, int(x) - 5)
553 except:
554 print '*** Error in argument:', `arg`
555 return
556 elif self.lineno is None:
557 first = max(1, self.curframe.f_lineno - 5)
558 else:
559 first = self.lineno + 1
560 if last is None:
561 last = first + 10
562 filename = self.curframe.f_code.co_filename
563 breaklist = self.get_file_breaks(filename)
564 try:
565 for lineno in range(first, last+1):
566 line = linecache.getline(filename, lineno)
567 if not line:
568 print '[EOF]'
569 break
570 else:
571 s = string.rjust(`lineno`, 3)
572 if len(s) < 4: s = s + ' '
573 if lineno in breaklist: s = s + 'B'
574 else: s = s + ' '
575 if lineno == self.curframe.f_lineno:
576 s = s + '->'
577 print s + '\t' + line,
578 self.lineno = lineno
579 except KeyboardInterrupt:
580 pass
581 do_l = do_list
Guido van Rossum2424f851998-09-11 22:50:09 +0000582
Tim Peters2344fae2001-01-15 00:50:52 +0000583 def do_whatis(self, arg):
584 try:
585 value = eval(arg, self.curframe.f_globals,
586 self.curframe.f_locals)
587 except:
588 t, v = sys.exc_info()[:2]
589 if type(t) == type(''):
590 exc_type_name = t
591 else: exc_type_name = t.__name__
592 print '***', exc_type_name + ':', `v`
593 return
594 code = None
595 # Is it a function?
596 try: code = value.func_code
597 except: pass
598 if code:
599 print 'Function', code.co_name
600 return
601 # Is it an instance method?
602 try: code = value.im_func.func_code
603 except: pass
604 if code:
605 print 'Method', code.co_name
606 return
607 # None of the above...
608 print type(value)
Guido van Rossum8e2ec561993-07-29 09:37:38 +0000609
Tim Peters2344fae2001-01-15 00:50:52 +0000610 def do_alias(self, arg):
611 args = string.split (arg)
612 if len(args) == 0:
613 keys = self.aliases.keys()
614 keys.sort()
615 for alias in keys:
616 print "%s = %s" % (alias, self.aliases[alias])
617 return
618 if self.aliases.has_key(args[0]) and len (args) == 1:
619 print "%s = %s" % (args[0], self.aliases[args[0]])
620 else:
621 self.aliases[args[0]] = string.join(args[1:], ' ')
Guido van Rossum23efba41992-01-27 16:58:47 +0000622
Tim Peters2344fae2001-01-15 00:50:52 +0000623 def do_unalias(self, arg):
624 args = string.split (arg)
625 if len(args) == 0: return
626 if self.aliases.has_key(args[0]):
627 del self.aliases[args[0]]
Guido van Rossum00230781993-03-29 11:39:45 +0000628
Tim Peters2344fae2001-01-15 00:50:52 +0000629 # Print a traceback starting at the top stack frame.
630 # The most recently entered frame is printed last;
631 # this is different from dbx and gdb, but consistent with
632 # the Python interpreter's stack trace.
633 # It is also consistent with the up/down commands (which are
634 # compatible with dbx and gdb: up moves towards 'main()'
635 # and down moves towards the most recent stack frame).
Guido van Rossum2424f851998-09-11 22:50:09 +0000636
Tim Peters2344fae2001-01-15 00:50:52 +0000637 def print_stack_trace(self):
638 try:
639 for frame_lineno in self.stack:
640 self.print_stack_entry(frame_lineno)
641 except KeyboardInterrupt:
642 pass
Guido van Rossum2424f851998-09-11 22:50:09 +0000643
Tim Peters2344fae2001-01-15 00:50:52 +0000644 def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix):
645 frame, lineno = frame_lineno
646 if frame is self.curframe:
647 print '>',
648 else:
649 print ' ',
650 print self.format_stack_entry(frame_lineno, prompt_prefix)
Guido van Rossum2424f851998-09-11 22:50:09 +0000651
Guido van Rossum921c8241992-01-10 14:54:42 +0000652
Tim Peters2344fae2001-01-15 00:50:52 +0000653 # Help methods (derived from pdb.doc)
Guido van Rossum921c8241992-01-10 14:54:42 +0000654
Tim Peters2344fae2001-01-15 00:50:52 +0000655 def help_help(self):
656 self.help_h()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000657
Tim Peters2344fae2001-01-15 00:50:52 +0000658 def help_h(self):
659 print """h(elp)
660Without argument, print the list of available commands.
661With a command name as argument, print help about that command
662"help pdb" pipes the full documentation file to the $PAGER
663"help exec" gives help on the ! command"""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000664
Tim Peters2344fae2001-01-15 00:50:52 +0000665 def help_where(self):
666 self.help_w()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000667
Tim Peters2344fae2001-01-15 00:50:52 +0000668 def help_w(self):
669 print """w(here)
670Print a stack trace, with the most recent frame at the bottom.
671An arrow indicates the "current frame", which determines the
Guido van Rossum6bd68352001-01-20 17:57:37 +0000672context of most commands. 'bt' is an alias for this command."""
673
674 help_bt = help_w
Guido van Rossumb6775db1994-08-01 11:34:53 +0000675
Tim Peters2344fae2001-01-15 00:50:52 +0000676 def help_down(self):
677 self.help_d()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000678
Tim Peters2344fae2001-01-15 00:50:52 +0000679 def help_d(self):
680 print """d(own)
681Move the current frame one level down in the stack trace
682(to an older frame)."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000683
Tim Peters2344fae2001-01-15 00:50:52 +0000684 def help_up(self):
685 self.help_u()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000686
Tim Peters2344fae2001-01-15 00:50:52 +0000687 def help_u(self):
688 print """u(p)
689Move the current frame one level up in the stack trace
690(to a newer frame)."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000691
Tim Peters2344fae2001-01-15 00:50:52 +0000692 def help_break(self):
693 self.help_b()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000694
Tim Peters2344fae2001-01-15 00:50:52 +0000695 def help_b(self):
696 print """b(reak) ([file:]lineno | function) [, condition]
697With a line number argument, set a break there in the current
698file. With a function name, set a break at first executable line
699of that function. Without argument, list all breaks. If a second
700argument is present, it is a string specifying an expression
701which must evaluate to true before the breakpoint is honored.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000702
Tim Peters2344fae2001-01-15 00:50:52 +0000703The line number may be prefixed with a filename and a colon,
704to specify a breakpoint in another file (probably one that
705hasn't been loaded yet). The file is searched for on sys.path;
706the .py suffix may be omitted."""
Guido van Rossumb5699c71998-07-20 23:13:54 +0000707
Tim Peters2344fae2001-01-15 00:50:52 +0000708 def help_clear(self):
709 self.help_cl()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000710
Tim Peters2344fae2001-01-15 00:50:52 +0000711 def help_cl(self):
712 print "cl(ear) filename:lineno"
713 print """cl(ear) [bpnumber [bpnumber...]]
714With a space separated list of breakpoint numbers, clear
715those breakpoints. Without argument, clear all breaks (but
716first ask confirmation). With a filename:lineno argument,
717clear all breaks at that line in that file.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000718
Tim Peters2344fae2001-01-15 00:50:52 +0000719Note that the argument is different from previous versions of
720the debugger (in python distributions 1.5.1 and before) where
721a linenumber was used instead of either filename:lineno or
722breakpoint numbers."""
Guido van Rossumb5699c71998-07-20 23:13:54 +0000723
Tim Peters2344fae2001-01-15 00:50:52 +0000724 def help_tbreak(self):
725 print """tbreak same arguments as break, but breakpoint is
726removed when first hit."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000727
Tim Peters2344fae2001-01-15 00:50:52 +0000728 def help_enable(self):
729 print """enable bpnumber [bpnumber ...]
730Enables the breakpoints given as a space separated list of
731bp numbers."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000732
Tim Peters2344fae2001-01-15 00:50:52 +0000733 def help_disable(self):
734 print """disable bpnumber [bpnumber ...]
735Disables 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_ignore(self):
739 print """ignore bpnumber count
740Sets the ignore count for the given breakpoint number. A breakpoint
741becomes active when the ignore count is zero. When non-zero, the
742count is decremented each time the breakpoint is reached and the
743breakpoint is not disabled and any associated condition evaluates
744to true."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000745
Tim Peters2344fae2001-01-15 00:50:52 +0000746 def help_condition(self):
747 print """condition bpnumber str_condition
748str_condition is a string specifying an expression which
749must evaluate to true before the breakpoint is honored.
750If str_condition is absent, any existing condition is removed;
751i.e., the breakpoint is made unconditional."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000752
Tim Peters2344fae2001-01-15 00:50:52 +0000753 def help_step(self):
754 self.help_s()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000755
Tim Peters2344fae2001-01-15 00:50:52 +0000756 def help_s(self):
757 print """s(tep)
758Execute the current line, stop at the first possible occasion
759(either in a function that is called or in the current function)."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000760
Tim Peters2344fae2001-01-15 00:50:52 +0000761 def help_next(self):
762 self.help_n()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000763
Tim Peters2344fae2001-01-15 00:50:52 +0000764 def help_n(self):
765 print """n(ext)
766Continue execution until the next line in the current function
767is reached or it returns."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000768
Tim Peters2344fae2001-01-15 00:50:52 +0000769 def help_return(self):
770 self.help_r()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000771
Tim Peters2344fae2001-01-15 00:50:52 +0000772 def help_r(self):
773 print """r(eturn)
774Continue execution until the current function returns."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000775
Tim Peters2344fae2001-01-15 00:50:52 +0000776 def help_continue(self):
777 self.help_c()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000778
Tim Peters2344fae2001-01-15 00:50:52 +0000779 def help_cont(self):
780 self.help_c()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000781
Tim Peters2344fae2001-01-15 00:50:52 +0000782 def help_c(self):
783 print """c(ont(inue))
784Continue execution, only stop when a breakpoint is encountered."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000785
Tim Peters2344fae2001-01-15 00:50:52 +0000786 def help_list(self):
787 self.help_l()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000788
Tim Peters2344fae2001-01-15 00:50:52 +0000789 def help_l(self):
790 print """l(ist) [first [,last]]
791List source code for the current file.
792Without arguments, list 11 lines around the current line
793or continue the previous listing.
794With one argument, list 11 lines starting at that line.
795With two arguments, list the given range;
796if the second argument is less than the first, it is a count."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000797
Tim Peters2344fae2001-01-15 00:50:52 +0000798 def help_args(self):
799 self.help_a()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000800
Tim Peters2344fae2001-01-15 00:50:52 +0000801 def help_a(self):
802 print """a(rgs)
803Print the arguments of the current function."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000804
Tim Peters2344fae2001-01-15 00:50:52 +0000805 def help_p(self):
806 print """p expression
807Print the value of the expression."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000808
Tim Peters2344fae2001-01-15 00:50:52 +0000809 def help_exec(self):
810 print """(!) statement
811Execute the (one-line) statement in the context of
812the current stack frame.
813The exclamation point can be omitted unless the first word
814of the statement resembles a debugger command.
815To assign to a global variable you must always prefix the
816command with a 'global' command, e.g.:
817(Pdb) global list_options; list_options = ['-l']
818(Pdb)"""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000819
Tim Peters2344fae2001-01-15 00:50:52 +0000820 def help_quit(self):
821 self.help_q()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000822
Tim Peters2344fae2001-01-15 00:50:52 +0000823 def help_q(self):
824 print """q(uit) Quit from the debugger.
825The program being executed is aborted."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000826
Tim Peters2344fae2001-01-15 00:50:52 +0000827 def help_whatis(self):
828 print """whatis arg
829Prints the type of the argument."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000830
Tim Peters2344fae2001-01-15 00:50:52 +0000831 def help_EOF(self):
832 print """EOF
833Handles the receipt of EOF as a command."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000834
Tim Peters2344fae2001-01-15 00:50:52 +0000835 def help_alias(self):
836 print """alias [name [command [parameter parameter ...] ]]
837Creates an alias called 'name' the executes 'command'. The command
838must *not* be enclosed in quotes. Replaceable parameters are
839indicated by %1, %2, and so on, while %* is replaced by all the
840parameters. If no command is given, the current alias for name
841is shown. If no name is given, all aliases are listed.
Guido van Rossum2424f851998-09-11 22:50:09 +0000842
Tim Peters2344fae2001-01-15 00:50:52 +0000843Aliases may be nested and can contain anything that can be
844legally typed at the pdb prompt. Note! You *can* override
845internal pdb commands with aliases! Those internal commands
846are then hidden until the alias is removed. Aliasing is recursively
847applied to the first word of the command line; all other words
848in the line are left alone.
Guido van Rossum2424f851998-09-11 22:50:09 +0000849
Tim Peters2344fae2001-01-15 00:50:52 +0000850Some useful aliases (especially when placed in the .pdbrc file) are:
Guido van Rossum2424f851998-09-11 22:50:09 +0000851
Tim Peters2344fae2001-01-15 00:50:52 +0000852#Print instance variables (usage "pi classInst")
853alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
Guido van Rossum2424f851998-09-11 22:50:09 +0000854
Tim Peters2344fae2001-01-15 00:50:52 +0000855#Print instance variables in self
856alias ps pi self
857"""
Guido van Rossum2424f851998-09-11 22:50:09 +0000858
Tim Peters2344fae2001-01-15 00:50:52 +0000859 def help_unalias(self):
860 print """unalias name
861Deletes the specified alias."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000862
Tim Peters2344fae2001-01-15 00:50:52 +0000863 def help_pdb(self):
864 help()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000865
Tim Peters2344fae2001-01-15 00:50:52 +0000866 def lookupmodule(self, filename):
867 """Helper function for break/clear parsing -- may be overridden."""
868 root, ext = os.path.splitext(filename)
869 if ext == '':
870 filename = filename + '.py'
871 if os.path.isabs(filename):
872 return filename
873 for dirname in sys.path:
874 while os.path.islink(dirname):
875 dirname = os.readlink(dirname)
876 fullname = os.path.join(dirname, filename)
877 if os.path.exists(fullname):
878 return fullname
879 return None
Guido van Rossumb5699c71998-07-20 23:13:54 +0000880
Guido van Rossum35771131992-09-08 11:59:04 +0000881# Simplified interface
882
Guido van Rossum5e38b6f1995-02-27 13:13:40 +0000883def run(statement, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +0000884 Pdb().run(statement, globals, locals)
Guido van Rossum5e38b6f1995-02-27 13:13:40 +0000885
886def runeval(expression, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +0000887 return Pdb().runeval(expression, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000888
889def runctx(statement, globals, locals):
Tim Peters2344fae2001-01-15 00:50:52 +0000890 # B/W compatibility
891 run(statement, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000892
Guido van Rossum4e160981992-09-02 20:43:20 +0000893def runcall(*args):
Tim Peters2344fae2001-01-15 00:50:52 +0000894 return apply(Pdb().runcall, args)
Guido van Rossum4e160981992-09-02 20:43:20 +0000895
Guido van Rossumb6775db1994-08-01 11:34:53 +0000896def set_trace():
Tim Peters2344fae2001-01-15 00:50:52 +0000897 Pdb().set_trace()
Guido van Rossum35771131992-09-08 11:59:04 +0000898
899# Post-Mortem interface
900
901def post_mortem(t):
Tim Peters2344fae2001-01-15 00:50:52 +0000902 p = Pdb()
903 p.reset()
904 while t.tb_next is not None:
905 t = t.tb_next
906 p.interaction(t.tb_frame, t)
Guido van Rossum35771131992-09-08 11:59:04 +0000907
908def pm():
Tim Peters2344fae2001-01-15 00:50:52 +0000909 post_mortem(sys.last_traceback)
Guido van Rossum35771131992-09-08 11:59:04 +0000910
911
912# Main program for testing
913
Guido van Rossum23efba41992-01-27 16:58:47 +0000914TESTCMD = 'import x; x.main()'
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000915
Guido van Rossum921c8241992-01-10 14:54:42 +0000916def test():
Tim Peters2344fae2001-01-15 00:50:52 +0000917 run(TESTCMD)
Guido van Rossume61fa0a1993-10-22 13:56:35 +0000918
919# print help
920def help():
Tim Peters2344fae2001-01-15 00:50:52 +0000921 for dirname in sys.path:
922 fullname = os.path.join(dirname, 'pdb.doc')
923 if os.path.exists(fullname):
924 sts = os.system('${PAGER-more} '+fullname)
925 if sts: print '*** Pager exit status:', sts
926 break
927 else:
928 print 'Sorry, can\'t find the help file "pdb.doc"',
929 print 'along the Python search path'
Guido van Rossumf17361d1996-07-30 16:28:13 +0000930
Guido van Rossumb5699c71998-07-20 23:13:54 +0000931mainmodule = ''
932mainpyfile = ''
933
Guido van Rossumf17361d1996-07-30 16:28:13 +0000934# When invoked as main program, invoke the debugger on a script
935if __name__=='__main__':
Tim Peters2344fae2001-01-15 00:50:52 +0000936 if not sys.argv[1:]:
937 print "usage: pdb.py scriptfile [arg] ..."
938 sys.exit(2)
Guido van Rossumf17361d1996-07-30 16:28:13 +0000939
Tim Peters2344fae2001-01-15 00:50:52 +0000940 mainpyfile = filename = sys.argv[1] # Get script filename
941 if not os.path.exists(filename):
942 print 'Error:', `filename`, 'does not exist'
943 sys.exit(1)
944 mainmodule = os.path.basename(filename)
945 del sys.argv[0] # Hide "pdb.py" from argument list
Guido van Rossumec577d51996-09-10 17:39:34 +0000946
Tim Peters2344fae2001-01-15 00:50:52 +0000947 # Insert script directory in front of module search path
948 sys.path.insert(0, os.path.dirname(filename))
Guido van Rossumf17361d1996-07-30 16:28:13 +0000949
Tim Peters2344fae2001-01-15 00:50:52 +0000950 run('execfile(' + `filename` + ')')