Python select.POLLIN Examples

The following are 30 code examples of select.POLLIN(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module select , or try the search function .
Example #1
Source File: poll.py    From multibootusb with GNU General Public License v2.0 6 votes vote down vote up
def _parse_events(self, events):
        """Parse ``events``.

        ``events`` is a list of events as returned by
        :meth:`select.poll.poll()`.

        Yield all parsed events.

        """
        for fd, event_mask in events:
            if self._has_event(event_mask, select.POLLNVAL):
                raise IOError('File descriptor not open: {0!r}'.format(fd))
            elif self._has_event(event_mask, select.POLLERR):
                raise IOError('Error while polling fd: {0!r}'.format(fd))

            if self._has_event(event_mask, select.POLLIN):
                yield fd, 'r'
            if self._has_event(event_mask, select.POLLOUT):
                yield fd, 'w'
            if self._has_event(event_mask, select.POLLHUP):
                yield fd, 'h' 
Example #2
Source File: wsgi_server.py    From browserscope with Apache License 2.0 6 votes vote down vote up
def _select(self):
    with self._lock:
      fds = self._file_descriptors
      fd_to_callback = self._file_descriptor_to_callback
    if fds:
      if _HAS_POLL:
        # With 100 file descriptors, it is approximately 5x slower to
        # recreate and reinitialize the Poll object on every call to _select
        # rather reuse one. But the absolute cost of contruction,
        # initialization and calling poll(0) is ~25us so code simplicity
        # wins.
        poll = select.poll()
        for fd in fds:
          poll.register(fd, select.POLLIN)
        ready_file_descriptors = [fd for fd, _ in poll.poll(1)]
      else:
        ready_file_descriptors, _, _ = select.select(fds, [], [], 1)
      for fd in ready_file_descriptors:
        fd_to_callback[fd]()
    else:
      # select([], [], [], 1) is not supported on Windows.
      time.sleep(1) 
Example #3
Source File: selectors.py    From jbox with MIT License 6 votes vote down vote up
def select(self, timeout=None):
            if timeout is None:
                timeout = None
            elif timeout <= 0:
                timeout = 0
            else:
                # poll() has a resolution of 1 millisecond, round away from
                # zero to wait *at least* timeout seconds.
                timeout = int(math.ceil(timeout * 1e3))
            ready = []
            try:
                fd_event_list = wrap_error(self._poll.poll, timeout)
            except InterruptedError:
                return ready
            for fd, event in fd_event_list:
                events = 0
                if event & ~select.POLLIN:
                    events |= EVENT_WRITE
                if event & ~select.POLLOUT:
                    events |= EVENT_READ

                key = self._key_from_fd(fd)
                if key:
                    ready.append((key, events & key.events))
            return ready 
Example #4
Source File: selectors.py    From jbox with MIT License 6 votes vote down vote up
def select(self, timeout=None):
            if timeout is None:
                timeout = None
            elif timeout <= 0:
                timeout = 0
            else:
                # devpoll() has a resolution of 1 millisecond, round away from
                # zero to wait *at least* timeout seconds.
                timeout = math.ceil(timeout * 1e3)
            ready = []
            try:
                fd_event_list = self._devpoll.poll(timeout)
            except InterruptedError:
                return ready
            for fd, event in fd_event_list:
                events = 0
                if event & ~select.POLLIN:
                    events |= EVENT_WRITE
                if event & ~select.POLLOUT:
                    events |= EVENT_READ

                key = self._key_from_fd(fd)
                if key:
                    ready.append((key, events & key.events))
            return ready 
Example #5
Source File: wait.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def poll_wait_for_socket(sock, read=False, write=False, timeout=None):
    if not read and not write:
        raise RuntimeError("must specify at least one of read=True, write=True")
    mask = 0
    if read:
        mask |= select.POLLIN
    if write:
        mask |= select.POLLOUT
    poll_obj = select.poll()
    poll_obj.register(sock, mask)

    # For some reason, poll() takes timeout in milliseconds
    def do_poll(t):
        if t is not None:
            t *= 1000
        return poll_obj.poll(t)

    return bool(_retry_on_intr(do_poll, timeout)) 
Example #6
Source File: virtio_console_guest.py    From avocado-vt with GNU General Public License v2.0 6 votes vote down vote up
def worker(virt):
    """
    Worker thread (infinite) loop of virtio_guest.
    """
    global exiting
    print("PASS: Daemon start.")
    p = select.poll()
    p.register(sys.stdin.fileno())
    while not exiting:
        d = p.poll()
        if (d[0][1] == select.POLLIN):
            out = input()
            try:
                exec(out)
            except Exception:
                exc_type, exc_value, exc_traceback = sys.exc_info()
                print("On Guest exception from: \n" + "".join(
                    traceback.format_exception(exc_type,
                                               exc_value,
                                               exc_traceback)))
                print("FAIL: Guest command exception.")
        elif (d[0][1] & select.POLLHUP):
            time.sleep(0.5) 
Example #7
Source File: virtio_console_guest.py    From avocado-vt with GNU General Public License v2.0 6 votes vote down vote up
def pollmask_to_str(mask):
        """
        Conver pool mast to string

        :param mask: poll return mask
        """
        out = ""
        if (mask & select.POLLIN):
            out += "IN "
        if (mask & select.POLLPRI):
            out += "PRI IN "
        if (mask & select.POLLOUT):
            out += "OUT "
        if (mask & select.POLLERR):
            out += "ERR "
        if (mask & select.POLLHUP):
            out += "HUP "
        if (mask & select.POLLMSG):
            out += "MSG "
        return out 
Example #8
Source File: wait.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def poll_wait_for_socket(sock, read=False, write=False, timeout=None):
    if not read and not write:
        raise RuntimeError("must specify at least one of read=True, write=True")
    mask = 0
    if read:
        mask |= select.POLLIN
    if write:
        mask |= select.POLLOUT
    poll_obj = select.poll()
    poll_obj.register(sock, mask)

    # For some reason, poll() takes timeout in milliseconds
    def do_poll(t):
        if t is not None:
            t *= 1000
        return poll_obj.poll(t)

    return bool(_retry_on_intr(do_poll, timeout)) 
Example #9
Source File: wait.py    From gist-alfred with MIT License 6 votes vote down vote up
def poll_wait_for_socket(sock, read=False, write=False, timeout=None):
    if not read and not write:
        raise RuntimeError("must specify at least one of read=True, write=True")
    mask = 0
    if read:
        mask |= select.POLLIN
    if write:
        mask |= select.POLLOUT
    poll_obj = select.poll()
    poll_obj.register(sock, mask)

    # For some reason, poll() takes timeout in milliseconds
    def do_poll(t):
        if t is not None:
            t *= 1000
        return poll_obj.poll(t)

    return bool(_retry_on_intr(do_poll, timeout)) 
Example #10
Source File: test_poll.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_poll_blocks_with_negative_ms(self):
        for timeout_ms in [None, -1000, -1, -1.0]:
            # Create two file descriptors. This will be used to unlock
            # the blocking call to poll.poll inside the thread
            r, w = os.pipe()
            pollster = select.poll()
            pollster.register(r, select.POLLIN)

            poll_thread = threading.Thread(target=pollster.poll, args=(timeout_ms,))
            poll_thread.start()
            poll_thread.join(timeout=0.1)
            self.assertTrue(poll_thread.is_alive())

            # Write to the pipe so pollster.poll unblocks and the thread ends.
            os.write(w, b'spam')
            poll_thread.join()
            self.assertFalse(poll_thread.is_alive())
            os.close(r)
            os.close(w) 
Example #11
Source File: CLIManager.py    From rtp_cluster with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def run(self):
        #print(self.run, 'enter')
        while True:
            #print(self.run, 'cycle')
            pollret = dict(self.pollobj.poll()).get(self.fileno, 0)
            if pollret & POLLNVAL != 0:
                break
            if pollret & POLLIN == 0:
                continue
            try:
                clientsock, addr = self.clicm.serversock.accept()
            except Exception as why:
                if isinstance(why, socket.error):
                    if why.errno == ECONNABORTED:
                        continue
                    elif why.errno == EBADF:
                        break
                    else:
                        raise
                dump_exception('CLIConnectionManager: unhandled exception when accepting incoming connection')
                break
            #print(self.run, 'handle_accept')
            ED2.callFromThread(self.clicm.handle_accept, clientsock, addr)
        self.clicm = None
        #print(self.run, 'exit') 
Example #12
Source File: wait.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def poll_wait_for_socket(sock, read=False, write=False, timeout=None):
    if not read and not write:
        raise RuntimeError("must specify at least one of read=True, write=True")
    mask = 0
    if read:
        mask |= select.POLLIN
    if write:
        mask |= select.POLLOUT
    poll_obj = select.poll()
    poll_obj.register(sock, mask)

    # For some reason, poll() takes timeout in milliseconds
    def do_poll(t):
        if t is not None:
            t *= 1000
        return poll_obj.poll(t)

    return bool(_retry_on_intr(do_poll, timeout)) 
Example #13
Source File: selectors.py    From Python24 with MIT License 5 votes vote down vote up
def register(self, fileobj, events, data=None):
            key = super(PollSelector, self).register(fileobj, events, data)
            event_mask = 0
            if events & EVENT_READ:
                event_mask |= select.POLLIN
            if events & EVENT_WRITE:
                event_mask |= select.POLLOUT
            self._poll.register(key.fd, event_mask)
            return key 
Example #14
Source File: selectors.py    From wow-addon-updater with GNU General Public License v3.0 5 votes vote down vote up
def select(self, timeout=None):
            ready = []
            fd_events = _syscall_wrapper(self._wrap_poll, True, timeout=timeout)
            for fd, event_mask in fd_events:
                events = 0
                if event_mask & ~select.POLLIN:
                    events |= EVENT_WRITE
                if event_mask & ~select.POLLOUT:
                    events |= EVENT_READ

                key = self._key_from_fd(fd)
                if key:
                    ready.append((key, events & key.events))

            return ready 
Example #15
Source File: selectors.py    From wow-addon-updater with GNU General Public License v3.0 5 votes vote down vote up
def register(self, fileobj, events, data=None):
            key = super(PollSelector, self).register(fileobj, events, data)
            event_mask = 0
            if events & EVENT_READ:
                event_mask |= select.POLLIN
            if events & EVENT_WRITE:
                event_mask |= select.POLLOUT
            self._poll.register(key.fd, event_mask)
            return key 
Example #16
Source File: selectors.py    From FuYiSpider with Apache License 2.0 5 votes vote down vote up
def select(self, timeout=None):
            ready = []
            fd_events = _syscall_wrapper(self._wrap_poll, True, timeout=timeout)
            for fd, event_mask in fd_events:
                events = 0
                if event_mask & ~select.POLLIN:
                    events |= EVENT_WRITE
                if event_mask & ~select.POLLOUT:
                    events |= EVENT_READ

                key = self._key_from_fd(fd)
                if key:
                    ready.append((key, events & key.events))

            return ready 
Example #17
Source File: selectors.py    From FuYiSpider with Apache License 2.0 5 votes vote down vote up
def register(self, fileobj, events, data=None):
            key = super(PollSelector, self).register(fileobj, events, data)
            event_mask = 0
            if events & EVENT_READ:
                event_mask |= select.POLLIN
            if events & EVENT_WRITE:
                event_mask |= select.POLLOUT
            self._poll.register(key.fd, event_mask)
            return key 
Example #18
Source File: selectors.py    From FuYiSpider with Apache License 2.0 5 votes vote down vote up
def select(self, timeout=None):
            ready = []
            fd_events = _syscall_wrapper(self._wrap_poll, True, timeout=timeout)
            for fd, event_mask in fd_events:
                events = 0
                if event_mask & ~select.POLLIN:
                    events |= EVENT_WRITE
                if event_mask & ~select.POLLOUT:
                    events |= EVENT_READ

                key = self._key_from_fd(fd)
                if key:
                    ready.append((key, events & key.events))

            return ready 
Example #19
Source File: selectors.py    From FuYiSpider with Apache License 2.0 5 votes vote down vote up
def register(self, fileobj, events, data=None):
            key = super(PollSelector, self).register(fileobj, events, data)
            event_mask = 0
            if events & EVENT_READ:
                event_mask |= select.POLLIN
            if events & EVENT_WRITE:
                event_mask |= select.POLLOUT
            self._poll.register(key.fd, event_mask)
            return key 
Example #20
Source File: asyncore.py    From BinderFilter with MIT License 5 votes vote down vote up
def readwrite(obj, flags):
    try:
        if flags & select.POLLIN:
            obj.handle_read_event()
        if flags & select.POLLOUT:
            obj.handle_write_event()
        if flags & select.POLLPRI:
            obj.handle_expt_event()
        if flags & (select.POLLHUP | select.POLLERR | select.POLLNVAL):
            obj.handle_close()
    except socket.error, e:
        if e.args[0] not in _DISCONNECTED:
            obj.handle_error()
        else:
            obj.handle_close() 
Example #21
Source File: connection.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def is_connection_dropped(conn):  # Platform-specific
    """
    Returns True if the connection is dropped and should be closed.

    :param conn:
        :class:`httplib.HTTPConnection` object.

    Note: For platforms like AppEngine, this will always return ``False`` to
    let the platform handle connection recycling transparently for us.
    """
    sock = getattr(conn, 'sock', False)
    if sock is False:  # Platform-specific: AppEngine
        return False
    if sock is None:  # Connection already closed (such as by httplib).
        return True

    if not poll:
        if not select:  # Platform-specific: AppEngine
            return False

        try:
            return select([sock], [], [], 0.0)[0]
        except socket.error:
            return True

    # This version is better on platforms that support it.
    p = poll()
    p.register(sock, POLLIN)
    for (fno, ev) in p.poll(0.0):
        if fno == sock.fileno():
            # Either data is buffered (bad), or the connection is dropped.
            return True


# This function is copied from socket.py in the Python 2.7 standard
# library test suite. Added to its signature is only `socket_options`. 
Example #22
Source File: selectors.py    From faces with GNU General Public License v2.0 5 votes vote down vote up
def select(self, timeout=None):
            ready = []
            fd_events = _syscall_wrapper(self._wrap_poll, True, timeout=timeout)
            for fd, event_mask in fd_events:
                events = 0
                if event_mask & ~select.POLLIN:
                    events |= EVENT_WRITE
                if event_mask & ~select.POLLOUT:
                    events |= EVENT_READ

                key = self._key_from_fd(fd)
                if key:
                    ready.append((key, events & key.events))

            return ready 
Example #23
Source File: selectors.py    From Python24 with MIT License 5 votes vote down vote up
def select(self, timeout=None):
            ready = []
            fd_events = _syscall_wrapper(self._wrap_poll, True, timeout=timeout)
            for fd, event_mask in fd_events:
                events = 0
                if event_mask & ~select.POLLIN:
                    events |= EVENT_WRITE
                if event_mask & ~select.POLLOUT:
                    events |= EVENT_READ

                key = self._key_from_fd(fd)
                if key:
                    ready.append((key, events & key.events))

            return ready 
Example #24
Source File: test_poll.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_threaded_poll(self):
        r, w = os.pipe()
        self.addCleanup(os.close, r)
        self.addCleanup(os.close, w)
        rfds = []
        for i in range(10):
            fd = os.dup(r)
            self.addCleanup(os.close, fd)
            rfds.append(fd)
        pollster = select.poll()
        for fd in rfds:
            pollster.register(fd, select.POLLIN)

        t = threading.Thread(target=pollster.poll)
        t.start()
        try:
            time.sleep(0.5)
            # trigger ufds array reallocation
            for fd in rfds:
                pollster.unregister(fd)
            pollster.register(w, select.POLLOUT)
            self.assertRaises(RuntimeError, pollster.poll)
        finally:
            # and make the call to poll() from the thread return
            os.write(w, b'spam')
            t.join() 
Example #25
Source File: connection.py    From SalesforceXyTools with Apache License 2.0 5 votes vote down vote up
def is_connection_dropped(conn):  # Platform-specific
    """
    Returns True if the connection is dropped and should be closed.

    :param conn:
        :class:`httplib.HTTPConnection` object.

    Note: For platforms like AppEngine, this will always return ``False`` to
    let the platform handle connection recycling transparently for us.
    """
    sock = getattr(conn, 'sock', False)
    if sock is False:  # Platform-specific: AppEngine
        return False
    if sock is None:  # Connection already closed (such as by httplib).
        return True

    if not poll:
        if not select:  # Platform-specific: AppEngine
            return False

        try:
            return select([sock], [], [], 0.0)[0]
        except socket.error:
            return True

    # This version is better on platforms that support it.
    p = poll()
    p.register(sock, POLLIN)
    for (fno, ev) in p.poll(0.0):
        if fno == sock.fileno():
            # Either data is buffered (bad), or the connection is dropped.
            return True


# This function is copied from socket.py in the Python 2.7 standard
# library test suite. Added to its signature is only `socket_options`. 
Example #26
Source File: remote_runner.py    From avocado-vt with GNU General Public License v2.0 5 votes vote down vote up
def sort_fds_event(fds):
    hup = [x[0] for x in fds if x[1] & select.POLLHUP]
    read = [x[0] for x in fds if x[1] & select.POLLIN]
    write = [x[0] for x in fds if x[1] & select.POLLOUT]
    return hup, read, write 
Example #27
Source File: virtio_console_guest.py    From avocado-vt with GNU General Public License v2.0 5 votes vote down vote up
def _poll_mode(self):
            """
            Read and write to device in polling mode.
            """

            pi = select.poll()
            po = select.poll()

            for fd in self.in_files:
                pi.register(fd, select.POLLIN)

            for fd in self.out_files:
                po.register(fd, select.POLLOUT)

            while not self.exit_thread.isSet():
                data = b""
                t_out = self.out_files

                readyf = pi.poll(1.0)
                for i in readyf:
                    data += os.read(i[0], self.cachesize)

                if data != b"":
                    while ((len(t_out) != len(readyf)) and not
                           self.exit_thread.isSet()):
                        readyf = po.poll(1.0)
                    for desc in t_out:
                        os.write(desc, data) 
Example #28
Source File: poll.py    From rb with Apache License 2.0 5 votes vote down vote up
def poll(self, timeout=None):
        rv = []
        for fd, event in self.pollobj.poll(timeout):
            obj = self.fd_to_object[fd]
            if event & select.POLLIN:
                rv.append((obj, 'read'))
            if event & select.POLLOUT:
                rv.append((obj, 'write'))
            if event & select.POLLHUP:
                rv.append((obj, 'close'))
        return rv 
Example #29
Source File: poll.py    From rb with Apache License 2.0 5 votes vote down vote up
def register(self, key, f):
        BasePoller.register(self, key, f)
        self.pollobj.register(f.fileno(), select.POLLIN | select.POLLOUT |
                              select.POLLHUP)
        self.fd_to_object[f.fileno()] = f 
Example #30
Source File: connection.py    From lambda-chef-node-cleanup with Apache License 2.0 5 votes vote down vote up
def is_connection_dropped(conn):  # Platform-specific
    """
    Returns True if the connection is dropped and should be closed.

    :param conn:
        :class:`httplib.HTTPConnection` object.

    Note: For platforms like AppEngine, this will always return ``False`` to
    let the platform handle connection recycling transparently for us.
    """
    sock = getattr(conn, 'sock', False)
    if sock is False:  # Platform-specific: AppEngine
        return False
    if sock is None:  # Connection already closed (such as by httplib).
        return True

    if not poll:
        if not select:  # Platform-specific: AppEngine
            return False

        try:
            return select([sock], [], [], 0.0)[0]
        except socket.error:
            return True

    # This version is better on platforms that support it.
    p = poll()
    p.register(sock, POLLIN)
    for (fno, ev) in p.poll(0.0):
        if fno == sock.fileno():
            # Either data is buffered (bad), or the connection is dropped.
            return True


# This function is copied from socket.py in the Python 2.7 standard
# library test suite. Added to its signature is only `socket_options`.