Update version number and release date.
[python/dscho.git] / Lib / pdb.py
blobc4d789eb2d784bf289ce36df44ed0ab15da84af7
1 #! /usr/bin/env python
3 """A Python debugger."""
5 # (See pdb.doc for documentation.)
7 import sys
8 import linecache
9 import cmd
10 import bdb
11 from repr import Repr
12 import os
13 import re
14 import pprint
16 # Create a custom safe Repr instance and increase its maxstring.
17 # The default of 30 truncates error messages too easily.
18 _repr = Repr()
19 _repr.maxstring = 200
20 _saferepr = _repr.repr
22 __all__ = ["run", "pm", "Pdb", "runeval", "runctx", "runcall", "set_trace",
23 "post_mortem", "help"]
25 def find_function(funcname, filename):
26 cre = re.compile(r'def\s+%s\s*[(]' % funcname)
27 try:
28 fp = open(filename)
29 except IOError:
30 return None
31 # consumer of this info expects the first line to be 1
32 lineno = 1
33 answer = None
34 while 1:
35 line = fp.readline()
36 if line == '':
37 break
38 if cre.match(line):
39 answer = funcname, filename, lineno
40 break
41 lineno = lineno + 1
42 fp.close()
43 return answer
46 # Interaction prompt line will separate file and call info from code
47 # text using value of line_prefix string. A newline and arrow may
48 # be to your liking. You can set it once pdb is imported using the
49 # command "pdb.line_prefix = '\n% '".
50 # line_prefix = ': ' # Use this to get the old situation back
51 line_prefix = '\n-> ' # Probably a better default
53 class Pdb(bdb.Bdb, cmd.Cmd):
55 def __init__(self):
56 bdb.Bdb.__init__(self)
57 cmd.Cmd.__init__(self)
58 self.prompt = '(Pdb) '
59 self.aliases = {}
60 # Try to load readline if it exists
61 try:
62 import readline
63 except ImportError:
64 pass
66 # Read $HOME/.pdbrc and ./.pdbrc
67 self.rcLines = []
68 if 'HOME' in os.environ:
69 envHome = os.environ['HOME']
70 try:
71 rcFile = open(os.path.join(envHome, ".pdbrc"))
72 except IOError:
73 pass
74 else:
75 for line in rcFile.readlines():
76 self.rcLines.append(line)
77 rcFile.close()
78 try:
79 rcFile = open(".pdbrc")
80 except IOError:
81 pass
82 else:
83 for line in rcFile.readlines():
84 self.rcLines.append(line)
85 rcFile.close()
87 def reset(self):
88 bdb.Bdb.reset(self)
89 self.forget()
91 def forget(self):
92 self.lineno = None
93 self.stack = []
94 self.curindex = 0
95 self.curframe = None
97 def setup(self, f, t):
98 self.forget()
99 self.stack, self.curindex = self.get_stack(f, t)
100 self.curframe = self.stack[self.curindex][0]
101 self.execRcLines()
103 # Can be executed earlier than 'setup' if desired
104 def execRcLines(self):
105 if self.rcLines:
106 # Make local copy because of recursion
107 rcLines = self.rcLines
108 # executed only once
109 self.rcLines = []
110 for line in rcLines:
111 line = line[:-1]
112 if len(line) > 0 and line[0] != '#':
113 self.onecmd(line)
115 # Override Bdb methods
117 def user_call(self, frame, argument_list):
118 """This method is called when there is the remote possibility
119 that we ever need to stop in this function."""
120 if self.stop_here(frame):
121 print '--Call--'
122 self.interaction(frame, None)
124 def user_line(self, frame):
125 """This function is called when we stop or break at this line."""
126 self.interaction(frame, None)
128 def user_return(self, frame, return_value):
129 """This function is called when a return trap is set here."""
130 frame.f_locals['__return__'] = return_value
131 print '--Return--'
132 self.interaction(frame, None)
134 def user_exception(self, frame, (exc_type, exc_value, exc_traceback)):
135 """This function is called if an exception occurs,
136 but only if we are to stop at or just below this level."""
137 frame.f_locals['__exception__'] = exc_type, exc_value
138 if type(exc_type) == type(''):
139 exc_type_name = exc_type
140 else: exc_type_name = exc_type.__name__
141 print exc_type_name + ':', _saferepr(exc_value)
142 self.interaction(frame, exc_traceback)
144 # General interaction function
146 def interaction(self, frame, traceback):
147 self.setup(frame, traceback)
148 self.print_stack_entry(self.stack[self.curindex])
149 self.cmdloop()
150 self.forget()
152 def default(self, line):
153 if line[:1] == '!': line = line[1:]
154 locals = self.curframe.f_locals
155 globals = self.curframe.f_globals
156 try:
157 code = compile(line + '\n', '<stdin>', 'single')
158 exec code in globals, locals
159 except:
160 t, v = sys.exc_info()[:2]
161 if type(t) == type(''):
162 exc_type_name = t
163 else: exc_type_name = t.__name__
164 print '***', exc_type_name + ':', v
166 def precmd(self, line):
167 """Handle alias expansion and ';;' separator."""
168 if not line.strip():
169 return line
170 args = line.split()
171 while args[0] in self.aliases:
172 line = self.aliases[args[0]]
173 ii = 1
174 for tmpArg in args[1:]:
175 line = line.replace("%" + str(ii),
176 tmpArg)
177 ii = ii + 1
178 line = line.replace("%*", ' '.join(args[1:]))
179 args = line.split()
180 # split into ';;' separated commands
181 # unless it's an alias command
182 if args[0] != 'alias':
183 marker = line.find(';;')
184 if marker >= 0:
185 # queue up everything after marker
186 next = line[marker+2:].lstrip()
187 self.cmdqueue.append(next)
188 line = line[:marker].rstrip()
189 return line
191 # Command definitions, called by cmdloop()
192 # The argument is the remaining string on the command line
193 # Return true to exit from the command loop
195 do_h = cmd.Cmd.do_help
197 def do_break(self, arg, temporary = 0):
198 # break [ ([filename:]lineno | function) [, "condition"] ]
199 if not arg:
200 if self.breaks: # There's at least one
201 print "Num Type Disp Enb Where"
202 for bp in bdb.Breakpoint.bpbynumber:
203 if bp:
204 bp.bpprint()
205 return
206 # parse arguments; comma has lowest precedence
207 # and cannot occur in filename
208 filename = None
209 lineno = None
210 cond = None
211 comma = arg.find(',')
212 if comma > 0:
213 # parse stuff after comma: "condition"
214 cond = arg[comma+1:].lstrip()
215 arg = arg[:comma].rstrip()
216 # parse stuff before comma: [filename:]lineno | function
217 colon = arg.rfind(':')
218 if colon >= 0:
219 filename = arg[:colon].rstrip()
220 f = self.lookupmodule(filename)
221 if not f:
222 print '*** ', `filename`,
223 print 'not found from sys.path'
224 return
225 else:
226 filename = f
227 arg = arg[colon+1:].lstrip()
228 try:
229 lineno = int(arg)
230 except ValueError, msg:
231 print '*** Bad lineno:', arg
232 return
233 else:
234 # no colon; can be lineno or function
235 try:
236 lineno = int(arg)
237 except ValueError:
238 try:
239 func = eval(arg,
240 self.curframe.f_globals,
241 self.curframe.f_locals)
242 except:
243 func = arg
244 try:
245 if hasattr(func, 'im_func'):
246 func = func.im_func
247 code = func.func_code
248 lineno = code.co_firstlineno
249 filename = code.co_filename
250 except:
251 # last thing to try
252 (ok, filename, ln) = self.lineinfo(arg)
253 if not ok:
254 print '*** The specified object',
255 print `arg`,
256 print 'is not a function'
257 print ('or was not found '
258 'along sys.path.')
259 return
260 lineno = int(ln)
261 if not filename:
262 filename = self.defaultFile()
263 # Check for reasonable breakpoint
264 line = self.checkline(filename, lineno)
265 if line:
266 # now set the break point
267 err = self.set_break(filename, line, temporary, cond)
268 if err: print '***', err
269 else:
270 bp = self.get_breaks(filename, line)[-1]
271 print "Breakpoint %d at %s:%d" % (bp.number,
272 bp.file,
273 bp.line)
275 # To be overridden in derived debuggers
276 def defaultFile(self):
277 """Produce a reasonable default."""
278 filename = self.curframe.f_code.co_filename
279 if filename == '<string>' and mainpyfile:
280 filename = mainpyfile
281 return filename
283 do_b = do_break
285 def do_tbreak(self, arg):
286 self.do_break(arg, 1)
288 def lineinfo(self, identifier):
289 failed = (None, None, None)
290 # Input is identifier, may be in single quotes
291 idstring = identifier.split("'")
292 if len(idstring) == 1:
293 # not in single quotes
294 id = idstring[0].strip()
295 elif len(idstring) == 3:
296 # quoted
297 id = idstring[1].strip()
298 else:
299 return failed
300 if id == '': return failed
301 parts = id.split('.')
302 # Protection for derived debuggers
303 if parts[0] == 'self':
304 del parts[0]
305 if len(parts) == 0:
306 return failed
307 # Best first guess at file to look at
308 fname = self.defaultFile()
309 if len(parts) == 1:
310 item = parts[0]
311 else:
312 # More than one part.
313 # First is module, second is method/class
314 f = self.lookupmodule(parts[0])
315 if f:
316 fname = f
317 item = parts[1]
318 answer = find_function(item, fname)
319 return answer or failed
321 def checkline(self, filename, lineno):
322 """Return line number of first line at or after input
323 argument such that if the input points to a 'def', the
324 returned line number is the first
325 non-blank/non-comment line to follow. If the input
326 points to a blank or comment line, return 0. At end
327 of file, also return 0."""
329 line = linecache.getline(filename, lineno)
330 if not line:
331 print 'End of file'
332 return 0
333 line = line.strip()
334 # Don't allow setting breakpoint at a blank line
335 if (not line or (line[0] == '#') or
336 (line[:3] == '"""') or line[:3] == "'''"):
337 print '*** Blank or comment'
338 return 0
339 # When a file is read in and a breakpoint is at
340 # the 'def' statement, the system stops there at
341 # code parse time. We don't want that, so all breakpoints
342 # set at 'def' statements are moved one line onward
343 if line[:3] == 'def':
344 instr = ''
345 brackets = 0
346 while 1:
347 skipone = 0
348 for c in line:
349 if instr:
350 if skipone:
351 skipone = 0
352 elif c == '\\':
353 skipone = 1
354 elif c == instr:
355 instr = ''
356 elif c == '#':
357 break
358 elif c in ('"',"'"):
359 instr = c
360 elif c in ('(','{','['):
361 brackets = brackets + 1
362 elif c in (')','}',']'):
363 brackets = brackets - 1
364 lineno = lineno+1
365 line = linecache.getline(filename, lineno)
366 if not line:
367 print 'end of file'
368 return 0
369 line = line.strip()
370 if not line: continue # Blank line
371 if brackets <= 0 and line[0] not in ('#','"',"'"):
372 break
373 return lineno
375 def do_enable(self, arg):
376 args = arg.split()
377 for i in args:
378 bp = bdb.Breakpoint.bpbynumber[int(i)]
379 if bp:
380 bp.enable()
382 def do_disable(self, arg):
383 args = arg.split()
384 for i in args:
385 bp = bdb.Breakpoint.bpbynumber[int(i)]
386 if bp:
387 bp.disable()
389 def do_condition(self, arg):
390 # arg is breakpoint number and condition
391 args = arg.split(' ', 1)
392 bpnum = int(args[0].strip())
393 try:
394 cond = args[1]
395 except:
396 cond = None
397 bp = bdb.Breakpoint.bpbynumber[bpnum]
398 if bp:
399 bp.cond = cond
400 if not cond:
401 print 'Breakpoint', bpnum,
402 print 'is now unconditional.'
404 def do_ignore(self,arg):
405 """arg is bp number followed by ignore count."""
406 args = arg.split()
407 bpnum = int(args[0].strip())
408 try:
409 count = int(args[1].strip())
410 except:
411 count = 0
412 bp = bdb.Breakpoint.bpbynumber[bpnum]
413 if bp:
414 bp.ignore = count
415 if count > 0:
416 reply = 'Will ignore next '
417 if count > 1:
418 reply = reply + '%d crossings' % count
419 else:
420 reply = reply + '1 crossing'
421 print reply + ' of breakpoint %d.' % bpnum
422 else:
423 print 'Will stop next time breakpoint',
424 print bpnum, 'is reached.'
426 def do_clear(self, arg):
427 """Three possibilities, tried in this order:
428 clear -> clear all breaks, ask for confirmation
429 clear file:lineno -> clear all breaks at file:lineno
430 clear bpno bpno ... -> clear breakpoints by number"""
431 if not arg:
432 try:
433 reply = raw_input('Clear all breaks? ')
434 except EOFError:
435 reply = 'no'
436 reply = reply.strip().lower()
437 if reply in ('y', 'yes'):
438 self.clear_all_breaks()
439 return
440 if ':' in arg:
441 # Make sure it works for "clear C:\foo\bar.py:12"
442 i = arg.rfind(':')
443 filename = arg[:i]
444 arg = arg[i+1:]
445 try:
446 lineno = int(arg)
447 except:
448 err = "Invalid line number (%s)" % arg
449 else:
450 err = self.clear_break(filename, lineno)
451 if err: print '***', err
452 return
453 numberlist = arg.split()
454 for i in numberlist:
455 err = self.clear_bpbynumber(i)
456 if err:
457 print '***', err
458 else:
459 print 'Deleted breakpoint %s ' % (i,)
460 do_cl = do_clear # 'c' is already an abbreviation for 'continue'
462 def do_where(self, arg):
463 self.print_stack_trace()
464 do_w = do_where
465 do_bt = do_where
467 def do_up(self, arg):
468 if self.curindex == 0:
469 print '*** Oldest frame'
470 else:
471 self.curindex = self.curindex - 1
472 self.curframe = self.stack[self.curindex][0]
473 self.print_stack_entry(self.stack[self.curindex])
474 self.lineno = None
475 do_u = do_up
477 def do_down(self, arg):
478 if self.curindex + 1 == len(self.stack):
479 print '*** Newest frame'
480 else:
481 self.curindex = self.curindex + 1
482 self.curframe = self.stack[self.curindex][0]
483 self.print_stack_entry(self.stack[self.curindex])
484 self.lineno = None
485 do_d = do_down
487 def do_step(self, arg):
488 self.set_step()
489 return 1
490 do_s = do_step
492 def do_next(self, arg):
493 self.set_next(self.curframe)
494 return 1
495 do_n = do_next
497 def do_return(self, arg):
498 self.set_return(self.curframe)
499 return 1
500 do_r = do_return
502 def do_continue(self, arg):
503 self.set_continue()
504 return 1
505 do_c = do_cont = do_continue
507 def do_jump(self, arg):
508 if self.curindex + 1 != len(self.stack):
509 print "*** You can only jump within the bottom frame"
510 return
511 try:
512 arg = int(arg)
513 except ValueError:
514 print "*** The 'jump' command requires a line number."
515 else:
516 try:
517 # Do the jump, fix up our copy of the stack, and display the
518 # new position
519 self.curframe.f_lineno = arg
520 self.stack[self.curindex] = self.stack[self.curindex][0], arg
521 self.print_stack_entry(self.stack[self.curindex])
522 except ValueError, e:
523 print '*** Jump failed:', e
524 do_j = do_jump
526 def do_debug(self, arg):
527 sys.settrace(None)
528 globals = self.curframe.f_globals
529 locals = self.curframe.f_locals
530 p = Pdb()
531 p.prompt = "(%s) " % self.prompt.strip()
532 print "ENTERING RECURSIVE DEBUGGER"
533 sys.call_tracing(p.run, (arg, globals, locals))
534 print "LEAVING RECURSIVE DEBUGGER"
535 sys.settrace(self.trace_dispatch)
536 self.lastcmd = p.lastcmd
538 def do_quit(self, arg):
539 self.set_quit()
540 return 1
541 do_q = do_quit
542 do_exit = do_quit
544 def do_EOF(self, arg):
545 print
546 self.set_quit()
547 return 1
549 def do_args(self, arg):
550 f = self.curframe
551 co = f.f_code
552 dict = f.f_locals
553 n = co.co_argcount
554 if co.co_flags & 4: n = n+1
555 if co.co_flags & 8: n = n+1
556 for i in range(n):
557 name = co.co_varnames[i]
558 print name, '=',
559 if name in dict: print dict[name]
560 else: print "*** undefined ***"
561 do_a = do_args
563 def do_retval(self, arg):
564 if '__return__' in self.curframe.f_locals:
565 print self.curframe.f_locals['__return__']
566 else:
567 print '*** Not yet returned!'
568 do_rv = do_retval
570 def _getval(self, arg):
571 try:
572 return eval(arg, self.curframe.f_globals,
573 self.curframe.f_locals)
574 except:
575 t, v = sys.exc_info()[:2]
576 if isinstance(t, str):
577 exc_type_name = t
578 else: exc_type_name = t.__name__
579 print '***', exc_type_name + ':', `v`
580 raise
582 def do_p(self, arg):
583 try:
584 print repr(self._getval(arg))
585 except:
586 pass
588 def do_pp(self, arg):
589 try:
590 pprint.pprint(self._getval(arg))
591 except:
592 pass
594 def do_list(self, arg):
595 self.lastcmd = 'list'
596 last = None
597 if arg:
598 try:
599 x = eval(arg, {}, {})
600 if type(x) == type(()):
601 first, last = x
602 first = int(first)
603 last = int(last)
604 if last < first:
605 # Assume it's a count
606 last = first + last
607 else:
608 first = max(1, int(x) - 5)
609 except:
610 print '*** Error in argument:', `arg`
611 return
612 elif self.lineno is None:
613 first = max(1, self.curframe.f_lineno - 5)
614 else:
615 first = self.lineno + 1
616 if last is None:
617 last = first + 10
618 filename = self.curframe.f_code.co_filename
619 breaklist = self.get_file_breaks(filename)
620 try:
621 for lineno in range(first, last+1):
622 line = linecache.getline(filename, lineno)
623 if not line:
624 print '[EOF]'
625 break
626 else:
627 s = `lineno`.rjust(3)
628 if len(s) < 4: s = s + ' '
629 if lineno in breaklist: s = s + 'B'
630 else: s = s + ' '
631 if lineno == self.curframe.f_lineno:
632 s = s + '->'
633 print s + '\t' + line,
634 self.lineno = lineno
635 except KeyboardInterrupt:
636 pass
637 do_l = do_list
639 def do_whatis(self, arg):
640 try:
641 value = eval(arg, self.curframe.f_globals,
642 self.curframe.f_locals)
643 except:
644 t, v = sys.exc_info()[:2]
645 if type(t) == type(''):
646 exc_type_name = t
647 else: exc_type_name = t.__name__
648 print '***', exc_type_name + ':', `v`
649 return
650 code = None
651 # Is it a function?
652 try: code = value.func_code
653 except: pass
654 if code:
655 print 'Function', code.co_name
656 return
657 # Is it an instance method?
658 try: code = value.im_func.func_code
659 except: pass
660 if code:
661 print 'Method', code.co_name
662 return
663 # None of the above...
664 print type(value)
666 def do_alias(self, arg):
667 args = arg.split()
668 if len(args) == 0:
669 keys = self.aliases.keys()
670 keys.sort()
671 for alias in keys:
672 print "%s = %s" % (alias, self.aliases[alias])
673 return
674 if args[0] in self.aliases and len(args) == 1:
675 print "%s = %s" % (args[0], self.aliases[args[0]])
676 else:
677 self.aliases[args[0]] = ' '.join(args[1:])
679 def do_unalias(self, arg):
680 args = arg.split()
681 if len(args) == 0: return
682 if args[0] in self.aliases:
683 del self.aliases[args[0]]
685 # Print a traceback starting at the top stack frame.
686 # The most recently entered frame is printed last;
687 # this is different from dbx and gdb, but consistent with
688 # the Python interpreter's stack trace.
689 # It is also consistent with the up/down commands (which are
690 # compatible with dbx and gdb: up moves towards 'main()'
691 # and down moves towards the most recent stack frame).
693 def print_stack_trace(self):
694 try:
695 for frame_lineno in self.stack:
696 self.print_stack_entry(frame_lineno)
697 except KeyboardInterrupt:
698 pass
700 def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix):
701 frame, lineno = frame_lineno
702 if frame is self.curframe:
703 print '>',
704 else:
705 print ' ',
706 print self.format_stack_entry(frame_lineno, prompt_prefix)
709 # Help methods (derived from pdb.doc)
711 def help_help(self):
712 self.help_h()
714 def help_h(self):
715 print """h(elp)
716 Without argument, print the list of available commands.
717 With a command name as argument, print help about that command
718 "help pdb" pipes the full documentation file to the $PAGER
719 "help exec" gives help on the ! command"""
721 def help_where(self):
722 self.help_w()
724 def help_w(self):
725 print """w(here)
726 Print a stack trace, with the most recent frame at the bottom.
727 An arrow indicates the "current frame", which determines the
728 context of most commands. 'bt' is an alias for this command."""
730 help_bt = help_w
732 def help_down(self):
733 self.help_d()
735 def help_d(self):
736 print """d(own)
737 Move the current frame one level down in the stack trace
738 (to an older frame)."""
740 def help_up(self):
741 self.help_u()
743 def help_u(self):
744 print """u(p)
745 Move the current frame one level up in the stack trace
746 (to a newer frame)."""
748 def help_break(self):
749 self.help_b()
751 def help_b(self):
752 print """b(reak) ([file:]lineno | function) [, condition]
753 With a line number argument, set a break there in the current
754 file. With a function name, set a break at first executable line
755 of that function. Without argument, list all breaks. If a second
756 argument is present, it is a string specifying an expression
757 which must evaluate to true before the breakpoint is honored.
759 The line number may be prefixed with a filename and a colon,
760 to specify a breakpoint in another file (probably one that
761 hasn't been loaded yet). The file is searched for on sys.path;
762 the .py suffix may be omitted."""
764 def help_clear(self):
765 self.help_cl()
767 def help_cl(self):
768 print "cl(ear) filename:lineno"
769 print """cl(ear) [bpnumber [bpnumber...]]
770 With a space separated list of breakpoint numbers, clear
771 those breakpoints. Without argument, clear all breaks (but
772 first ask confirmation). With a filename:lineno argument,
773 clear all breaks at that line in that file.
775 Note that the argument is different from previous versions of
776 the debugger (in python distributions 1.5.1 and before) where
777 a linenumber was used instead of either filename:lineno or
778 breakpoint numbers."""
780 def help_tbreak(self):
781 print """tbreak same arguments as break, but breakpoint is
782 removed when first hit."""
784 def help_enable(self):
785 print """enable bpnumber [bpnumber ...]
786 Enables the breakpoints given as a space separated list of
787 bp numbers."""
789 def help_disable(self):
790 print """disable bpnumber [bpnumber ...]
791 Disables the breakpoints given as a space separated list of
792 bp numbers."""
794 def help_ignore(self):
795 print """ignore bpnumber count
796 Sets the ignore count for the given breakpoint number. A breakpoint
797 becomes active when the ignore count is zero. When non-zero, the
798 count is decremented each time the breakpoint is reached and the
799 breakpoint is not disabled and any associated condition evaluates
800 to true."""
802 def help_condition(self):
803 print """condition bpnumber str_condition
804 str_condition is a string specifying an expression which
805 must evaluate to true before the breakpoint is honored.
806 If str_condition is absent, any existing condition is removed;
807 i.e., the breakpoint is made unconditional."""
809 def help_step(self):
810 self.help_s()
812 def help_s(self):
813 print """s(tep)
814 Execute the current line, stop at the first possible occasion
815 (either in a function that is called or in the current function)."""
817 def help_next(self):
818 self.help_n()
820 def help_n(self):
821 print """n(ext)
822 Continue execution until the next line in the current function
823 is reached or it returns."""
825 def help_return(self):
826 self.help_r()
828 def help_r(self):
829 print """r(eturn)
830 Continue execution until the current function returns."""
832 def help_continue(self):
833 self.help_c()
835 def help_cont(self):
836 self.help_c()
838 def help_c(self):
839 print """c(ont(inue))
840 Continue execution, only stop when a breakpoint is encountered."""
842 def help_jump(self):
843 self.help_j()
845 def help_j(self):
846 print """j(ump) lineno
847 Set the next line that will be executed."""
849 def help_debug(self):
850 print """debug code
851 Enter a recursive debugger that steps through the code argument
852 (which is an arbitrary expression or statement to be executed
853 in the current environment)."""
855 def help_list(self):
856 self.help_l()
858 def help_l(self):
859 print """l(ist) [first [,last]]
860 List source code for the current file.
861 Without arguments, list 11 lines around the current line
862 or continue the previous listing.
863 With one argument, list 11 lines starting at that line.
864 With two arguments, list the given range;
865 if the second argument is less than the first, it is a count."""
867 def help_args(self):
868 self.help_a()
870 def help_a(self):
871 print """a(rgs)
872 Print the arguments of the current function."""
874 def help_p(self):
875 print """p expression
876 Print the value of the expression."""
878 def help_pp(self):
879 print """pp expression
880 Pretty-print the value of the expression."""
882 def help_exec(self):
883 print """(!) statement
884 Execute the (one-line) statement in the context of
885 the current stack frame.
886 The exclamation point can be omitted unless the first word
887 of the statement resembles a debugger command.
888 To assign to a global variable you must always prefix the
889 command with a 'global' command, e.g.:
890 (Pdb) global list_options; list_options = ['-l']
891 (Pdb)"""
893 def help_quit(self):
894 self.help_q()
896 def help_q(self):
897 print """q(uit) or exit - Quit from the debugger.
898 The program being executed is aborted."""
900 help_exit = help_q
902 def help_whatis(self):
903 print """whatis arg
904 Prints the type of the argument."""
906 def help_EOF(self):
907 print """EOF
908 Handles the receipt of EOF as a command."""
910 def help_alias(self):
911 print """alias [name [command [parameter parameter ...] ]]
912 Creates an alias called 'name' the executes 'command'. The command
913 must *not* be enclosed in quotes. Replaceable parameters are
914 indicated by %1, %2, and so on, while %* is replaced by all the
915 parameters. If no command is given, the current alias for name
916 is shown. If no name is given, all aliases are listed.
918 Aliases may be nested and can contain anything that can be
919 legally typed at the pdb prompt. Note! You *can* override
920 internal pdb commands with aliases! Those internal commands
921 are then hidden until the alias is removed. Aliasing is recursively
922 applied to the first word of the command line; all other words
923 in the line are left alone.
925 Some useful aliases (especially when placed in the .pdbrc file) are:
927 #Print instance variables (usage "pi classInst")
928 alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
930 #Print instance variables in self
931 alias ps pi self
934 def help_unalias(self):
935 print """unalias name
936 Deletes the specified alias."""
938 def help_pdb(self):
939 help()
941 def lookupmodule(self, filename):
942 """Helper function for break/clear parsing -- may be overridden."""
943 root, ext = os.path.splitext(filename)
944 if ext == '':
945 filename = filename + '.py'
946 if os.path.isabs(filename):
947 return filename
948 for dirname in sys.path:
949 while os.path.islink(dirname):
950 dirname = os.readlink(dirname)
951 fullname = os.path.join(dirname, filename)
952 if os.path.exists(fullname):
953 return fullname
954 return None
956 # Simplified interface
958 def run(statement, globals=None, locals=None):
959 Pdb().run(statement, globals, locals)
961 def runeval(expression, globals=None, locals=None):
962 return Pdb().runeval(expression, globals, locals)
964 def runctx(statement, globals, locals):
965 # B/W compatibility
966 run(statement, globals, locals)
968 def runcall(*args):
969 return Pdb().runcall(*args)
971 def set_trace():
972 Pdb().set_trace()
974 # Post-Mortem interface
976 def post_mortem(t):
977 p = Pdb()
978 p.reset()
979 while t.tb_next is not None:
980 t = t.tb_next
981 p.interaction(t.tb_frame, t)
983 def pm():
984 post_mortem(sys.last_traceback)
987 # Main program for testing
989 TESTCMD = 'import x; x.main()'
991 def test():
992 run(TESTCMD)
994 # print help
995 def help():
996 for dirname in sys.path:
997 fullname = os.path.join(dirname, 'pdb.doc')
998 if os.path.exists(fullname):
999 sts = os.system('${PAGER-more} '+fullname)
1000 if sts: print '*** Pager exit status:', sts
1001 break
1002 else:
1003 print 'Sorry, can\'t find the help file "pdb.doc"',
1004 print 'along the Python search path'
1006 mainmodule = ''
1007 mainpyfile = ''
1009 # When invoked as main program, invoke the debugger on a script
1010 if __name__=='__main__':
1011 if not sys.argv[1:]:
1012 print "usage: pdb.py scriptfile [arg] ..."
1013 sys.exit(2)
1015 mainpyfile = filename = sys.argv[1] # Get script filename
1016 if not os.path.exists(filename):
1017 print 'Error:', `filename`, 'does not exist'
1018 sys.exit(1)
1019 mainmodule = os.path.basename(filename)
1020 del sys.argv[0] # Hide "pdb.py" from argument list
1022 # Insert script directory in front of module search path
1023 sys.path.insert(0, os.path.dirname(filename))
1025 run('execfile(' + `filename` + ')')