home *** CD-ROM | disk | FTP | other *** search
/ PC PowerPlay 56 / CDPowerplay56Disc2.iso / demos / blade / data1.cab / Program_Executable_Files / Lib / Bldb.py < prev    next >
Encoding:
Python Source  |  2000-10-27  |  19.0 KB  |  752 lines

  1. #! /usr/bin/env python
  2.  
  3. # Bldb.py -- Blade Python debugger
  4.  
  5.  
  6.  
  7. import string
  8. import sys
  9. import linecache
  10. import cmd
  11. import bdb
  12. import repr
  13.  
  14. import os
  15. import Bldbx
  16. import win32file
  17. import win32pipe
  18. import win32api
  19.  
  20.  
  21. # Interaction prompt line will separate file and call info from code
  22. # text using value of line_prefix string.  A newline and arrow may
  23. # be to your liking.  You can set it once pdb is imported using the
  24. # command "pdb.line_prefix = '\n% '".
  25. # line_prefix = ': '    # Use this to get the old situation back
  26. line_prefix = '\n-> '    # Probably a better default
  27.  
  28. class Bldb(bdb.Bdb, cmd.Cmd):
  29.     
  30.     def __init__(self):
  31.         bdb.Bdb.__init__(self)
  32.         cmd.Cmd.__init__(self)
  33.         self.prompt = '(Bldb) '
  34.  
  35.         self.UseBldbx=Bldbx.initComm("BPyDebug")
  36.         if self.UseBldbx:
  37.             print "BPyDebug found."
  38.         else:
  39.             print "Can't find BPyDebug."
  40.  
  41.         try:
  42.             self.pipe=win32file.CreateFile("\\\\.\\pipe\\BPyDebug",win32file.GENERIC_READ|win32file.GENERIC_WRITE,win32file.FILE_SHARE_WRITE|win32file.FILE_SHARE_READ,None,win32file.OPEN_EXISTING,0,0)
  43.             self.status=win32pipe.GetNamedPipeHandleState(self.pipe)
  44.             self.UsePipe=1
  45.  
  46.             str_path=os.getcwd()+";"
  47.             for i in sys.path:
  48.                 str_path=str_path+str(i)+";"
  49.             self.SendMessageToDebugger("Init;"+str_path)
  50.         except:
  51.             self.UsePipe=0
  52.  
  53.         if self.UsePipe==0:
  54.             print "Can┤t use pipes to communicate with the debugger."
  55.         else:
  56.             print "self.UsePipe"
  57.             self.old_stdout=sys.stdout
  58.             self.old_stderr=sys.stderr
  59.             sys.stdout=self
  60.  
  61.  
  62.     
  63.     def reset(self):
  64.         bdb.Bdb.reset(self)
  65.         self.forget()
  66.  
  67.     def forget(self):
  68.         self.lineno = None
  69.         self.stack = []
  70.         self.curindex = 0
  71.         self.curframe = None
  72.     
  73.     def setup(self, f, t):
  74.         self.forget()
  75.         self.stack, self.curindex = self.get_stack(f, t)
  76.         self.curframe = self.stack[self.curindex][0]
  77.         #informo al depurador del archivo en el que estamos
  78.         self.UpdateDebugger()
  79.  
  80.  
  81.     # Override Bdb methods (except user_call, for now)
  82.     
  83.     def user_line(self, frame):
  84.         # This function is called when we stop or break at this line
  85.         self.interaction(frame, None)
  86.     
  87.     def user_return(self, frame, return_value):
  88.         # This function is called when a return trap is set here
  89.         frame.f_locals['__return__'] = return_value
  90.         print '--Return--'
  91.         self.interaction(frame, None)
  92.     
  93.     def user_exception(self, frame, (exc_type, exc_value, exc_traceback)):
  94.         # This function is called if an exception occurs,
  95.         # but only if we are to stop at or just below this level
  96.         frame.f_locals['__exception__'] = exc_type, exc_value
  97.         if type(exc_type) == type(''):
  98.             exc_type_name = exc_type
  99.         else: exc_type_name = exc_type.__name__
  100.         print exc_type_name + ':', repr.repr(exc_value)
  101.         self.interaction(frame, exc_traceback)
  102.     
  103.     # General interaction function
  104.     
  105.     def interaction(self, frame, traceback):
  106.         self.setup(frame, traceback)
  107.         if not self.UseBldbx:
  108.             self.print_stack_entry(self.stack[self.curindex])
  109.         self.cmdloop()
  110.         self.forget()
  111.  
  112.     def default(self, line):
  113.         if line[:1] == '!': line = line[1:]
  114.         locals = self.curframe.f_locals
  115.         globals = self.curframe.f_globals
  116.         globals['__privileged__'] = 1
  117.         try:
  118.             code = compile(line + '\n', '<stdin>', 'single')
  119.             exec code in globals, locals
  120.         except:
  121.             t, v = sys.exc_info()[:2]
  122.             if type(t) == type(''):
  123.                 exc_type_name = t
  124.             else: exc_type_name = t.__name__
  125.             print '***', exc_type_name + ':', v
  126.  
  127.     # Command definitions, called by cmdloop()
  128.     # The argument is the remaining string on the command line
  129.     # Return true to exit from the command loop 
  130.     
  131.     do_h = cmd.Cmd.do_help
  132.  
  133.     def do_break(self, arg):
  134.         if not arg:
  135.             print self.get_all_breaks() # XXX
  136.             return
  137.         # Try line number as argument
  138.         try:
  139.             arg = eval(arg, self.curframe.f_globals,
  140.                    self.curframe.f_locals)
  141.         except:
  142.             print '*** Could not eval argument:', arg
  143.             return
  144.  
  145.         # Check for condition
  146.         try: arg, cond = arg
  147.         except: arg, cond = arg, None
  148.  
  149.         try:    
  150.             lineno = int(arg)
  151.             filename = self.curframe.f_code.co_filename
  152.         except:
  153.             # Try function name as the argument
  154.             try:
  155.                 func = arg
  156.                 if hasattr(func, 'im_func'):
  157.                     func = func.im_func
  158.                 code = func.func_code
  159.             except:
  160.                 print '*** The specified object',
  161.                 print 'is not a function', arg
  162.                 return
  163.             lineno = code.co_firstlineno
  164.             filename = code.co_filename
  165.  
  166.         # now set the break point
  167.         err = self.set_break(filename, lineno, cond)
  168.         if err: print '***', err
  169.  
  170.     do_b = do_break
  171.     
  172.     def do_clear(self, arg):
  173.         if not arg:
  174.             try:
  175.                 reply = raw_input('Clear all breaks? ')
  176.             except EOFError:
  177.                 reply = 'no'
  178.             reply = string.lower(string.strip(reply))
  179.             if reply in ('y', 'yes'):
  180.                 self.clear_all_breaks()
  181.             return
  182.         try:
  183.             lineno = int(eval(arg))
  184.         except:
  185.             print '*** Error in argument:', `arg`
  186.             return
  187.         filename = self.curframe.f_code.co_filename
  188.         err = self.clear_break(filename, lineno)
  189.         if err: print '***', err
  190.     do_cl = do_clear # 'c' is already an abbreviation for 'continue'
  191.     
  192.     def do_where(self, arg):
  193.         self.print_stack_trace()
  194.     do_w = do_where
  195.     
  196.     def do_up(self, arg):
  197.         if self.curindex == 0:
  198.             print '*** Oldest frame'
  199.         else:
  200.             self.curindex = self.curindex - 1
  201.             self.curframe = self.stack[self.curindex][0]
  202.             self.print_stack_entry(self.stack[self.curindex])
  203.             self.lineno = None
  204.     do_u = do_up
  205.     
  206.     def do_down(self, arg):
  207.         if self.curindex + 1 == len(self.stack):
  208.             print '*** Newest frame'
  209.         else:
  210.             self.curindex = self.curindex + 1
  211.             self.curframe = self.stack[self.curindex][0]
  212.             self.print_stack_entry(self.stack[self.curindex])
  213.             self.lineno = None
  214.     do_d = do_down
  215.     
  216.     def do_step(self, arg):
  217.         self.set_step()
  218.         return 1
  219.     do_s = do_step
  220.     
  221.     def do_next(self, arg):
  222.         self.set_next(self.curframe)
  223.         return 1
  224.     do_n = do_next
  225.     
  226.     def do_return(self, arg):
  227.         self.set_return(self.curframe)
  228.         return 1
  229.     do_r = do_return
  230.     
  231.     def do_continue(self, arg):
  232.         self.set_continue()
  233.         return 1
  234.     do_c = do_cont = do_continue
  235.     
  236.     def do_quit(self, arg):
  237.         self.set_quit()
  238.         return 1
  239.     do_q = do_quit
  240.     
  241.     def do_args(self, arg):
  242.         f = self.curframe
  243.         co = f.f_code
  244.         dict = f.f_locals
  245.         n = co.co_argcount
  246.         if co.co_flags & 4: n = n+1
  247.         if co.co_flags & 8: n = n+1
  248.         for i in range(n):
  249.             name = co.co_varnames[i]
  250.             print name, '=',
  251.             if dict.has_key(name): print dict[name]
  252.             else: print "*** undefined ***"
  253.     do_a = do_args
  254.     
  255.     def do_retval(self, arg):
  256.         if self.curframe.f_locals.has_key('__return__'):
  257.             print self.curframe.f_locals['__return__']
  258.         else:
  259.             print '*** Not yet returned!'
  260.     do_rv = do_retval
  261.     
  262.     def do_p(self, arg):
  263.         self.curframe.f_globals['__privileged__'] = 1
  264.         try:
  265.             value = eval(arg, self.curframe.f_globals, \
  266.                     self.curframe.f_locals)
  267.         except:
  268.             t, v = sys.exc_info()[:2]
  269.             if type(t) == type(''):
  270.                 exc_type_name = t
  271.             else: exc_type_name = t.__name__
  272.             print '***', exc_type_name + ':', `v`
  273.             return
  274.  
  275.         print `value`
  276.  
  277.     def do_list(self, arg):
  278.         self.lastcmd = 'list'
  279.         last = None
  280.         if arg:
  281.             try:
  282.                 x = eval(arg, {}, {})
  283.                 if type(x) == type(()):
  284.                     first, last = x
  285.                     first = int(first)
  286.                     last = int(last)
  287.                     if last < first:
  288.                         # Assume it's a count
  289.                         last = first + last
  290.                 else:
  291.                     first = max(1, int(x) - 5)
  292.             except:
  293.                 print '*** Error in argument:', `arg`
  294.                 return
  295.         elif self.lineno is None:
  296.             first = max(1, self.curframe.f_lineno - 5)
  297.         else:
  298.             first = self.lineno + 1
  299.         if last == None:
  300.             last = first + 10
  301.         filename = self.curframe.f_code.co_filename
  302.         breaklist = self.get_file_breaks(filename)
  303.         try:
  304.             for lineno in range(first, last+1):
  305.                 line = linecache.getline(filename, lineno)
  306.                 if not line:
  307.                     print '[EOF]'
  308.                     break
  309.                 else:
  310.                     s = string.rjust(`lineno`, 3)
  311.                     if len(s) < 4: s = s + ' '
  312.                     if lineno in breaklist: s = s + 'B'
  313.                     else: s = s + ' '
  314.                     if lineno == self.curframe.f_lineno:
  315.                         s = s + '->'
  316.                     print s + '\t' + line,
  317.                     self.lineno = lineno
  318.         except KeyboardInterrupt:
  319.             pass
  320.     do_l = do_list
  321.  
  322.     def do_whatis(self, arg):
  323.         try:
  324.             value = eval(arg, self.curframe.f_globals, \
  325.                     self.curframe.f_locals)
  326.         except:
  327.             t, v = sys.exc_info()[:2]
  328.             if type(t) == type(''):
  329.                 exc_type_name = t
  330.             else: exc_type_name = t.__name__
  331.             print '***', exc_type_name + ':', `v`
  332.             return
  333.         code = None
  334.         # Is it a function?
  335.         try: code = value.func_code
  336.         except: pass
  337.         if code:
  338.             print 'Function', code.co_name
  339.             return
  340.         # Is it an instance method?
  341.         try: code = value.im_func.func_code
  342.         except: pass
  343.         if code:
  344.             print 'Method', code.co_name
  345.             return
  346.         # None of the above...
  347.         print type(value)
  348.     
  349.     # Print a traceback starting at the top stack frame.
  350.     # The most recently entered frame is printed last;
  351.     # this is different from dbx and gdb, but consistent with
  352.     # the Python interpreter's stack trace.
  353.     # It is also consistent with the up/down commands (which are
  354.     # compatible with dbx and gdb: up moves towards 'main()'
  355.     # and down moves towards the most recent stack frame).
  356.     
  357.     def print_stack_trace(self):
  358.         try:
  359.             for frame_lineno in self.stack:
  360.                 self.print_stack_entry(frame_lineno)
  361.         except KeyboardInterrupt:
  362.             pass
  363.     
  364.     def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix):
  365.         frame, lineno = frame_lineno
  366.         if frame is self.curframe:
  367.             print '>',
  368.         else:
  369.             print ' ',
  370.         print self.format_stack_entry(frame_lineno, prompt_prefix)
  371.  
  372.  
  373.     # Help methods (derived from pdb.doc)
  374.  
  375.     def help_help(self):
  376.         self.help_h()
  377.  
  378.     def help_h(self):
  379.         print """h(elp)
  380.     Without argument, print the list of available commands.
  381.     With a command name as argument, print help about that command
  382.     "help pdb" pipes the full documentation file to the $PAGER
  383.     "help exec" gives help on the ! command"""
  384.  
  385.     def help_where(self):
  386.         self.help_w()
  387.  
  388.     def help_w(self):
  389.         print """w(here)
  390.     Print a stack trace, with the most recent frame at the bottom.
  391.     An arrow indicates the "current frame", which determines the
  392.     context of most commands."""
  393.  
  394.     def help_down(self):
  395.         self.help_d()
  396.  
  397.     def help_d(self):
  398.         print """d(own)
  399.     Move the current frame one level down in the stack trace
  400.     (to an older frame)."""
  401.  
  402.     def help_up(self):
  403.         self.help_u()
  404.  
  405.     def help_u(self):
  406.         print """u(p)
  407.     Move the current frame one level up in the stack trace
  408.     (to a newer frame)."""
  409.  
  410.     def help_break(self):
  411.         self.help_b()
  412.  
  413.     def help_b(self):
  414.         print """b(reak) [lineno | function] [, "condition"]
  415.     With a line number argument, set a break there in the current
  416.     file.  With a function name, set a break at the entry of that
  417.     function.  Without argument, list all breaks.  If a second
  418.     argument is present, it is a string specifying an expression
  419.     which must evaluate to true before the breakpoint is honored.
  420.     """
  421.  
  422.     def help_clear(self):
  423.         self.help_cl()
  424.  
  425.     def help_cl(self):
  426.         print """cl(ear) [lineno]
  427.     With a line number argument, clear that break in the current file.
  428.     Without argument, clear all breaks (but first ask confirmation)."""
  429.  
  430.     def help_step(self):
  431.         self.help_s()
  432.  
  433.     def help_s(self):
  434.         print """s(tep)
  435.     Execute the current line, stop at the first possible occasion
  436.     (either in a function that is called or in the current function)."""
  437.  
  438.     def help_next(self):
  439.         self.help_n()
  440.  
  441.     def help_n(self):
  442.         print """n(ext)
  443.     Continue execution until the next line in the current function
  444.     is reached or it returns."""
  445.  
  446.     def help_return(self):
  447.         self.help_r()
  448.  
  449.     def help_r(self):
  450.         print """r(eturn)
  451.     Continue execution until the current function returns."""
  452.  
  453.     def help_continue(self):
  454.         self.help_c()
  455.  
  456.     def help_cont(self):
  457.         self.help_c()
  458.  
  459.     def help_c(self):
  460.         print """c(ont(inue))
  461.     Continue execution, only stop when a breakpoint is encountered."""
  462.  
  463.     def help_list(self):
  464.         self.help_l()
  465.  
  466.     def help_l(self):
  467.         print """l(ist) [first [,last]]
  468.     List source code for the current file.
  469.     Without arguments, list 11 lines around the current line
  470.     or continue the previous listing.
  471.     With one argument, list 11 lines starting at that line.
  472.     With two arguments, list the given range;
  473.     if the second argument is less than the first, it is a count."""
  474.  
  475.     def help_args(self):
  476.         self.help_a()
  477.  
  478.     def help_a(self):
  479.         print """a(rgs)
  480.     Print the arguments of the current function."""
  481.  
  482.     def help_p(self):
  483.         print """p expression
  484.     Print the value of the expression."""
  485.  
  486.     def help_exec(self):
  487.         print """(!) statement
  488.     Execute the (one-line) statement in the context of
  489.     the current stack frame.
  490.     The exclamation point can be omitted unless the first word
  491.     of the statement resembles a debugger command.
  492.     To assign to a global variable you must always prefix the
  493.     command with a 'global' command, e.g.:
  494.     (Pdb) global list_options; list_options = ['-l']
  495.     (Pdb)"""
  496.  
  497.     def help_quit(self):
  498.         self.help_q()
  499.  
  500.     def help_q(self):
  501.         print """q(uit)    Quit from the debugger.
  502.     The program being executed is aborted."""
  503.  
  504.     def help_pdb(self):
  505.         help()
  506.  
  507.  
  508.  
  509.     # Nuevo cmdloop con win32pipe
  510.     def cmdloop(self):
  511.         stop = None
  512.         while not stop:
  513.             try:
  514.                 if self.UsePipe:
  515.                     line = win32file.ReadFile(self.pipe,512,None)[1]
  516.                 else:
  517.                     #sys.stdout=self.old_stdout
  518.                     line=raw_input(self.prompt)
  519.                     #sys.stdout=self
  520.             except EOFError:
  521.                 line = 'EOF'
  522.             stop = self.onecmd(line)
  523.  
  524.     def SendMessageToDebugger(self,message):
  525.         if self.UseBldbx:
  526.             Bldbx.SendDebugMessage(0,message)
  527.  
  528.     # Comunica al depurador en que archivo estmos
  529.     def SetDebugFile(self,filename,linenumber):
  530.         #full_path=os.path.abspath(filename)
  531.         string="Filename;"+str(linenumber)+";"+filename
  532.         #string="Filename;"+str(linenumber)+";"+str(full_path)
  533.         self.SendMessageToDebugger(string)
  534.  
  535.  
  536.     # Redirecciona la salida al depurador
  537.     def write(self,message):
  538.         string="Output;"+str(message)
  539.         #self.old_stdout.write(string)
  540.         self.SendMessageToDebugger(string)
  541.  
  542.  
  543.     def UpdateDebugger(self):
  544.         filename = self.curframe.f_code.co_filename
  545.         self.SetDebugFile(filename,self.curframe.f_lineno)
  546.         self.DebugShowStackTrace()
  547.  
  548.  
  549.  
  550.     def DebugShowStackTrace(self):
  551.         "Pasa informacion sobre la pila al depurador"
  552.         try:
  553.             nEntry=0
  554.             nEntrys=len(self.stack)
  555.             for frame_lineno in self.stack:
  556.                 self.DebugShowStackEntry(frame_lineno,nEntry,nEntrys)
  557.                 #self.print_stack_entry(frame_lineno)
  558.                 nEntry=nEntry+1
  559.         except KeyboardInterrupt:
  560.             pass
  561.     
  562.     def DebugShowStackEntry(self, frame_lineno,nEntry,nEntrys):
  563.         frame, lineno = frame_lineno
  564.         entry=" "
  565.         if frame is self.curframe:
  566.             entry='>'
  567.  
  568.         EntryText=self.DebugFormatStackEntry(frame_lineno, line_prefix)
  569.         entry=entry+EntryText
  570.         string="SetStackEntry;"+entry+";"+frame.f_code.co_filename+";"+str(lineno)+";"+str(nEntry)+";"+str(nEntrys)
  571.         self.SendMessageToDebugger(string)
  572.  
  573.     def DebugFormatStackEntry(self, frame_lineno, lprefix=': '):
  574.         import linecache, repr, string
  575.         frame, lineno = frame_lineno
  576.         filename = frame.f_code.co_filename
  577.         #s = filename + '(' + `lineno` + ')'
  578.         if frame.f_code.co_name:
  579.             s = frame.f_code.co_name
  580.         else:
  581.             s = "<lambda>"
  582.  
  583.         #if frame.f_locals.has_key('__args__'):
  584.         #    args = frame.f_locals['__args__']
  585.         #else:
  586.         #    args = None
  587.         #if args:
  588.         #    s = s + repr.repr(args)
  589.         #else:
  590.         #    s = s + '()'
  591.  
  592.         self.old_stdout.write("Check1")
  593.         fcode=frame.f_code
  594.         fdict=frame.f_locals
  595.         nargs = fcode.co_argcount
  596.         self.old_stdout.write("nargs"+str(nargs))
  597.         if fcode.co_flags & 4:
  598.             nargs = nargs+1
  599.         if fcode.co_flags & 8:
  600.             nargs = nargs+1
  601.         s=s+'('#+str(nargs)
  602.         for iarg in range(nargs):
  603.             argname = fcode.co_varnames[iarg]
  604.             s=s + argname# + '='
  605.         #    if fdict.has_key(argname):
  606.         #        s=s+str(fdict[argname])
  607.         #    else:
  608.         #        s=s+ "*** undefined ***"
  609.             if iarg!=nargs-1:
  610.                 s=s+","
  611.  
  612.         s=s+')'
  613.         #if frame.f_locals.has_key('__return__'):
  614.         #    rv = frame.f_locals['__return__']
  615.         #    s = s + '->'
  616.         #    s = s + repr.repr(rv)
  617.         #line = linecache.getline(filename, lineno)
  618.         #if line: s = s + lprefix + string.strip(line)
  619.         return s
  620.  
  621.  
  622.     def set_break(self, filename, lineno, cond=None):
  623.         print "set_break\n"
  624.  
  625.         if not self.breaks.has_key(filename):
  626.             print "Adding self.breaks[filename] = [],",filename
  627.             self.breaks[filename]=[]
  628.         else:
  629.             print "Has key",filename
  630.  
  631.         print "self.breaks,filename",self.breaks,filename
  632.         list = self.breaks[filename]
  633.         print "list,lineno",list,lineno
  634.         if lineno in list:
  635.             print "Inside if"
  636.             self.clear_break(filename,lineno)
  637.             print "break cleared"
  638.             string="RemoveBreakPoint;"+filename+";"+str(lineno)
  639.             self.SendMessageToDebugger(string)
  640.             return
  641.  
  642.         list.append(lineno)
  643.         if cond is not None:
  644.             self.cbreaks[filename, lineno]=cond
  645.  
  646.         string="SetBreakPoint;"+filename+";"+str(lineno)+";"+str(cond)
  647.         self.SendMessageToDebugger(string)
  648.  
  649.  
  650.     def clear_break(self, filename, lineno):
  651.         print "clear_break called"
  652.         if not self.breaks.has_key(filename):
  653.             print 'There are no breakpoints in that file!'
  654.         print "clear_break: if 1"
  655.         if lineno not in self.breaks[filename]:
  656.             print 'There is no breakpoint there!'
  657.         print "clear_break: if 2"
  658.         self.breaks[filename].remove(lineno)
  659.         print "clear_break: remove"
  660.         if not self.breaks[filename]:
  661.             del self.breaks[filename]
  662.         try:
  663.             del self.cbreaks[filename, lineno]
  664.         except:
  665.             pass
  666.  
  667.  
  668.     def do_BladeBreak(self,arg): # Siempre serßn archivo,n·mero de lφnea
  669.         self.old_stderr.write("\ndo_BladeBreak\n")
  670.         try:
  671.             arg = eval(arg, self.curframe.f_globals,self.curframe.f_locals)
  672.         except:
  673.             print '*** Could not eval argument:', arg
  674.             return
  675.  
  676.         filename,lineno=arg
  677.         str_temp= "BladeBreak ->"+str(filename)+str(lineno)+"\n"
  678.         self.old_stderr.write(str_temp)
  679.         err = self.set_break(filename, lineno, None)
  680.         if err:
  681.             print '*** BladeBreak *** ', err
  682.  
  683.  
  684.  
  685. # Simplified interface
  686.  
  687. def run(statement, globals=None, locals=None):
  688.     Bldb().run(statement, globals, locals)
  689.  
  690. def runeval(expression, globals=None, locals=None):
  691.     return Bldb().runeval(expression, globals, locals)
  692.  
  693. def runctx(statement, globals, locals):
  694.     # B/W compatibility
  695.     run(statement, globals, locals)
  696.  
  697. def runcall(*args):
  698.     return apply(Bldb().runcall, args)
  699.  
  700. def set_trace():
  701.     Bldb().set_trace()
  702.  
  703. # Post-Mortem interface
  704.  
  705. def post_mortem(t):
  706.     p = Bldb()
  707.     p.reset()
  708.     while t.tb_next <> None: t = t.tb_next
  709.     p.interaction(t.tb_frame, t)
  710.  
  711. def pm():
  712.     import sys
  713.     post_mortem(sys.last_traceback)
  714.  
  715.  
  716. # Main program for testing
  717.  
  718. TESTCMD = 'import x; x.main()'
  719.  
  720. def test():
  721.     run(TESTCMD)
  722.  
  723. # print help
  724. def help():
  725.     import os
  726.     for dirname in sys.path:
  727.         fullname = os.path.join(dirname, 'pdb.doc')
  728.         if os.path.exists(fullname):
  729.             sts = os.system('${PAGER-more} '+fullname)
  730.             if sts: print '*** Pager exit status:', sts
  731.             break
  732.     else:
  733.         print 'Sorry, can\'t find the help file "pdb.doc"',
  734.         print 'along the Python search path'
  735.  
  736. # When invoked as main program, invoke the debugger on a script
  737. if __name__=='__main__':
  738.     import sys
  739.     import os
  740.     if not sys.argv[1:]:
  741.         print "usage: pdb.py scriptfile [arg] ..."
  742.         sys.exit(2)
  743.  
  744.     filename = sys.argv[1]    # Get script filename
  745.  
  746.     del sys.argv[0]        # Hide "pdb.py" from argument list
  747.  
  748.     # Insert script directory in front of module search path
  749.     sys.path.insert(0, os.path.dirname(filename))
  750.  
  751.     run('execfile(' + `filename` + ')', {'__name__': '__main__'})
  752.