debug.py 1.63 KB
Newer Older
Julien Muchembled's avatar
Julien Muchembled committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
import errno, os, socket, stat, threading


class Socket(object):

    def __init__(self, socket):
        # In case that the default timeout is not None.
        socket.settimeout(None)
        self._socket = socket
        self._buf = ''

    def close(self):
        self._socket.close()

    def write(self, data):
        self._socket.send(data)

    def readline(self):
        recv = self._socket.recv
        data = self._buf
        while True:
            i = 1 + data.find('\n')
            if i:
                self._buf = data[i:]
                return data[:i]
            d = recv(4096)
            data += d
            if not d:
                self._buf = ''
                return data

    def flush(self):
        pass

    def closed(self):
        self._socket.setblocking(0)
        try:
            self._socket.recv(0)
            return True
        except socket.error, (err, _):
            if err != errno.EAGAIN:
                raise
            self._socket.setblocking(1)
        return False


class Console(object):

    def __init__(self, path, pdb):
        self.path = path
        s = socket.socket(socket.AF_UNIX)
        try:
            self.close()
        except OSError, e:
            if e.errno != errno.ENOENT:
                raise
        s.bind(path)
        s.listen(5)
        def accept():
            t = threading.Thread(target=pdb, args=(Socket(s.accept()[0]),))
            t.daemon = True
            t.start()
        def select(r, w, t):
            r[s] = accept
        self.select = select

    def close(self):
        if stat.S_ISSOCK(os.lstat(self.path).st_mode):
            os.remove(self.path)