blob: d7fe54ab72939aa11f4d10029acfc4da59186d38 [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
16def find_function(funcname, filename):
Tim Peters2344fae2001-01-15 00:50:52 +000017 cre = re.compile(r'def\s+%s\s*[(]' % funcname)
18 try:
19 fp = open(filename)
20 except IOError:
21 return None
22 # consumer of this info expects the first line to be 1
23 lineno = 1
24 answer = None
25 while 1:
26 line = fp.readline()
27 if line == '':
28 break
29 if cre.match(line):
30 answer = funcname, filename, lineno
31 break
32 lineno = lineno + 1
33 fp.close()
34 return answer
Guido van Rossum921c8241992-01-10 14:54:42 +000035
36
Guido van Rossuma558e371994-11-10 22:27:35 +000037# Interaction prompt line will separate file and call info from code
38# text using value of line_prefix string. A newline and arrow may
39# be to your liking. You can set it once pdb is imported using the
40# command "pdb.line_prefix = '\n% '".
Tim Peters2344fae2001-01-15 00:50:52 +000041# line_prefix = ': ' # Use this to get the old situation back
42line_prefix = '\n-> ' # Probably a better default
Guido van Rossuma558e371994-11-10 22:27:35 +000043
Guido van Rossum23efba41992-01-27 16:58:47 +000044class Pdb(bdb.Bdb, cmd.Cmd):
Guido van Rossum2424f851998-09-11 22:50:09 +000045
Tim Peters2344fae2001-01-15 00:50:52 +000046 def __init__(self):
47 bdb.Bdb.__init__(self)
48 cmd.Cmd.__init__(self)
49 self.prompt = '(Pdb) '
50 self.aliases = {}
51 # Try to load readline if it exists
52 try:
53 import readline
54 except ImportError:
55 pass
Guido van Rossum2424f851998-09-11 22:50:09 +000056
Tim Peters2344fae2001-01-15 00:50:52 +000057 # Read $HOME/.pdbrc and ./.pdbrc
58 self.rcLines = []
59 if os.environ.has_key('HOME'):
60 envHome = os.environ['HOME']
61 try:
62 rcFile = open(os.path.join(envHome, ".pdbrc"))
63 except IOError:
64 pass
65 else:
66 for line in rcFile.readlines():
67 self.rcLines.append(line)
68 rcFile.close()
69 try:
70 rcFile = open(".pdbrc")
71 except IOError:
72 pass
73 else:
74 for line in rcFile.readlines():
75 self.rcLines.append(line)
76 rcFile.close()
Guido van Rossum23efba41992-01-27 16:58:47 +000077
Tim Peters2344fae2001-01-15 00:50:52 +000078 def reset(self):
79 bdb.Bdb.reset(self)
80 self.forget()
Guido van Rossum23efba41992-01-27 16:58:47 +000081
Tim Peters2344fae2001-01-15 00:50:52 +000082 def forget(self):
83 self.lineno = None
84 self.stack = []
85 self.curindex = 0
86 self.curframe = None
Guido van Rossum2424f851998-09-11 22:50:09 +000087
Tim Peters2344fae2001-01-15 00:50:52 +000088 def setup(self, f, t):
89 self.forget()
90 self.stack, self.curindex = self.get_stack(f, t)
91 self.curframe = self.stack[self.curindex][0]
92 self.execRcLines()
Guido van Rossumb6775db1994-08-01 11:34:53 +000093
Tim Peters2344fae2001-01-15 00:50:52 +000094 # Can be executed earlier than 'setup' if desired
95 def execRcLines(self):
96 if self.rcLines:
97 # Make local copy because of recursion
98 rcLines = self.rcLines
99 # executed only once
100 self.rcLines = []
101 for line in rcLines:
102 line = line[:-1]
103 if len (line) > 0 and line[0] != '#':
104 self.onecmd (line)
Guido van Rossum2424f851998-09-11 22:50:09 +0000105
Tim Peters2344fae2001-01-15 00:50:52 +0000106 # Override Bdb methods (except user_call, for now)
Guido van Rossum2424f851998-09-11 22:50:09 +0000107
Tim Peters2344fae2001-01-15 00:50:52 +0000108 def user_line(self, frame):
109 """This function is called when we stop or break at this line."""
110 self.interaction(frame, None)
Guido van Rossum9e1ee971997-07-11 13:43:53 +0000111
Tim Peters2344fae2001-01-15 00:50:52 +0000112 def user_return(self, frame, return_value):
113 """This function is called when a return trap is set here."""
114 frame.f_locals['__return__'] = return_value
115 print '--Return--'
116 self.interaction(frame, None)
Guido van Rossum2424f851998-09-11 22:50:09 +0000117
Tim Peters2344fae2001-01-15 00:50:52 +0000118 def user_exception(self, frame, (exc_type, exc_value, exc_traceback)):
119 """This function is called if an exception occurs,
120 but only if we are to stop at or just below this level."""
121 frame.f_locals['__exception__'] = exc_type, exc_value
122 if type(exc_type) == type(''):
123 exc_type_name = exc_type
124 else: exc_type_name = exc_type.__name__
125 print exc_type_name + ':', repr.repr(exc_value)
126 self.interaction(frame, exc_traceback)
Guido van Rossum2424f851998-09-11 22:50:09 +0000127
Tim Peters2344fae2001-01-15 00:50:52 +0000128 # General interaction function
129
130 def interaction(self, frame, traceback):
131 self.setup(frame, traceback)
132 self.print_stack_entry(self.stack[self.curindex])
133 self.cmdloop()
134 self.forget()
135
136 def default(self, line):
137 if line[:1] == '!': line = line[1:]
138 locals = self.curframe.f_locals
139 globals = self.curframe.f_globals
140 try:
141 code = compile(line + '\n', '<stdin>', 'single')
142 exec code in globals, locals
143 except:
144 t, v = sys.exc_info()[:2]
145 if type(t) == type(''):
146 exc_type_name = t
147 else: exc_type_name = t.__name__
148 print '***', exc_type_name + ':', v
149
150 def precmd(self, line):
151 """Handle alias expansion and ';;' separator."""
152 if not line:
153 return line
154 args = string.split(line)
155 while self.aliases.has_key(args[0]):
156 line = self.aliases[args[0]]
157 ii = 1
158 for tmpArg in args[1:]:
159 line = string.replace(line, "%" + str(ii),
160 tmpArg)
161 ii = ii + 1
162 line = string.replace(line, "%*",
163 string.join(args[1:], ' '))
164 args = string.split(line)
165 # split into ';;' separated commands
166 # unless it's an alias command
167 if args[0] != 'alias':
168 marker = string.find(line, ';;')
169 if marker >= 0:
170 # queue up everything after marker
171 next = string.lstrip(line[marker+2:])
172 self.cmdqueue.append(next)
173 line = string.rstrip(line[:marker])
174 return line
175
176 # Command definitions, called by cmdloop()
177 # The argument is the remaining string on the command line
178 # Return true to exit from the command loop
179
180 do_h = cmd.Cmd.do_help
181
182 def do_EOF(self, arg):
183 return 0 # Don't die on EOF
184
185 def do_break(self, arg, temporary = 0):
186 # break [ ([filename:]lineno | function) [, "condition"] ]
187 if not arg:
188 if self.breaks: # There's at least one
189 print "Num Type Disp Enb Where"
190 for bp in bdb.Breakpoint.bpbynumber:
191 if bp:
192 bp.bpprint()
193 return
194 # parse arguments; comma has lowest precedence
195 # and cannot occur in filename
196 filename = None
197 lineno = None
198 cond = None
199 comma = string.find(arg, ',')
200 if comma > 0:
201 # parse stuff after comma: "condition"
202 cond = string.lstrip(arg[comma+1:])
203 arg = string.rstrip(arg[:comma])
204 # parse stuff before comma: [filename:]lineno | function
205 colon = string.rfind(arg, ':')
206 if colon >= 0:
207 filename = string.rstrip(arg[:colon])
208 f = self.lookupmodule(filename)
209 if not f:
210 print '*** ', `filename`,
211 print 'not found from sys.path'
212 return
213 else:
214 filename = f
215 arg = string.lstrip(arg[colon+1:])
216 try:
217 lineno = int(arg)
218 except ValueError, msg:
219 print '*** Bad lineno:', arg
220 return
221 else:
222 # no colon; can be lineno or function
223 try:
224 lineno = int(arg)
225 except ValueError:
226 try:
227 func = eval(arg,
228 self.curframe.f_globals,
229 self.curframe.f_locals)
230 except:
231 func = arg
232 try:
233 if hasattr(func, 'im_func'):
234 func = func.im_func
235 code = func.func_code
236 lineno = code.co_firstlineno
237 filename = code.co_filename
238 except:
239 # last thing to try
240 (ok, filename, ln) = self.lineinfo(arg)
241 if not ok:
242 print '*** The specified object',
243 print `arg`,
244 print 'is not a function'
245 print ('or was not found '
246 'along sys.path.')
247 return
248 lineno = int(ln)
249 if not filename:
250 filename = self.defaultFile()
251 # Check for reasonable breakpoint
252 line = self.checkline(filename, lineno)
253 if line:
254 # now set the break point
255 err = self.set_break(filename, line, temporary, cond)
256 if err: print '***', err
257 else:
258 bp = self.get_breaks(filename, line)[-1]
259 print "Breakpoint %d at %s:%d" % (bp.number,
260 bp.file,
261 bp.line)
262
263 # To be overridden in derived debuggers
264 def defaultFile(self):
265 """Produce a reasonable default."""
266 filename = self.curframe.f_code.co_filename
267 if filename == '<string>' and mainpyfile:
268 filename = mainpyfile
269 return filename
270
271 do_b = do_break
272
273 def do_tbreak(self, arg):
274 self.do_break(arg, 1)
275
276 def lineinfo(self, identifier):
277 failed = (None, None, None)
278 # Input is identifier, may be in single quotes
279 idstring = string.split(identifier, "'")
280 if len(idstring) == 1:
281 # not in single quotes
282 id = string.strip(idstring[0])
283 elif len(idstring) == 3:
284 # quoted
285 id = string.strip(idstring[1])
286 else:
287 return failed
288 if id == '': return failed
289 parts = string.split(id, '.')
290 # Protection for derived debuggers
291 if parts[0] == 'self':
292 del parts[0]
293 if len(parts) == 0:
294 return failed
295 # Best first guess at file to look at
296 fname = self.defaultFile()
297 if len(parts) == 1:
298 item = parts[0]
299 else:
300 # More than one part.
301 # First is module, second is method/class
302 f = self.lookupmodule(parts[0])
303 if f:
304 fname = f
305 item = parts[1]
306 answer = find_function(item, fname)
307 return answer or failed
308
309 def checkline(self, filename, lineno):
310 """Return line number of first line at or after input
311 argument such that if the input points to a 'def', the
312 returned line number is the first
313 non-blank/non-comment line to follow. If the input
314 points to a blank or comment line, return 0. At end
315 of file, also return 0."""
316
317 line = linecache.getline(filename, lineno)
318 if not line:
319 print 'End of file'
320 return 0
321 line = string.strip(line)
322 # Don't allow setting breakpoint at a blank line
323 if ( not line or (line[0] == '#') or
324 (line[:3] == '"""') or line[:3] == "'''" ):
325 print '*** Blank or comment'
326 return 0
327 # When a file is read in and a breakpoint is at
328 # the 'def' statement, the system stops there at
329 # code parse time. We don't want that, so all breakpoints
330 # set at 'def' statements are moved one line onward
331 if line[:3] == 'def':
332 instr = ''
333 brackets = 0
334 while 1:
335 skipone = 0
336 for c in line:
337 if instr:
338 if skipone:
339 skipone = 0
340 elif c == '\\':
341 skipone = 1
342 elif c == instr:
343 instr = ''
344 elif c == '#':
345 break
346 elif c in ('"',"'"):
347 instr = c
348 elif c in ('(','{','['):
349 brackets = brackets + 1
350 elif c in (')','}',']'):
351 brackets = brackets - 1
352 lineno = lineno+1
353 line = linecache.getline(filename, lineno)
354 if not line:
355 print 'end of file'
356 return 0
357 line = string.strip(line)
358 if not line: continue # Blank line
359 if brackets <= 0 and line[0] not in ('#','"',"'"):
360 break
361 return lineno
362
363 def do_enable(self, arg):
364 args = string.split(arg)
365 for i in args:
366 bp = bdb.Breakpoint.bpbynumber[int(i)]
367 if bp:
368 bp.enable()
369
370 def do_disable(self, arg):
371 args = string.split(arg)
372 for i in args:
373 bp = bdb.Breakpoint.bpbynumber[int(i)]
374 if bp:
375 bp.disable()
376
377 def do_condition(self, arg):
378 # arg is breakpoint number and condition
379 args = string.split(arg, ' ', 1)
380 bpnum = int(string.strip(args[0]))
381 try:
382 cond = args[1]
383 except:
384 cond = None
385 bp = bdb.Breakpoint.bpbynumber[bpnum]
386 if bp:
387 bp.cond = cond
388 if not cond:
389 print 'Breakpoint', bpnum,
390 print 'is now unconditional.'
391
392 def do_ignore(self,arg):
393 """arg is bp number followed by ignore count."""
394 args = string.split(arg)
395 bpnum = int(string.strip(args[0]))
396 try:
397 count = int(string.strip(args[1]))
398 except:
399 count = 0
400 bp = bdb.Breakpoint.bpbynumber[bpnum]
401 if bp:
402 bp.ignore = count
403 if (count > 0):
404 reply = 'Will ignore next '
405 if (count > 1):
406 reply = reply + '%d crossings' % count
407 else:
408 reply = reply + '1 crossing'
409 print reply + ' of breakpoint %d.' % bpnum
410 else:
411 print 'Will stop next time breakpoint',
412 print bpnum, 'is reached.'
413
414 def do_clear(self, arg):
415 """Three possibilities, tried in this order:
416 clear -> clear all breaks, ask for confirmation
417 clear file:lineno -> clear all breaks at file:lineno
418 clear bpno bpno ... -> clear breakpoints by number"""
419 if not arg:
420 try:
421 reply = raw_input('Clear all breaks? ')
422 except EOFError:
423 reply = 'no'
424 reply = string.lower(string.strip(reply))
425 if reply in ('y', 'yes'):
426 self.clear_all_breaks()
427 return
428 if ':' in arg:
429 # Make sure it works for "clear C:\foo\bar.py:12"
430 i = string.rfind(arg, ':')
431 filename = arg[:i]
432 arg = arg[i+1:]
433 try:
434 lineno = int(arg)
435 except:
436 err = "Invalid line number (%s)" % arg
437 else:
438 err = self.clear_break(filename, lineno)
439 if err: print '***', err
440 return
441 numberlist = string.split(arg)
442 for i in numberlist:
443 err = self.clear_bpbynumber(i)
444 if err:
445 print '***', err
446 else:
447 print 'Deleted breakpoint %s ' % (i,)
448 do_cl = do_clear # 'c' is already an abbreviation for 'continue'
449
450 def do_where(self, arg):
451 self.print_stack_trace()
452 do_w = do_where
Guido van Rossum6bd68352001-01-20 17:57:37 +0000453 do_bt = do_where
Tim Peters2344fae2001-01-15 00:50:52 +0000454
455 def do_up(self, arg):
456 if self.curindex == 0:
457 print '*** Oldest frame'
458 else:
459 self.curindex = self.curindex - 1
460 self.curframe = self.stack[self.curindex][0]
461 self.print_stack_entry(self.stack[self.curindex])
462 self.lineno = None
463 do_u = do_up
464
465 def do_down(self, arg):
466 if self.curindex + 1 == len(self.stack):
467 print '*** Newest frame'
468 else:
469 self.curindex = self.curindex + 1
470 self.curframe = self.stack[self.curindex][0]
471 self.print_stack_entry(self.stack[self.curindex])
472 self.lineno = None
473 do_d = do_down
474
475 def do_step(self, arg):
476 self.set_step()
477 return 1
478 do_s = do_step
479
480 def do_next(self, arg):
481 self.set_next(self.curframe)
482 return 1
483 do_n = do_next
484
485 def do_return(self, arg):
486 self.set_return(self.curframe)
487 return 1
488 do_r = do_return
489
490 def do_continue(self, arg):
491 self.set_continue()
492 return 1
493 do_c = do_cont = do_continue
494
495 def do_quit(self, arg):
496 self.set_quit()
497 return 1
498 do_q = do_quit
499
500 def do_args(self, arg):
501 f = self.curframe
502 co = f.f_code
503 dict = f.f_locals
504 n = co.co_argcount
505 if co.co_flags & 4: n = n+1
506 if co.co_flags & 8: n = n+1
507 for i in range(n):
508 name = co.co_varnames[i]
509 print name, '=',
510 if dict.has_key(name): print dict[name]
511 else: print "*** undefined ***"
512 do_a = do_args
Guido van Rossum2424f851998-09-11 22:50:09 +0000513
Tim Peters2344fae2001-01-15 00:50:52 +0000514 def do_retval(self, arg):
515 if self.curframe.f_locals.has_key('__return__'):
516 print self.curframe.f_locals['__return__']
517 else:
518 print '*** Not yet returned!'
519 do_rv = do_retval
Guido van Rossum2424f851998-09-11 22:50:09 +0000520
Tim Peters2344fae2001-01-15 00:50:52 +0000521 def do_p(self, arg):
522 try:
523 value = eval(arg, self.curframe.f_globals,
524 self.curframe.f_locals)
525 except:
526 t, v = sys.exc_info()[:2]
527 if type(t) == type(''):
528 exc_type_name = t
529 else: exc_type_name = t.__name__
530 print '***', exc_type_name + ':', `v`
531 return
Guido van Rossum2424f851998-09-11 22:50:09 +0000532
Tim Peters2344fae2001-01-15 00:50:52 +0000533 print `value`
Guido van Rossum2424f851998-09-11 22:50:09 +0000534
Tim Peters2344fae2001-01-15 00:50:52 +0000535 def do_list(self, arg):
536 self.lastcmd = 'list'
537 last = None
538 if arg:
539 try:
540 x = eval(arg, {}, {})
541 if type(x) == type(()):
542 first, last = x
543 first = int(first)
544 last = int(last)
545 if last < first:
546 # Assume it's a count
547 last = first + last
548 else:
549 first = max(1, int(x) - 5)
550 except:
551 print '*** Error in argument:', `arg`
552 return
553 elif self.lineno is None:
554 first = max(1, self.curframe.f_lineno - 5)
555 else:
556 first = self.lineno + 1
557 if last is None:
558 last = first + 10
559 filename = self.curframe.f_code.co_filename
560 breaklist = self.get_file_breaks(filename)
561 try:
562 for lineno in range(first, last+1):
563 line = linecache.getline(filename, lineno)
564 if not line:
565 print '[EOF]'
566 break
567 else:
568 s = string.rjust(`lineno`, 3)
569 if len(s) < 4: s = s + ' '
570 if lineno in breaklist: s = s + 'B'
571 else: s = s + ' '
572 if lineno == self.curframe.f_lineno:
573 s = s + '->'
574 print s + '\t' + line,
575 self.lineno = lineno
576 except KeyboardInterrupt:
577 pass
578 do_l = do_list
Guido van Rossum2424f851998-09-11 22:50:09 +0000579
Tim Peters2344fae2001-01-15 00:50:52 +0000580 def do_whatis(self, arg):
581 try:
582 value = eval(arg, self.curframe.f_globals,
583 self.curframe.f_locals)
584 except:
585 t, v = sys.exc_info()[:2]
586 if type(t) == type(''):
587 exc_type_name = t
588 else: exc_type_name = t.__name__
589 print '***', exc_type_name + ':', `v`
590 return
591 code = None
592 # Is it a function?
593 try: code = value.func_code
594 except: pass
595 if code:
596 print 'Function', code.co_name
597 return
598 # Is it an instance method?
599 try: code = value.im_func.func_code
600 except: pass
601 if code:
602 print 'Method', code.co_name
603 return
604 # None of the above...
605 print type(value)
Guido van Rossum8e2ec561993-07-29 09:37:38 +0000606
Tim Peters2344fae2001-01-15 00:50:52 +0000607 def do_alias(self, arg):
608 args = string.split (arg)
609 if len(args) == 0:
610 keys = self.aliases.keys()
611 keys.sort()
612 for alias in keys:
613 print "%s = %s" % (alias, self.aliases[alias])
614 return
615 if self.aliases.has_key(args[0]) and len (args) == 1:
616 print "%s = %s" % (args[0], self.aliases[args[0]])
617 else:
618 self.aliases[args[0]] = string.join(args[1:], ' ')
Guido van Rossum23efba41992-01-27 16:58:47 +0000619
Tim Peters2344fae2001-01-15 00:50:52 +0000620 def do_unalias(self, arg):
621 args = string.split (arg)
622 if len(args) == 0: return
623 if self.aliases.has_key(args[0]):
624 del self.aliases[args[0]]
Guido van Rossum00230781993-03-29 11:39:45 +0000625
Tim Peters2344fae2001-01-15 00:50:52 +0000626 # Print a traceback starting at the top stack frame.
627 # The most recently entered frame is printed last;
628 # this is different from dbx and gdb, but consistent with
629 # the Python interpreter's stack trace.
630 # It is also consistent with the up/down commands (which are
631 # compatible with dbx and gdb: up moves towards 'main()'
632 # and down moves towards the most recent stack frame).
Guido van Rossum2424f851998-09-11 22:50:09 +0000633
Tim Peters2344fae2001-01-15 00:50:52 +0000634 def print_stack_trace(self):
635 try:
636 for frame_lineno in self.stack:
637 self.print_stack_entry(frame_lineno)
638 except KeyboardInterrupt:
639 pass
Guido van Rossum2424f851998-09-11 22:50:09 +0000640
Tim Peters2344fae2001-01-15 00:50:52 +0000641 def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix):
642 frame, lineno = frame_lineno
643 if frame is self.curframe:
644 print '>',
645 else:
646 print ' ',
647 print self.format_stack_entry(frame_lineno, prompt_prefix)
Guido van Rossum2424f851998-09-11 22:50:09 +0000648
Guido van Rossum921c8241992-01-10 14:54:42 +0000649
Tim Peters2344fae2001-01-15 00:50:52 +0000650 # Help methods (derived from pdb.doc)
Guido van Rossum921c8241992-01-10 14:54:42 +0000651
Tim Peters2344fae2001-01-15 00:50:52 +0000652 def help_help(self):
653 self.help_h()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000654
Tim Peters2344fae2001-01-15 00:50:52 +0000655 def help_h(self):
656 print """h(elp)
657Without argument, print the list of available commands.
658With a command name as argument, print help about that command
659"help pdb" pipes the full documentation file to the $PAGER
660"help exec" gives help on the ! command"""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000661
Tim Peters2344fae2001-01-15 00:50:52 +0000662 def help_where(self):
663 self.help_w()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000664
Tim Peters2344fae2001-01-15 00:50:52 +0000665 def help_w(self):
666 print """w(here)
667Print a stack trace, with the most recent frame at the bottom.
668An arrow indicates the "current frame", which determines the
Guido van Rossum6bd68352001-01-20 17:57:37 +0000669context of most commands. 'bt' is an alias for this command."""
670
671 help_bt = help_w
Guido van Rossumb6775db1994-08-01 11:34:53 +0000672
Tim Peters2344fae2001-01-15 00:50:52 +0000673 def help_down(self):
674 self.help_d()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000675
Tim Peters2344fae2001-01-15 00:50:52 +0000676 def help_d(self):
677 print """d(own)
678Move the current frame one level down in the stack trace
679(to an older frame)."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000680
Tim Peters2344fae2001-01-15 00:50:52 +0000681 def help_up(self):
682 self.help_u()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000683
Tim Peters2344fae2001-01-15 00:50:52 +0000684 def help_u(self):
685 print """u(p)
686Move the current frame one level up in the stack trace
687(to a newer frame)."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000688
Tim Peters2344fae2001-01-15 00:50:52 +0000689 def help_break(self):
690 self.help_b()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000691
Tim Peters2344fae2001-01-15 00:50:52 +0000692 def help_b(self):
693 print """b(reak) ([file:]lineno | function) [, condition]
694With a line number argument, set a break there in the current
695file. With a function name, set a break at first executable line
696of that function. Without argument, list all breaks. If a second
697argument is present, it is a string specifying an expression
698which must evaluate to true before the breakpoint is honored.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000699
Tim Peters2344fae2001-01-15 00:50:52 +0000700The line number may be prefixed with a filename and a colon,
701to specify a breakpoint in another file (probably one that
702hasn't been loaded yet). The file is searched for on sys.path;
703the .py suffix may be omitted."""
Guido van Rossumb5699c71998-07-20 23:13:54 +0000704
Tim Peters2344fae2001-01-15 00:50:52 +0000705 def help_clear(self):
706 self.help_cl()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000707
Tim Peters2344fae2001-01-15 00:50:52 +0000708 def help_cl(self):
709 print "cl(ear) filename:lineno"
710 print """cl(ear) [bpnumber [bpnumber...]]
711With a space separated list of breakpoint numbers, clear
712those breakpoints. Without argument, clear all breaks (but
713first ask confirmation). With a filename:lineno argument,
714clear all breaks at that line in that file.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000715
Tim Peters2344fae2001-01-15 00:50:52 +0000716Note that the argument is different from previous versions of
717the debugger (in python distributions 1.5.1 and before) where
718a linenumber was used instead of either filename:lineno or
719breakpoint numbers."""
Guido van Rossumb5699c71998-07-20 23:13:54 +0000720
Tim Peters2344fae2001-01-15 00:50:52 +0000721 def help_tbreak(self):
722 print """tbreak same arguments as break, but breakpoint is
723removed when first hit."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000724
Tim Peters2344fae2001-01-15 00:50:52 +0000725 def help_enable(self):
726 print """enable bpnumber [bpnumber ...]
727Enables the breakpoints given as a space separated list of
728bp numbers."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000729
Tim Peters2344fae2001-01-15 00:50:52 +0000730 def help_disable(self):
731 print """disable bpnumber [bpnumber ...]
732Disables the breakpoints given as a space separated list of
733bp numbers."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000734
Tim Peters2344fae2001-01-15 00:50:52 +0000735 def help_ignore(self):
736 print """ignore bpnumber count
737Sets the ignore count for the given breakpoint number. A breakpoint
738becomes active when the ignore count is zero. When non-zero, the
739count is decremented each time the breakpoint is reached and the
740breakpoint is not disabled and any associated condition evaluates
741to true."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000742
Tim Peters2344fae2001-01-15 00:50:52 +0000743 def help_condition(self):
744 print """condition bpnumber str_condition
745str_condition is a string specifying an expression which
746must evaluate to true before the breakpoint is honored.
747If str_condition is absent, any existing condition is removed;
748i.e., the breakpoint is made unconditional."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000749
Tim Peters2344fae2001-01-15 00:50:52 +0000750 def help_step(self):
751 self.help_s()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000752
Tim Peters2344fae2001-01-15 00:50:52 +0000753 def help_s(self):
754 print """s(tep)
755Execute the current line, stop at the first possible occasion
756(either in a function that is called or in the current function)."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000757
Tim Peters2344fae2001-01-15 00:50:52 +0000758 def help_next(self):
759 self.help_n()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000760
Tim Peters2344fae2001-01-15 00:50:52 +0000761 def help_n(self):
762 print """n(ext)
763Continue execution until the next line in the current function
764is reached or it returns."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000765
Tim Peters2344fae2001-01-15 00:50:52 +0000766 def help_return(self):
767 self.help_r()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000768
Tim Peters2344fae2001-01-15 00:50:52 +0000769 def help_r(self):
770 print """r(eturn)
771Continue execution until the current function returns."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000772
Tim Peters2344fae2001-01-15 00:50:52 +0000773 def help_continue(self):
774 self.help_c()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000775
Tim Peters2344fae2001-01-15 00:50:52 +0000776 def help_cont(self):
777 self.help_c()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000778
Tim Peters2344fae2001-01-15 00:50:52 +0000779 def help_c(self):
780 print """c(ont(inue))
781Continue execution, only stop when a breakpoint is encountered."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000782
Tim Peters2344fae2001-01-15 00:50:52 +0000783 def help_list(self):
784 self.help_l()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000785
Tim Peters2344fae2001-01-15 00:50:52 +0000786 def help_l(self):
787 print """l(ist) [first [,last]]
788List source code for the current file.
789Without arguments, list 11 lines around the current line
790or continue the previous listing.
791With one argument, list 11 lines starting at that line.
792With two arguments, list the given range;
793if the second argument is less than the first, it is a count."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000794
Tim Peters2344fae2001-01-15 00:50:52 +0000795 def help_args(self):
796 self.help_a()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000797
Tim Peters2344fae2001-01-15 00:50:52 +0000798 def help_a(self):
799 print """a(rgs)
800Print the arguments of the current function."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000801
Tim Peters2344fae2001-01-15 00:50:52 +0000802 def help_p(self):
803 print """p expression
804Print the value of the expression."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000805
Tim Peters2344fae2001-01-15 00:50:52 +0000806 def help_exec(self):
807 print """(!) statement
808Execute the (one-line) statement in the context of
809the current stack frame.
810The exclamation point can be omitted unless the first word
811of the statement resembles a debugger command.
812To assign to a global variable you must always prefix the
813command with a 'global' command, e.g.:
814(Pdb) global list_options; list_options = ['-l']
815(Pdb)"""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000816
Tim Peters2344fae2001-01-15 00:50:52 +0000817 def help_quit(self):
818 self.help_q()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000819
Tim Peters2344fae2001-01-15 00:50:52 +0000820 def help_q(self):
821 print """q(uit) Quit from the debugger.
822The program being executed is aborted."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000823
Tim Peters2344fae2001-01-15 00:50:52 +0000824 def help_whatis(self):
825 print """whatis arg
826Prints the type of the argument."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000827
Tim Peters2344fae2001-01-15 00:50:52 +0000828 def help_EOF(self):
829 print """EOF
830Handles the receipt of EOF as a command."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000831
Tim Peters2344fae2001-01-15 00:50:52 +0000832 def help_alias(self):
833 print """alias [name [command [parameter parameter ...] ]]
834Creates an alias called 'name' the executes 'command'. The command
835must *not* be enclosed in quotes. Replaceable parameters are
836indicated by %1, %2, and so on, while %* is replaced by all the
837parameters. If no command is given, the current alias for name
838is shown. If no name is given, all aliases are listed.
Guido van Rossum2424f851998-09-11 22:50:09 +0000839
Tim Peters2344fae2001-01-15 00:50:52 +0000840Aliases may be nested and can contain anything that can be
841legally typed at the pdb prompt. Note! You *can* override
842internal pdb commands with aliases! Those internal commands
843are then hidden until the alias is removed. Aliasing is recursively
844applied to the first word of the command line; all other words
845in the line are left alone.
Guido van Rossum2424f851998-09-11 22:50:09 +0000846
Tim Peters2344fae2001-01-15 00:50:52 +0000847Some useful aliases (especially when placed in the .pdbrc file) are:
Guido van Rossum2424f851998-09-11 22:50:09 +0000848
Tim Peters2344fae2001-01-15 00:50:52 +0000849#Print instance variables (usage "pi classInst")
850alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
Guido van Rossum2424f851998-09-11 22:50:09 +0000851
Tim Peters2344fae2001-01-15 00:50:52 +0000852#Print instance variables in self
853alias ps pi self
854"""
Guido van Rossum2424f851998-09-11 22:50:09 +0000855
Tim Peters2344fae2001-01-15 00:50:52 +0000856 def help_unalias(self):
857 print """unalias name
858Deletes the specified alias."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000859
Tim Peters2344fae2001-01-15 00:50:52 +0000860 def help_pdb(self):
861 help()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000862
Tim Peters2344fae2001-01-15 00:50:52 +0000863 def lookupmodule(self, filename):
864 """Helper function for break/clear parsing -- may be overridden."""
865 root, ext = os.path.splitext(filename)
866 if ext == '':
867 filename = filename + '.py'
868 if os.path.isabs(filename):
869 return filename
870 for dirname in sys.path:
871 while os.path.islink(dirname):
872 dirname = os.readlink(dirname)
873 fullname = os.path.join(dirname, filename)
874 if os.path.exists(fullname):
875 return fullname
876 return None
Guido van Rossumb5699c71998-07-20 23:13:54 +0000877
Guido van Rossum35771131992-09-08 11:59:04 +0000878# Simplified interface
879
Guido van Rossum5e38b6f1995-02-27 13:13:40 +0000880def run(statement, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +0000881 Pdb().run(statement, globals, locals)
Guido van Rossum5e38b6f1995-02-27 13:13:40 +0000882
883def runeval(expression, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +0000884 return Pdb().runeval(expression, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000885
886def runctx(statement, globals, locals):
Tim Peters2344fae2001-01-15 00:50:52 +0000887 # B/W compatibility
888 run(statement, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000889
Guido van Rossum4e160981992-09-02 20:43:20 +0000890def runcall(*args):
Tim Peters2344fae2001-01-15 00:50:52 +0000891 return apply(Pdb().runcall, args)
Guido van Rossum4e160981992-09-02 20:43:20 +0000892
Guido van Rossumb6775db1994-08-01 11:34:53 +0000893def set_trace():
Tim Peters2344fae2001-01-15 00:50:52 +0000894 Pdb().set_trace()
Guido van Rossum35771131992-09-08 11:59:04 +0000895
896# Post-Mortem interface
897
898def post_mortem(t):
Tim Peters2344fae2001-01-15 00:50:52 +0000899 p = Pdb()
900 p.reset()
901 while t.tb_next is not None:
902 t = t.tb_next
903 p.interaction(t.tb_frame, t)
Guido van Rossum35771131992-09-08 11:59:04 +0000904
905def pm():
Tim Peters2344fae2001-01-15 00:50:52 +0000906 post_mortem(sys.last_traceback)
Guido van Rossum35771131992-09-08 11:59:04 +0000907
908
909# Main program for testing
910
Guido van Rossum23efba41992-01-27 16:58:47 +0000911TESTCMD = 'import x; x.main()'
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000912
Guido van Rossum921c8241992-01-10 14:54:42 +0000913def test():
Tim Peters2344fae2001-01-15 00:50:52 +0000914 run(TESTCMD)
Guido van Rossume61fa0a1993-10-22 13:56:35 +0000915
916# print help
917def help():
Tim Peters2344fae2001-01-15 00:50:52 +0000918 for dirname in sys.path:
919 fullname = os.path.join(dirname, 'pdb.doc')
920 if os.path.exists(fullname):
921 sts = os.system('${PAGER-more} '+fullname)
922 if sts: print '*** Pager exit status:', sts
923 break
924 else:
925 print 'Sorry, can\'t find the help file "pdb.doc"',
926 print 'along the Python search path'
Guido van Rossumf17361d1996-07-30 16:28:13 +0000927
Guido van Rossumb5699c71998-07-20 23:13:54 +0000928mainmodule = ''
929mainpyfile = ''
930
Guido van Rossumf17361d1996-07-30 16:28:13 +0000931# When invoked as main program, invoke the debugger on a script
932if __name__=='__main__':
Tim Peters2344fae2001-01-15 00:50:52 +0000933 if not sys.argv[1:]:
934 print "usage: pdb.py scriptfile [arg] ..."
935 sys.exit(2)
Guido van Rossumf17361d1996-07-30 16:28:13 +0000936
Tim Peters2344fae2001-01-15 00:50:52 +0000937 mainpyfile = filename = sys.argv[1] # Get script filename
938 if not os.path.exists(filename):
939 print 'Error:', `filename`, 'does not exist'
940 sys.exit(1)
941 mainmodule = os.path.basename(filename)
942 del sys.argv[0] # Hide "pdb.py" from argument list
Guido van Rossumec577d51996-09-10 17:39:34 +0000943
Tim Peters2344fae2001-01-15 00:50:52 +0000944 # Insert script directory in front of module search path
945 sys.path.insert(0, os.path.dirname(filename))
Guido van Rossumf17361d1996-07-30 16:28:13 +0000946
Tim Peters2344fae2001-01-15 00:50:52 +0000947 run('execfile(' + `filename` + ')')