home *** CD-ROM | disk | FTP | other *** search
/ Chip 2004 December / CHIP_CD_2004-12.iso / bonus / oo / OOo_1.1.3_ru_RU_infra_WinIntel_install.exe / $PLUGINSDIR / f_0372 / python-core-2.2.2 / lib / pdb.py < prev    next >
Text File  |  2004-10-09  |  30KB  |  958 lines

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