home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / pyos2bin.zip / Lib / pdb.py < prev    next >
Text File  |  1997-09-29  |  13KB  |  529 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.  
  14.  
  15. # Interaction prompt line will separate file and call info from code
  16. # text using value of line_prefix string.  A newline and arrow may
  17. # be to your liking.  You can set it once pdb is imported using the
  18. # command "pdb.line_prefix = '\n% '".
  19. # line_prefix = ': '    # Use this to get the old situation back
  20. line_prefix = '\n-> '    # Probably a better default
  21.  
  22. class Pdb(bdb.Bdb, cmd.Cmd):
  23.     
  24.     def __init__(self):
  25.         bdb.Bdb.__init__(self)
  26.         cmd.Cmd.__init__(self)
  27.         self.prompt = '(Pdb) '
  28.     
  29.     def reset(self):
  30.         bdb.Bdb.reset(self)
  31.         self.forget()
  32.     
  33.     def forget(self):
  34.         self.lineno = None
  35.         self.stack = []
  36.         self.curindex = 0
  37.         self.curframe = None
  38.     
  39.     def setup(self, f, t):
  40.         self.forget()
  41.         self.stack, self.curindex = self.get_stack(f, t)
  42.         self.curframe = self.stack[self.curindex][0]
  43.     
  44.     # Override Bdb methods (except user_call, for now)
  45.     
  46.     def user_line(self, frame):
  47.         # This function is called when we stop or break at this line
  48.         self.interaction(frame, None)
  49.     
  50.     def user_return(self, frame, return_value):
  51.         # This function is called when a return trap is set here
  52.         frame.f_locals['__return__'] = return_value
  53.         print '--Return--'
  54.         self.interaction(frame, None)
  55.     
  56.     def user_exception(self, frame, (exc_type, exc_value, exc_traceback)):
  57.         # This function is called if an exception occurs,
  58.         # but only if we are to stop at or just below this level
  59.         frame.f_locals['__exception__'] = exc_type, exc_value
  60.         if type(exc_type) == type(''):
  61.             exc_type_name = exc_type
  62.         else: exc_type_name = exc_type.__name__
  63.         print exc_type_name + ':', repr.repr(exc_value)
  64.         self.interaction(frame, exc_traceback)
  65.     
  66.     # General interaction function
  67.     
  68.     def interaction(self, frame, traceback):
  69.         self.setup(frame, traceback)
  70.         self.print_stack_entry(self.stack[self.curindex])
  71.         self.cmdloop()
  72.         self.forget()
  73.  
  74.     def default(self, line):
  75.         if line[:1] == '!': line = line[1:]
  76.         locals = self.curframe.f_locals
  77.         globals = self.curframe.f_globals
  78.         globals['__privileged__'] = 1
  79.         try:
  80.             code = compile(line + '\n', '<stdin>', 'single')
  81.             exec code in globals, locals
  82.         except:
  83.             t, v = sys.exc_info()[:2]
  84.             if type(t) == type(''):
  85.                 exc_type_name = t
  86.             else: exc_type_name = t.__name__
  87.             print '***', exc_type_name + ':', v
  88.  
  89.     # Command definitions, called by cmdloop()
  90.     # The argument is the remaining string on the command line
  91.     # Return true to exit from the command loop 
  92.     
  93.     do_h = cmd.Cmd.do_help
  94.  
  95.     def do_break(self, arg):
  96.         if not arg:
  97.             print self.get_all_breaks() # XXX
  98.             return
  99.         # Try line number as argument
  100.         try:
  101.             arg = eval(arg, self.curframe.f_globals,
  102.                    self.curframe.f_locals)
  103.         except:
  104.             print '*** Could not eval argument:', arg
  105.             return
  106.  
  107.         # Check for condition
  108.         try: arg, cond = arg
  109.         except: arg, cond = arg, None
  110.  
  111.         try:    
  112.             lineno = int(arg)
  113.             filename = self.curframe.f_code.co_filename
  114.         except:
  115.             # Try function name as the argument
  116.             try:
  117.                 func = arg
  118.                 if hasattr(func, 'im_func'):
  119.                     func = func.im_func
  120.                 code = func.func_code
  121.             except:
  122.                 print '*** The specified object',
  123.                 print 'is not a function', arg
  124.                 return
  125.             lineno = code.co_firstlineno
  126.             filename = code.co_filename
  127.  
  128.         # now set the break point
  129.         err = self.set_break(filename, lineno, cond)
  130.         if err: print '***', err
  131.  
  132.     do_b = do_break
  133.     
  134.     def do_clear(self, arg):
  135.         if not arg:
  136.             try:
  137.                 reply = raw_input('Clear all breaks? ')
  138.             except EOFError:
  139.                 reply = 'no'
  140.             reply = string.lower(string.strip(reply))
  141.             if reply in ('y', 'yes'):
  142.                 self.clear_all_breaks()
  143.             return
  144.         try:
  145.             lineno = int(eval(arg))
  146.         except:
  147.             print '*** Error in argument:', `arg`
  148.             return
  149.         filename = self.curframe.f_code.co_filename
  150.         err = self.clear_break(filename, lineno)
  151.         if err: print '***', err
  152.     do_cl = do_clear # 'c' is already an abbreviation for 'continue'
  153.     
  154.     def do_where(self, arg):
  155.         self.print_stack_trace()
  156.     do_w = do_where
  157.     
  158.     def do_up(self, arg):
  159.         if self.curindex == 0:
  160.             print '*** Oldest frame'
  161.         else:
  162.             self.curindex = self.curindex - 1
  163.             self.curframe = self.stack[self.curindex][0]
  164.             self.print_stack_entry(self.stack[self.curindex])
  165.             self.lineno = None
  166.     do_u = do_up
  167.     
  168.     def do_down(self, arg):
  169.         if self.curindex + 1 == len(self.stack):
  170.             print '*** Newest frame'
  171.         else:
  172.             self.curindex = self.curindex + 1
  173.             self.curframe = self.stack[self.curindex][0]
  174.             self.print_stack_entry(self.stack[self.curindex])
  175.             self.lineno = None
  176.     do_d = do_down
  177.     
  178.     def do_step(self, arg):
  179.         self.set_step()
  180.         return 1
  181.     do_s = do_step
  182.     
  183.     def do_next(self, arg):
  184.         self.set_next(self.curframe)
  185.         return 1
  186.     do_n = do_next
  187.     
  188.     def do_return(self, arg):
  189.         self.set_return(self.curframe)
  190.         return 1
  191.     do_r = do_return
  192.     
  193.     def do_continue(self, arg):
  194.         self.set_continue()
  195.         return 1
  196.     do_c = do_cont = do_continue
  197.     
  198.     def do_quit(self, arg):
  199.         self.set_quit()
  200.         return 1
  201.     do_q = do_quit
  202.     
  203.     def do_args(self, arg):
  204.         if self.curframe.f_locals.has_key('__args__'):
  205.             print `self.curframe.f_locals['__args__']`
  206.         else:
  207.             print '*** No arguments?!'
  208.     do_a = do_args
  209.     
  210.     def do_retval(self, arg):
  211.         if self.curframe.f_locals.has_key('__return__'):
  212.             print self.curframe.f_locals['__return__']
  213.         else:
  214.             print '*** Not yet returned!'
  215.     do_rv = do_retval
  216.     
  217.     def do_p(self, arg):
  218.         self.curframe.f_globals['__privileged__'] = 1
  219.         try:
  220.             value = eval(arg, self.curframe.f_globals, \
  221.                     self.curframe.f_locals)
  222.         except:
  223.             t, v = sys.exc_info()[:2]
  224.             if type(t) == type(''):
  225.                 exc_type_name = t
  226.             else: exc_type_name = t.__name__
  227.             print '***', exc_type_name + ':', `v`
  228.             return
  229.  
  230.         print `value`
  231.  
  232.     def do_list(self, arg):
  233.         self.lastcmd = 'list'
  234.         last = None
  235.         if arg:
  236.             try:
  237.                 x = eval(arg, {}, {})
  238.                 if type(x) == type(()):
  239.                     first, last = x
  240.                     first = int(first)
  241.                     last = int(last)
  242.                     if last < first:
  243.                         # Assume it's a count
  244.                         last = first + last
  245.                 else:
  246.                     first = max(1, int(x) - 5)
  247.             except:
  248.                 print '*** Error in argument:', `arg`
  249.                 return
  250.         elif self.lineno is None:
  251.             first = max(1, self.curframe.f_lineno - 5)
  252.         else:
  253.             first = self.lineno + 1
  254.         if last == None:
  255.             last = first + 10
  256.         filename = self.curframe.f_code.co_filename
  257.         breaklist = self.get_file_breaks(filename)
  258.         try:
  259.             for lineno in range(first, last+1):
  260.                 line = linecache.getline(filename, lineno)
  261.                 if not line:
  262.                     print '[EOF]'
  263.                     break
  264.                 else:
  265.                     s = string.rjust(`lineno`, 3)
  266.                     if len(s) < 4: s = s + ' '
  267.                     if lineno in breaklist: s = s + 'B'
  268.                     else: s = s + ' '
  269.                     if lineno == self.curframe.f_lineno:
  270.                         s = s + '->'
  271.                     print s + '\t' + line,
  272.                     self.lineno = lineno
  273.         except KeyboardInterrupt:
  274.             pass
  275.     do_l = do_list
  276.  
  277.     def do_whatis(self, arg):
  278.         try:
  279.             value = eval(arg, self.curframe.f_globals, \
  280.                     self.curframe.f_locals)
  281.         except:
  282.             t, v = sys.exc_info()[:2]
  283.             if type(t) == type(''):
  284.                 exc_type_name = t
  285.             else: exc_type_name = t.__name__
  286.             print '***', exc_type_name + ':', `v`
  287.             return
  288.         code = None
  289.         # Is it a function?
  290.         try: code = value.func_code
  291.         except: pass
  292.         if code:
  293.             print 'Function', code.co_name
  294.             return
  295.         # Is it an instance method?
  296.         try: code = value.im_func.func_code
  297.         except: pass
  298.         if code:
  299.             print 'Method', code.co_name
  300.             return
  301.         # None of the above...
  302.         print type(value)
  303.     
  304.     # Print a traceback starting at the top stack frame.
  305.     # The most recently entered frame is printed last;
  306.     # this is different from dbx and gdb, but consistent with
  307.     # the Python interpreter's stack trace.
  308.     # It is also consistent with the up/down commands (which are
  309.     # compatible with dbx and gdb: up moves towards 'main()'
  310.     # and down moves towards the most recent stack frame).
  311.     
  312.     def print_stack_trace(self):
  313.         try:
  314.             for frame_lineno in self.stack:
  315.                 self.print_stack_entry(frame_lineno)
  316.         except KeyboardInterrupt:
  317.             pass
  318.     
  319.     def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix):
  320.         frame, lineno = frame_lineno
  321.         if frame is self.curframe:
  322.             print '>',
  323.         else:
  324.             print ' ',
  325.         print self.format_stack_entry(frame_lineno, prompt_prefix)
  326.  
  327.  
  328.     # Help methods (derived from pdb.doc)
  329.  
  330.     def help_help(self):
  331.         self.help_h()
  332.  
  333.     def help_h(self):
  334.         print """h(elp)
  335.     Without argument, print the list of available commands.
  336.     With a command name as argument, print help about that command
  337.     "help pdb" pipes the full documentation file to the $PAGER
  338.     "help exec" gives help on the ! command"""
  339.  
  340.     def help_where(self):
  341.         self.help_w()
  342.  
  343.     def help_w(self):
  344.         print """w(here)
  345.     Print a stack trace, with the most recent frame at the bottom.
  346.     An arrow indicates the "current frame", which determines the
  347.     context of most commands."""
  348.  
  349.     def help_down(self):
  350.         self.help_d()
  351.  
  352.     def help_d(self):
  353.         print """d(own)
  354.     Move the current frame one level down in the stack trace
  355.     (to an older frame)."""
  356.  
  357.     def help_up(self):
  358.         self.help_u()
  359.  
  360.     def help_u(self):
  361.         print """u(p)
  362.     Move the current frame one level up in the stack trace
  363.     (to a newer frame)."""
  364.  
  365.     def help_break(self):
  366.         self.help_b()
  367.  
  368.     def help_b(self):
  369.         print """b(reak) [lineno | function] [, "condition"]
  370.     With a line number argument, set a break there in the current
  371.     file.  With a function name, set a break at the entry of that
  372.     function.  Without argument, list all breaks.  If a second
  373.     argument is present, it is a string specifying an expression
  374.     which must evaluate to true before the breakpoint is honored.
  375.     """
  376.  
  377.     def help_clear(self):
  378.         self.help_cl()
  379.  
  380.     def help_cl(self):
  381.         print """cl(ear) [lineno]
  382.     With a line number argument, clear that break in the current file.
  383.     Without argument, clear all breaks (but first ask confirmation)."""
  384.  
  385.     def help_step(self):
  386.         self.help_s()
  387.  
  388.     def help_s(self):
  389.         print """s(tep)
  390.     Execute the current line, stop at the first possible occasion
  391.     (either in a function that is called or in the current function)."""
  392.  
  393.     def help_next(self):
  394.         self.help_n()
  395.  
  396.     def help_n(self):
  397.         print """n(ext)
  398.     Continue execution until the next line in the current function
  399.     is reached or it returns."""
  400.  
  401.     def help_return(self):
  402.         self.help_r()
  403.  
  404.     def help_r(self):
  405.         print """r(eturn)
  406.     Continue execution until the current function returns."""
  407.  
  408.     def help_continue(self):
  409.         self.help_c()
  410.  
  411.     def help_cont(self):
  412.         self.help_c()
  413.  
  414.     def help_c(self):
  415.         print """c(ont(inue))
  416.     Continue execution, only stop when a breakpoint is encountered."""
  417.  
  418.     def help_list(self):
  419.         self.help_l()
  420.  
  421.     def help_l(self):
  422.         print """l(ist) [first [,last]]
  423.     List source code for the current file.
  424.     Without arguments, list 11 lines around the current line
  425.     or continue the previous listing.
  426.     With one argument, list 11 lines starting at that line.
  427.     With two arguments, list the given range;
  428.     if the second argument is less than the first, it is a count."""
  429.  
  430.     def help_args(self):
  431.         self.help_a()
  432.  
  433.     def help_a(self):
  434.         print """a(rgs)
  435.     Print the argument list of the current function."""
  436.  
  437.     def help_p(self):
  438.         print """p expression
  439.     Print the value of the expression."""
  440.  
  441.     def help_exec(self):
  442.         print """(!) statement
  443.     Execute the (one-line) statement in the context of
  444.     the current stack frame.
  445.     The exclamation point can be omitted unless the first word
  446.     of the statement resembles a debugger command.
  447.     To assign to a global variable you must always prefix the
  448.     command with a 'global' command, e.g.:
  449.     (Pdb) global list_options; list_options = ['-l']
  450.     (Pdb)"""
  451.  
  452.     def help_quit(self):
  453.         self.help_q()
  454.  
  455.     def help_q(self):
  456.         print """q(uit)    Quit from the debugger.
  457.     The program being executed is aborted."""
  458.  
  459.     def help_pdb(self):
  460.         help()
  461.  
  462. # Simplified interface
  463.  
  464. def run(statement, globals=None, locals=None):
  465.     Pdb().run(statement, globals, locals)
  466.  
  467. def runeval(expression, globals=None, locals=None):
  468.     return Pdb().runeval(expression, globals, locals)
  469.  
  470. def runctx(statement, globals, locals):
  471.     # B/W compatibility
  472.     run(statement, globals, locals)
  473.  
  474. def runcall(*args):
  475.     return apply(Pdb().runcall, args)
  476.  
  477. def set_trace():
  478.     Pdb().set_trace()
  479.  
  480. # Post-Mortem interface
  481.  
  482. def post_mortem(t):
  483.     p = Pdb()
  484.     p.reset()
  485.     while t.tb_next <> None: t = t.tb_next
  486.     p.interaction(t.tb_frame, t)
  487.  
  488. def pm():
  489.     import sys
  490.     post_mortem(sys.last_traceback)
  491.  
  492.  
  493. # Main program for testing
  494.  
  495. TESTCMD = 'import x; x.main()'
  496.  
  497. def test():
  498.     run(TESTCMD)
  499.  
  500. # print help
  501. def help():
  502.     import os
  503.     for dirname in sys.path:
  504.         fullname = os.path.join(dirname, 'pdb.doc')
  505.         if os.path.exists(fullname):
  506.             sts = os.system('${PAGER-more} '+fullname)
  507.             if sts: print '*** Pager exit status:', sts
  508.             break
  509.     else:
  510.         print 'Sorry, can\'t find the help file "pdb.doc"',
  511.         print 'along the Python search path'
  512.  
  513. # When invoked as main program, invoke the debugger on a script
  514. if __name__=='__main__':
  515.     import sys
  516.     import os
  517.     if not sys.argv[1:]:
  518.         print "usage: pdb.py scriptfile [arg] ..."
  519.         sys.exit(2)
  520.  
  521.     filename = sys.argv[1]    # Get script filename
  522.  
  523.     del sys.argv[0]        # Hide "pdb.py" from argument list
  524.  
  525.     # Insert script directory in front of module search path
  526.     sys.path.insert(0, os.path.dirname(filename))
  527.  
  528.     run('execfile(' + `filename` + ')', {'__name__': '__main__'})
  529.