Ejemplo n.º 1
0
 def __init__(self, host, port, patch_stdstreams=False):
     listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
     listen_socket.bind((host, port))
     cry("RemotePdb session open at %s:%s, waiting for connection ..." % listen_socket.getsockname())
     listen_socket.listen(1)
     connection, address = listen_socket.accept()
     cry("RemotePdb accepted connection from %s." % repr(address))
     if PY3:
         self.handle = LF2CRLF_FileWrapper(connection.makefile('rw'))
     else:
         self.handle = LF2CRLF_FileWrapper(connection.makefile())
     Pdb.__init__(self, completekey='tab', stdin=self.handle, stdout=self.handle)
     self.backup = []
     if patch_stdstreams:
         for name in (
                 'stderr',
                 'stdout',
                 '__stderr__',
                 '__stdout__',
                 'stdin',
                 '__stdin__',
         ):
             self.backup.append((name, getattr(sys, name)))
             setattr(sys, name, self.handle)
     RemotePdb.active_instance = self
Ejemplo n.º 2
0
 def __init__(self):
     self.stepping = True
     self.command = ''
     self.lineno = 666
     self.calls = []
     self.first = True
     Pdb.__init__(self)
Ejemplo n.º 3
0
    def __init__(self,
                 host=CELERY_RDB_HOST,
                 port=CELERY_RDB_PORT,
                 port_search_limit=100,
                 port_skew=+0,
                 out=sys.stdout):
        self.active = True
        self.out = out

        self._prev_handles = sys.stdin, sys.stdout

        self._sock, this_port = self.get_avail_port(
            host,
            port,
            port_search_limit,
            port_skew,
        )
        self._sock.setblocking(1)
        self._sock.listen(1)
        self.ident = '{0}:{1}'.format(self.me, this_port)
        self.host = host
        self.port = this_port
        self.say(BANNER.format(self=self))

        self._client, address = self._sock.accept()
        self._client.setblocking(1)
        self.remote_addr = ':'.join(str(v) for v in address)
        self.say(SESSION_STARTED.format(self=self))
        self._handle = sys.stdin = sys.stdout = self._client.makefile('rw')
        Pdb.__init__(self,
                     completekey='tab',
                     stdin=self._handle,
                     stdout=self._handle)
Ejemplo n.º 4
0
 def __init__(self, *args, **kwargs):
     Pdb.__init__(self, *args, **kwargs)
     self.botframe = None
     self.quitting = False
     self.stopframe = None
     self.codemap = {}
     self.entered = False
Ejemplo n.º 5
0
def test():
    testfile = "e_2_pdb.pdb"
    a = Pdb(testfile)
    b = a.parser()
    b.assignAtomTypes()
    b.pbc = [20.80, 20.80, 20.80, 90.0, 90.0, 90.0]
    toReaxLammps(b)
Ejemplo n.º 6
0
def pdbIntoRunningThread(tid):
    from pdb import Pdb
    #from IPython.Debugger import Pdb

    pdb = Pdb()
    pdb.reset()

    import threading
    injectEvent = threading.Event()

    def inject_tracefunc(frame, ev, arg):
        injectEvent.set()
        pdb.interaction(frame, None)
        return pdb.trace_dispatch

    sys.settrace(dummytracer)  # set some dummy. required by setTraceOfThread

    # go into loop. in some cases, it doesn't seem to work for some reason...
    while not injectEvent.isSet():
        setTraceOfThread(tid, inject_tracefunc)

        # Wait until we got into the inject_tracefunc.
        # This may be important as there is a chance that some of these
        # objects will get freed before they are used. (Which is probably
        # some other refcounting bug somewhere.)
        injectEvent.wait(1)
Ejemplo n.º 7
0
    def __init__(self,
                 host=CELERY_RDB_HOST,
                 port=CELERY_RDB_PORT,
                 port_search_limit=100,
                 port_skew=+0,
                 out=sys.stdout):
        self.active = True
        self.out = out

        self._prev_handles = sys.stdin, sys.stdout

        self._sock, this_port = self.get_avail_port(host, port,
                                                    port_search_limit,
                                                    port_skew)
        self._sock.listen(1)
        me = "%s:%s" % (self.me, this_port)
        context = self.context = {"me": me, "host": host, "port": this_port}
        self.say("%(me)s: Please telnet %(host)s %(port)s."
                 "  Type `exit` in session to continue." % context)
        self.say("%(me)s: Waiting for client..." % context)

        self._client, address = self._sock.accept()
        context["remote_addr"] = ":".join(map(str, address))
        self.say("%(me)s: In session with %(remote_addr)s" % context)
        self._handle = sys.stdin = sys.stdout = self._client.makefile("rw")
        Pdb.__init__(self,
                     completekey="tab",
                     stdin=self._handle,
                     stdout=self._handle)
Ejemplo n.º 8
0
 def __init__(self, tcbk):
     Pdb.__init__(self)
     self.reset()
     while tcbk.tb_next is not None:
         tcbk = tcbk.tb_next
     self._tcbk = tcbk
     self._histfile = osp.join(os.environ["HOME"], ".pdbhist")
Ejemplo n.º 9
0
 def __init__(self):
     Pdb.__init__(self)
     self.capturing = False
     config = getConfiguration()
     self.to_vim = ProxyToVim(config)
     self.from_vim = ProxyFromVim(config)
     self._textOutput = ''
Ejemplo n.º 10
0
 def __init__(self, host, port, patch_stdstreams=False, quiet=False):
     self._quiet = quiet
     listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
     listen_socket.bind((host, port))
     if not self._quiet:
         cry("RemotePdb session open at %s:%s, waiting for connection ..." %
             listen_socket.getsockname())
     listen_socket.listen(1)
     connection, address = listen_socket.accept()
     if not self._quiet:
         cry("RemotePdb accepted connection from %s." % repr(address))
     self.handle = LF2CRLF_FileWrapper(connection)
     Pdb.__init__(self,
                  completekey='tab',
                  stdin=self.handle,
                  stdout=self.handle)
     self.backup = []
     if patch_stdstreams:
         for name in (
                 'stderr',
                 'stdout',
                 '__stderr__',
                 '__stdout__',
                 'stdin',
                 '__stdin__',
         ):
             self.backup.append((name, getattr(sys, name)))
             setattr(sys, name, self.handle)
     RemotePdb.active_instance = self
Ejemplo n.º 11
0
 def listen(self):
     if not self._quiet:
         cry("RemotePdb session open at %s:%s, "
             "use 'ray debug' to connect..." %
             (self._ip_address, self._listen_socket.getsockname()[1]))
     self._listen_socket.listen(1)
     connection, address = self._listen_socket.accept()
     if not self._quiet:
         cry("RemotePdb accepted connection from %s." % repr(address))
     self.handle = LF2CRLF_FileWrapper(connection)
     Pdb.__init__(self,
                  completekey="tab",
                  stdin=self.handle,
                  stdout=self.handle,
                  skip=["ray.*"])
     self.backup = []
     if self._patch_stdstreams:
         for name in (
                 "stderr",
                 "stdout",
                 "__stderr__",
                 "__stdout__",
                 "stdin",
                 "__stdin__",
         ):
             self.backup.append((name, getattr(sys, name)))
             setattr(sys, name, self.handle)
     RemotePdb.active_instance = self
Ejemplo n.º 12
0
 def __init__(self, host='', port=5555, patch_stdstreams=False):
     """
     :param host: web-UI hostname or IP-address
     :type host: str
     :param port: web-UI port. If ``port=-1``, choose a random port value
         between 32768 and 65536.
     :type port: int
     :param patch_stdstreams: redirect all standard input and output
         streams to the web-UI.
     :type patch_stdstreams: bool
     """
     if port == -1:
         random.seed()
         port = random.randint(32768, 65536)
     self.console = WebConsole(host, port, self)
     Pdb.__init__(self, stdin=self.console, stdout=self.console)
     # Borrowed from here: https://github.com/ionelmc/python-remote-pdb
     self._backup = []
     if patch_stdstreams:
         for name in (
                 'stderr',
                 'stdout',
                 '__stderr__',
                 '__stdout__',
                 'stdin',
                 '__stdin__',
         ):
             self._backup.append((name, getattr(sys, name)))
             setattr(sys, name, self.console)
     WebPdb.active_instance = self
Ejemplo n.º 13
0
def pdbIntoRunningThread(tid):
	from pdb import Pdb
	#from IPython.Debugger import Pdb
	
	pdb = Pdb()
	pdb.reset()
	
	import threading
	injectEvent = threading.Event()
	
	def inject_tracefunc(frame,ev,arg):
		injectEvent.set()
		pdb.interaction(frame, None)
		return pdb.trace_dispatch
	
	sys.settrace(dummytracer) # set some dummy. required by setTraceOfThread

	# go into loop. in some cases, it doesn't seem to work for some reason...
	while not injectEvent.isSet():
		setTraceOfThread(tid, inject_tracefunc)
	
		# Wait until we got into the inject_tracefunc.
		# This may be important as there is a chance that some of these
		# objects will get freed before they are used. (Which is probably
		# some other refcounting bug somewhere.)
		injectEvent.wait(1)
Ejemplo n.º 14
0
 def __init__(self):
     self.stepping = True
     self.command = ''
     self.lineno = 666
     self.calls = []
     self.first = True
     Pdb.__init__(self)
Ejemplo n.º 15
0
 def user_line(self, frame):
     self.calls = []
     for i in self.get_stack(frame, None)[0]:
        name = i[0].f_code.co_name
        if name != '?' and name != 'run':
           self.calls.append([i[0].f_code.co_filename, i[0].f_lineno, name])
     Pdb.user_line(self, frame)
Ejemplo n.º 16
0
 def user_return(self, frame, return_value):
     # print "RETURN"
     name = frame.f_code.co_name
     Pdb.user_return(self, frame, return_value)
     if name != '?':
        import cheney
        cheney.user_return()
Ejemplo n.º 17
0
 def __init__(self, *args, **kwargs):
     Pdb.__init__(self, *args, **kwargs)
     self.botframe = None
     self.quitting = False
     self.stopframe = None
     self.codemap = {}
     self.entered = False
Ejemplo n.º 18
0
    def __init__(self, color_scheme=None, completekey=None, stdin=None, stdout=None, context=5):

        # Parent constructor:
        try:
            self.context = int(context)
            if self.context <= 0:
                raise ValueError("Context must be a positive integer")
        except (TypeError, ValueError):
            raise ValueError("Context must be a positive integer")

        OldPdb.__init__(self, completekey, stdin, stdout)

        # IPython changes...
        self.shell = get_ipython()

        if self.shell is None:
            # No IPython instance running, we must create one
            from IPython.terminal.interactiveshell import TerminalInteractiveShell

            self.shell = TerminalInteractiveShell.instance()

        if color_scheme is not None:
            warnings.warn("The `color_scheme` argument is deprecated since version 5.1", DeprecationWarning)
        else:
            color_scheme = self.shell.colors

        self.aliases = {}

        # Create color table: we copy the default one from the traceback
        # module and add a few attributes needed for debugging
        self.color_scheme_table = exception_colors()

        # shorthands
        C = coloransi.TermColors
        cst = self.color_scheme_table

        cst["NoColor"].colors.prompt = C.NoColor
        cst["NoColor"].colors.breakpoint_enabled = C.NoColor
        cst["NoColor"].colors.breakpoint_disabled = C.NoColor

        cst["Linux"].colors.prompt = C.Green
        cst["Linux"].colors.breakpoint_enabled = C.LightRed
        cst["Linux"].colors.breakpoint_disabled = C.Red

        cst["LightBG"].colors.prompt = C.Blue
        cst["LightBG"].colors.breakpoint_enabled = C.LightRed
        cst["LightBG"].colors.breakpoint_disabled = C.Red

        cst["Neutral"].colors.prompt = C.Blue
        cst["Neutral"].colors.breakpoint_enabled = C.LightRed
        cst["Neutral"].colors.breakpoint_disabled = C.Red

        self.set_colors(color_scheme)

        # Add a python parser so we can syntax highlight source while
        # debugging.
        self.parser = PyColorize.Parser()

        # Set the prompt - the default prompt is '(Pdb)'
        self.prompt = prompt
Ejemplo n.º 19
0
    def __init__(self, host=CELERY_RDB_HOST, port=CELERY_RDB_PORT,
                 port_search_limit=100, port_skew=+0, out=sys.stdout):
        self.active = True
        self.out = out

        self._prev_handles = sys.stdin, sys.stdout

        self._sock, this_port = self.get_avail_port(
            host, port, port_search_limit, port_skew,
        )
        self._sock.setblocking(1)
        self._sock.listen(1)
        me = '%s:%s' % (self.me, this_port)
        context = self.context = {'me': me, 'host': host, 'port': this_port}
        self.say('%(me)s: Please telnet %(host)s %(port)s.'
                 '  Type `exit` in session to continue.' % context)
        self.say('%(me)s: Waiting for client...' % context)

        self._client, address = self._sock.accept()
        self._client.setblocking(1)
        context['remote_addr'] = ':'.join(str(v) for v in address)
        self.say('%(me)s: In session with %(remote_addr)s' % context)
        self._handle = sys.stdin = sys.stdout = self._client.makefile('rw')
        Pdb.__init__(self, completekey='tab',
                     stdin=self._handle, stdout=self._handle)
Ejemplo n.º 20
0
 def do_xquit(self, arg):
     print 'Rpdb(%s:%s) debugger: stoped.' % self.io.addr
     self.debugging = False
     Pdb.clear_all_breaks(self)
     Pdb.set_continue(self)
     self.io.close()
     return True
Ejemplo n.º 21
0
def monte_carlo():
    """ a python shell for Monte Carlo reaxFF simulation'
    """
    welcome()
    mc = MC()
    # read the pdb file
    print("Reading input pdbfile")
    pdbfile = "model.pdb"
    a = Pdb(pdbfile)
    sim = a.parser()
    sim.assignEleTypes()
    sim.assignAtomTypes()
    # read the control file
    read_control(mc)
    # read index file
    indexfile = "index.ndx"
    grp = Group(indexfile)

    # system init
    log = open(mc.log, "w")

    if mc.swap_flag == 1:
        assign_swap_grps(mc, sim, grp)

    print "Starting simulation:"
    for i in range(mc.nsteps):
        print("Running step %d" % i)
        log.write("step %-6d" % i)
        mc_moves(mc, sim, grp, log)
        shutil.copy("out.data", "out.data.%06d" % i)
        shutil.copy("dump.lmp", "dump.lmp.%06d" % i)

    toReaxLammps(sim, "lammps.data.final")
    log.close()
Ejemplo n.º 22
0
def test():
    testfile = "e_2_pdb.pdb"
    a = Pdb(testfile)
    b = a.parser()
    b.assignAtomTypes()
    b.pbc = [20.80, 20.80, 20.80, 90.0, 90.0, 90.0]
    toReaxLammps(b)
Ejemplo n.º 23
0
    def __init__(self,
                 host=CELERY_RDB_HOST,
                 port=CELERY_RDB_PORT,
                 port_search_limit=100,
                 port_skew=+0,
                 out=sys.stdout):
        self.active = True
        self.out = out

        self._prev_handles = sys.stdin, sys.stdout

        self._sock, this_port = self.get_avail_port(host, port,
                                                    port_search_limit,
                                                    port_skew)
        self._sock.listen(1)
        me = '%s:%s' % (self.me, this_port)
        context = self.context = {'me': me, 'host': host, 'port': this_port}
        self.say('%(me)s: Please telnet %(host)s %(port)s.'
                 '  Type `exit` in session to continue.' % context)
        self.say('%(me)s: Waiting for client...' % context)

        self._client, address = self._sock.accept()
        context['remote_addr'] = ':'.join(map(str, address))
        self.say('%(me)s: In session with %(remote_addr)s' % context)
        self._handle = sys.stdin = sys.stdout = self._client.makefile('rw')
        Pdb.__init__(self,
                     completekey='tab',
                     stdin=self._handle,
                     stdout=self._handle)
Ejemplo n.º 24
0
def monte_carlo():
    """ a python shell for Monte Carlo reaxFF simulation'
    """
    welcome()
    mc = MC()
    # read the pdb file
    print("Reading input pdbfile")
    pdbfile = "model.pdb"
    a = Pdb(pdbfile)
    sim = a.parser()
    sim.assignEleTypes()
    sim.assignAtomTypes()
    # read the control file
    read_control(mc)
    # read index file
    indexfile = "index.ndx"
    grp = Group(indexfile)

    # system init
    log = open(mc.log, "w")

    if mc.swap_flag == 1:
        assign_swap_grps(mc, sim, grp)
    
    print "Starting simulation:"
    for i in range(mc.nsteps):
        print("Running step %d"%i)
        log.write("step %-6d"%i)
        mc_moves(mc, sim, grp, log)
        shutil.copy("out.data", "out.data.%06d"%i)
        shutil.copy("dump.lmp", "dump.lmp.%06d"%i)

    toReaxLammps(sim, "lammps.data.final")
    log.close()
Ejemplo n.º 25
0
def withPbc(testfile="supper.pdb", args=''):
    a = Pdb(testfile)
    b = a.parser()
    b.assignAtomTypes()
    b.assignEleTypes()
    b.assignIdNumbers()
    b.toFrac()
    #b.translate(12.0, "z")
    toXyz(b, "out.xyz")
    toMusic(b, "out.music")
    if len(b.pbc) == 0:
        b.geotag = "BIOGRF 200"
    else:
        b.geotag = "XTLGRF 200"
    toReaxLammps(b, "lammps.data")
    toGeo(b, "sim.geo")
    toMsd(b, "sim.msd")
    toPoscar(b, )
    toCfg(b, )
    toJdft(b, )
    toTowheecoords(b)
    if args:
        if args.element:
            toPdb(b, "out.pdb", 1)
    else:
        toPdb(b, "out.pdb")
Ejemplo n.º 26
0
 def user_return(self, frame, return_value):
     # print "RETURN"
     name = frame.f_code.co_name
     Pdb.user_return(self, frame, return_value)
     if name != '?':
         import cheney
         cheney.user_return()
Ejemplo n.º 27
0
    def __init__(self, host=SDB_HOST, port=SDB_PORT,
                 notify_host=SDB_NOTIFY_HOST, context_lines=SDB_CONTEXT_LINES,
                 port_search_limit=100, port_skew=+0, out=sys.stdout,
                 colorize=SDB_COLORIZE):
        self.active = True
        self.out = out
        self.colorize = colorize

        self._prev_handles = sys.stdin, sys.stdout

        self.notify_host = notify_host
        self.context_lines = int(context_lines)
        self._sock, this_port = self.get_avail_port(
            host, port, port_search_limit, port_skew,
        )
        self._sock.setblocking(1)
        self._sock.listen(1)
        self.host = host
        self.port = this_port
        self.ident = '{0}:{1}'.format(self.me, this_port)
        self.say(BANNER.format(self=self))

        self._client, address = self._sock.accept()
        self._client.setblocking(1)
        self.remote_addr = ':'.join(str(v) for v in address)
        self.say(SESSION_STARTED.format(self=self))
        self._handle = sys.stdin = sys.stdout = self._client.makefile('rw')
        Pdb.__init__(self, stdin=self._handle, stdout=self._handle)
        self.prompt = ''
Ejemplo n.º 28
0
 def __init__(self, tcbk):
     Pdb.__init__(self)
     self.reset()
     while tcbk.tb_next is not None:
         tcbk = tcbk.tb_next
     self._tcbk = tcbk
     self._histfile = osp.join(os.environ["HOME"], ".pdbhist")
Ejemplo n.º 29
0
 def do_xquit(self, arg):
     print 'Rpdb(%s:%s) debugger: stoped.' % self.io.addr
     self.debugging = False
     Pdb.clear_all_breaks(self)
     Pdb.set_continue(self)
     self.io.close()
     return True 
Ejemplo n.º 30
0
 def set_trace(self, frame=None):
     if frame is None:
         frame = sys._getframe().f_back
     try:
         Pdb.set_trace(self, frame)
     except IOError as exc:
         if exc.errno != errno.ECONNRESET:
             raise
Ejemplo n.º 31
0
 def set_trace(self, frame=None):
     if frame is None:
         frame = sys._getframe().f_back
     try:
         Pdb.set_trace(self, frame)
     except IOError as exc:
         if exc.errno != errno.ECONNRESET:
             raise
Ejemplo n.º 32
0
 def __init__(self, tcbk=None):
     Pdb.__init__(self)
     self.reset()
     if tcbk:
         while tcbk.tb_next is not None:
             tcbk = tcbk.tb_next
     self._tcbk = tcbk
     self._histfile = os.path.expanduser("~/.pdbhist")
Ejemplo n.º 33
0
 def __init__(self, tcbk=None):
     Pdb.__init__(self)
     self.reset()
     if tcbk:
         while tcbk.tb_next is not None:
             tcbk = tcbk.tb_next
     self._tcbk = tcbk
     self._histfile = os.path.expanduser("~/.pdbhist")
Ejemplo n.º 34
0
    def __init__(self,color_scheme='NoColor',completekey=None,
                 stdin=None, stdout=None, context=5):

        # Parent constructor:
        try:
            self.context=int(context)
            if self.context <= 0:
                raise ValueError("Context must be a positive integer")
        except (TypeError, ValueError):
                raise ValueError("Context must be a positive integer")

        OldPdb.__init__(self,completekey,stdin,stdout)

        # IPython changes...
        self.shell = get_ipython()

        if self.shell is None:
            # No IPython instance running, we must create one
            from IPython.terminal.interactiveshell import \
                TerminalInteractiveShell
            self.shell = TerminalInteractiveShell.instance()

        self.aliases = {}

        # Create color table: we copy the default one from the traceback
        # module and add a few attributes needed for debugging
        self.color_scheme_table = exception_colors()

        # shorthands
        C = coloransi.TermColors
        cst = self.color_scheme_table

        cst['NoColor'].colors.prompt = C.NoColor
        cst['NoColor'].colors.breakpoint_enabled = C.NoColor
        cst['NoColor'].colors.breakpoint_disabled = C.NoColor

        cst['Linux'].colors.prompt = C.Green
        cst['Linux'].colors.breakpoint_enabled = C.LightRed
        cst['Linux'].colors.breakpoint_disabled = C.Red

        cst['LightBG'].colors.prompt = C.Blue
        cst['LightBG'].colors.breakpoint_enabled = C.LightRed
        cst['LightBG'].colors.breakpoint_disabled = C.Red

        self.set_colors(color_scheme)

        # Add a python parser so we can syntax highlight source while
        # debugging.
        self.parser = PyColorize.Parser()

        # Set the prompt - the default prompt is '(Pdb)'
        Colors = cst.active_colors
        if color_scheme == 'NoColor':
            self.prompt = prompt
        else:
            # The colour markers are wrapped by bytes 01 and 02 so that readline
            # can calculate the width.
            self.prompt = u'\x01%s\x02%s\x01%s\x02' % (Colors.prompt, prompt, Colors.Normal)
Ejemplo n.º 35
0
 def set_trace(self, frame=None):
     if frame is None:
         frame = _frame().f_back
     try:
         Pdb.set_trace(self, frame)
     except socket.error as exc:
         # connection reset by peer.
         if exc.errno != errno.ECONNRESET:
             raise
Ejemplo n.º 36
0
Archivo: add.py Proyecto: tarbaig/simpy
def read_pdb(pdbfile):
    """read pdb file
    """

    a = Pdb(pdbfile)
    b = a.parser()
    b.assignAtomTypes()
    b.assignEleTypes()
    return b
Ejemplo n.º 37
0
def test():
    testfile = "test.pdb"
    a = Pdb(testfile)
    b = a.parser()
    atoms = b.atoms
    print atoms[0].x
    b.sortZ()
    atoms = b.atoms
    print atoms[0].x
Ejemplo n.º 38
0
Archivo: rdb.py Proyecto: Rundll/celery
 def set_trace(self, frame=None):
     if frame is None:
         frame = _frame().f_back
     try:
         Pdb.set_trace(self, frame)
     except socket.error, exc:
         # connection reset by peer.
         if exc.errno != errno.ECONNRESET:
             raise
Ejemplo n.º 39
0
    def __init__(self,
                 color_scheme='NoColor',
                 completekey=None,
                 stdin=None,
                 stdout=None,
                 context=5):

        # Parent constructor:
        try:
            self.context = int(context)
            if self.context <= 0:
                raise ValueError("Context must be a positive integer")
        except (TypeError, ValueError):
            raise ValueError("Context must be a positive integer")

        OldPdb.__init__(self, completekey, stdin, stdout)

        # IPython changes...
        self.shell = get_ipython()

        if self.shell is None:
            # No IPython instance running, we must create one
            from IPython.terminal.interactiveshell import \
                TerminalInteractiveShell
            self.shell = TerminalInteractiveShell.instance()

        self.aliases = {}

        # Create color table: we copy the default one from the traceback
        # module and add a few attributes needed for debugging
        self.color_scheme_table = exception_colors()

        # shorthands
        C = coloransi.TermColors
        cst = self.color_scheme_table

        cst['NoColor'].colors.prompt = C.NoColor
        cst['NoColor'].colors.breakpoint_enabled = C.NoColor
        cst['NoColor'].colors.breakpoint_disabled = C.NoColor

        cst['Linux'].colors.prompt = C.Green
        cst['Linux'].colors.breakpoint_enabled = C.LightRed
        cst['Linux'].colors.breakpoint_disabled = C.Red

        cst['LightBG'].colors.prompt = C.Blue
        cst['LightBG'].colors.breakpoint_enabled = C.LightRed
        cst['LightBG'].colors.breakpoint_disabled = C.Red

        self.set_colors(color_scheme)

        # Add a python parser so we can syntax highlight source while
        # debugging.
        self.parser = PyColorize.Parser()

        # Set the prompt - the default prompt is '(Pdb)'
        self.prompt = prompt
Ejemplo n.º 40
0
def read_pdb(control):
    print "    Reading pdb file ..."
    a = Pdb(control.pdbfile)
    b = a.parser()
    b.assignAtomTypes2()
    print "        cell parameters:"
    print "            a = %8.3f: "%b.pbc[0]
    print "            a = %8.3f: "%b.pbc[1]
    print "            a = %8.3f: "%b.pbc[2]
    return b
Ejemplo n.º 41
0
 def user_line(self, frame):
     if not self.first:
         pass
     print "breakpoint in ", frame.f_code.co_filename, "line", frame.f_lineno
     self.calls = []
     for i in self.get_stack(frame, None)[0]:
        name = i[0].f_code.co_name 
        if name != '?' and name != 'run':
           self.calls.append([i[0].f_code.co_filename, i[0].f_lineno, name]) 
     Pdb.user_line(self, frame)
Ejemplo n.º 42
0
 def post_mortem(self, traceback=None):
     # See https://github.com/python/cpython/blob/
     # 022bc7572f061e1d1132a4db9d085b29707701e7/Lib/pdb.py#L1617
     try:
         t = sys.exc_info()[2]
         self.reset()
         Pdb.interaction(self, None, t)
     except IOError as exc:
         if exc.errno != errno.ECONNRESET:
             raise
Ejemplo n.º 43
0
def ddb(rank=0):
    """
    Distributed Debugger that will insert a py debugger on rank `rank` and
    pause all other distributed processes until debugging is complete.
    :param rank:
    """
    if torch.distributed.get_rank() == rank:
        from pdb import Pdb
        pdb = Pdb(skip=["torch.distributed.*"])
        pdb.set_trace(sys._getframe().f_back)
    torch.distributed.barrier()
Ejemplo n.º 44
0
 def set_trace(self, frame=None):
     if self.suspend:
         self.con.acquire()
         try:
             while not self.debugging:
                 self.con.wait()
             self.suspend = False
         finally:
             self.con.release()
     if self.debugging:
         Pdb.set_trace(self, frame=frame)
Ejemplo n.º 45
0
 def set_trace(self, frame=None):
     if self.suspend:
         self.con.acquire()
         try:
             while not self.debugging:
                 self.con.wait()
             self.suspend = False
         finally:
             self.con.release()
     if self.debugging:
         Pdb.set_trace(self, frame=frame)
Ejemplo n.º 46
0
 def user_line(self, frame):
     if not self.first:
         pass
     print "breakpoint in ", frame.f_code.co_filename, "line", frame.f_lineno
     self.calls = []
     for i in self.get_stack(frame, None)[0]:
         name = i[0].f_code.co_name
         if name != '?' and name != 'run':
             self.calls.append(
                 [i[0].f_code.co_filename, i[0].f_lineno, name])
     Pdb.user_line(self, frame)
Ejemplo n.º 47
0
 def __init__(self, endcallback):
     Pdb.__init__(self)
     # completely reinitialize breakpoints since they sometimes seem
     # to get stuck
     Breakpoint.next = 1
     Breakpoint.bplist = {}
     Breakpoint.bpbynumber = [None]
     self._endcallback = endcallback
     # do not display any prompt
     self.prompt = ''
     # get input lines from our fake input stream
     self.stdin = FakeStdin()
Ejemplo n.º 48
0
 def __init__(self, port=8787):
     # pdb server
     self.skt = socket(AF_INET, SOCK_STREAM)
     self.skt.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
     self.skt.bind(('0.0.0.0', port))
     self.skt.listen(1)
     # listen for debugger client
     self.client , self.client_addr = self.skt.accept()
     self.client_io = self.client.makefile('rw')
     print 'Rpdb(%s:%s) debugger: starting.' % self.client_addr
     # init pdb
     Pdb.__init__(self, stdin=self.client_io, stdout=self.client_io)
Ejemplo n.º 49
0
 def __init__(self, port=8787):
     # pdb server
     self.skt = socket(AF_INET, SOCK_STREAM)
     self.skt.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
     self.skt.bind(('0.0.0.0', port))
     self.skt.listen(1)
     # listen for debugger client
     self.client, self.client_addr = self.skt.accept()
     self.client_io = self.client.makefile('rw')
     print 'Rpdb(%s:%s) debugger: starting.' % self.client_addr
     # init pdb
     Pdb.__init__(self, stdin=self.client_io, stdout=self.client_io)
Ejemplo n.º 50
0
    def __init__(self):
        Pdb.__init__(self)
        self.proto = Proto()
        self.c_stdout = self.stdout #crunchy output
        self.stdout =  MyStringIO(self.stdout)  #eat up everything output by orginal pdb
        self.prompt = "" #remove prompt
        self.use_rawinput = 0

        #these name should not be exposed to user (as they are used by pdb)
        self.exclude_name_list = ['__return__', '__exception__']#, '__builtins__']

        self.last_locals = {}
Ejemplo n.º 51
0
 def interaction(self, frame, traceback):
     self.shell.set_completer_frame(frame)
     while True:
         try:
             OldPdb.interaction(self, frame, traceback)
             break
         except KeyboardInterrupt:
             self.shell.write('\n' + self.shell.get_exception_only())
             break
         finally:
             # Pdb sets readline delimiters, so set them back to our own
             if self.shell.readline is not None:
                 self.shell.readline.set_completer_delims(self.shell.readline_delims)
Ejemplo n.º 52
0
 def __init__(self, fn):
     ''' generate a CallTree with the given function '''
     assert callable(
         fn), 'CallTree needs a function as its argument, not {}'.format(fn)
     sio = StringIO()
     p = Pdb(stdout=sio)
     for i in range(512):
         p.cmdqueue.append('s')
     p.cmdqueue.append('q')
     p.runcall(fn)
     sio.seek(0)
     self.target_fn = fn
     self.pdb_text = sio.read()
Ejemplo n.º 53
0
 def __init__(self, port=8787, suspend=True):
     self.con = Condition()
     # pdb server
     self.skt = socket(AF_INET, SOCK_STREAM)
     self.skt.setsockopt(SOL_SOCKET, SO_REUSEADDR, True)
     self.skt.bind(('0.0.0.0', port))
     self.skt.listen(1)
     self._listen()
     # debug io
     self.io = RpdbIO()
     self.debugging = False
     self.suspend = suspend
     # init pdb
     Pdb.__init__(self, stdin=self.io, stdout=self.io)
Ejemplo n.º 54
0
 def __init__(self, port=8787, suspend=True):
     self.con = Condition()
     # pdb server
     self.skt = socket(AF_INET, SOCK_STREAM)
     self.skt.setsockopt(SOL_SOCKET, SO_REUSEADDR, True)
     self.skt.bind(('0.0.0.0', port))
     self.skt.listen(1)
     self._listen()
     # debug io
     self.io = RpdbIO()
     self.debugging = False
     self.suspend = suspend
     # init pdb
     Pdb.__init__(self, stdin=self.io, stdout=self.io)
Ejemplo n.º 55
0
def getBoxl(pdbfile, n, density):

    density = density * 1000
    a = Pdb(pdbfile)
    b = a.parser()
    b.getMass()
    mass = b.mass
    print "Molecule mass: ", mass
    total = mass * n
    vol = total*amc/density * 1e30 # here length is in A
    print "Volume: ", vol
    l = math.pow(vol, 1/3.0)
    print "box a, b, c =", l

    return l
Ejemplo n.º 56
0
def fortranOut(testfile = "output.pdb", args=''):
    a = Pdb(testfile)
    b = a.parser()
    b.assignAtomTypes()
    b.assignEleTypes()
    b.pbc = [50.00, 50.00, 50.00, 90.0, 90.0, 90.0]
    b.geotag = "XTLGRF 200"
    toReaxLammps(b, "lammps.data")
    if args:
        if args.element:
            toPdb(b, "out.pdb", 1)
    else:
        toPdb(b, "out.pdb")
    toMsd(b, "sim.msd")
    toGeo(b, "sim.geo")
Ejemplo n.º 57
0
 def do_list(self, arg):
     """overrides default list command to display the surrounding block
     instead of 5 lines of context
     """
     self.lastcmd = "list"
     if not arg:
         try:
             source, start_lineno = getsource(self.curframe)
             print colorize("".join(source), start_lineno, self.curframe.f_lineno)
         except KeyboardInterrupt:
             pass
         except IOError:
             Pdb.do_list(self, arg)
     else:
         Pdb.do_list(self, arg)
Ejemplo n.º 58
0
def main():
    if len(sys.argv) < 4:
        usage()
    else:
        pdbfile = sys.argv[1]
        n = int(sys.argv[2])
        density = float(sys.argv[3])
        l = getBoxl(pdbfile, n, density)
        writeInp(pdbfile, n, l)
        os.system("packmol < inp")
        if os.path.exists("sim.pdb"):
            os.system("editconf -f sim.pdb -o sim.pdb -box %.4f"%(l/10))
            a = Pdb("sim.pdb")
            b = a.parser()
            b.assignAtomTypes()
            toReaxLammps(b)