"""
$URL: svn+ssh://svn.mems-exchange.org/repos/trunk/dulcinea/lib/script_util.py $
$Id: script_util.py 30177 2007-10-19 11:30:16Z dbinger $
"""
import sys, os, pdb


class Debugger(pdb.Pdb):
    """
    Calling the constructor of this class puts you in the
    interactive debugger.  This is like pdb.post_mortem, except
    that the traceback is printed and the exit command works.
    """
    def __init__(self):
        pdb.Pdb.__init__(self)
        (exc_type, exc_value, tb) = sys.exc_info()
        up = 0
        if tb is None:
            try:
                raise
            except:
                (exc_type, exc_value, tb) = sys.exc_info()
            down = 1
        self.reset()
        while tb.tb_next is not None:
            tb = tb.tb_next
        self.interaction(tb.tb_frame, tb)

    def interaction(self, frame, traceback):
        self.setup(frame, traceback)
        self.curindex = self.curindex - 1
        self.curframe = self.stack[self.curindex][0]
        self.lineno = None
        self.do_explain()
        self.cmdloop()
        self.forget()

    def do_explain(self, arg=None):
        print("\n")
        for stack_entry in self.stack[self.curindex-3:-1]:
            self.print_stack_entry(stack_entry)
        print("")
        self.do_args(None)
        print("")
        self.do_list("%s,13" % (self.curframe.f_lineno - 12))

    def help_explain(self):
        print("""
Print a slice of the stack, args to this function, and list the list the
section of code being executed.
""")
    def do_exit(self, arg):
        os._exit(1)

    def help_exit(self):
        print("""Terminate this process.""")

