home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / pytho152.zip / emx / lib / python1.5 / pdb.py < prev    next >
Text File  |  2000-08-10  |  25KB  |  922 lines

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