Python select 模块,poll() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用select.poll()

项目:googletranslate.popclipext    作者:wizyoung    | 项目源码 | 文件源码
def _can_allocate(struct):
    """ Checks that select structs can be allocated by the underlying
    operating system, not just advertised by the select module. We don't
    check select() because we'll be hopeful that most platforms that
    don't have it available will not advertise it. (ie: GAE) """
    try:
        # select.poll() objects won't fail until used.
        if struct == 'poll':
            p = select.poll()
            p.poll(0)

        # All others will fail on allocation.
        else:
            getattr(select, struct)().close()
        return True
    except (OSError, AttributeError) as e:
        return False


# Choose the best implementation, roughly:
# kqueue == epoll > poll > select. Devpoll not supported. (See above)
# select() also can't accept a FD > FD_SETSIZE (usually around 1024)
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def _can_allocate(struct):
    """ Checks that select structs can be allocated by the underlying
    operating system, not just advertised by the select module. We don't
    check select() because we'll be hopeful that most platforms that
    don't have it available will not advertise it. (ie: GAE) """
    try:
        # select.poll() objects won't fail until used.
        if struct == 'poll':
            p = select.poll()
            p.poll(0)

        # All others will fail on allocation.
        else:
            getattr(select, struct)().close()
        return True
    except (OSError, AttributeError) as e:
        return False


# Choose the best implementation, roughly:
# kqueue == epoll > poll > select. Devpoll not supported. (See above)
# select() also can't accept a FD > FD_SETSIZE (usually around 1024)
项目:pip-update-requirements    作者:alanhamlett    | 项目源码 | 文件源码
def _can_allocate(struct):
    """ Checks that select structs can be allocated by the underlying
    operating system, not just advertised by the select module. We don't
    check select() because we'll be hopeful that most platforms that
    don't have it available will not advertise it. (ie: GAE) """
    try:
        # select.poll() objects won't fail until used.
        if struct == 'poll':
            p = select.poll()
            p.poll(0)

        # All others will fail on allocation.
        else:
            getattr(select, struct)().close()
        return True
    except (OSError, AttributeError) as e:
        return False


# Choose the best implementation, roughly:
# kqueue == epoll > poll > select. Devpoll not supported. (See above)
# select() also can't accept a FD > FD_SETSIZE (usually around 1024)
项目:pypilot    作者:pypilot    | 项目源码 | 文件源码
def receive_line(self, timeout = 0):
        line = self.socket.readline()
        if line:
            try:
                msg = kjson.loads(line.rstrip())
            except:
                raise Exception('invalid message from server:', line)
            return msg

        if timeout < 0:
            return False

        t = time.time()
        try:
            if not self.poll(timeout):
                return False
        except ConnectionLost:
            self.disconnected()
        dt = time.time()-t
        return self.receive_line(timeout - dt)
项目:pypilot    作者:pypilot    | 项目源码 | 文件源码
def flush(self):
        if not self.out_buffer:
            return
        try:
            if not self.pollout.poll(0):
                if sendfail_cnt >= sendfail_msg:
                    print 'signalk socket failed to send', sendfail_cnt
                    self.sendfail_msg *= 10
                self.sendfail_cnt += 1
                return
            t0 = time.time()
            count = self.socket.send(self.out_buffer)
            t1 = time.time()
            if t1-t0 > .1:
                print 'socket send took too long!?!?', t1-t0
            if count < 0:
                print 'socket send error', count
                self.socket.close()
            self.out_buffer = self.out_buffer[count:]
        except:
            self.socket.close()
项目:pypilot    作者:pypilot    | 项目源码 | 文件源码
def HandleRequests(self):
      if not self.init:
          try:
              self.server_socket.bind(('0.0.0.0', self.port))
          except:
              print 'signalk_server: bind failed, try again.'
              time.sleep(1)
              return

          self.server_socket.listen(5)
          self.init = True
          self.fd_to_socket = {self.server_socket.fileno() : self.server_socket}
          self.poller = select.poll()
          self.poller.register(self.server_socket, select.POLLIN)

      t1 = time.time()
      if t1 >= self.persistent_timeout:
          self.StorePersistentValues()
          if time.time() - t1 > .1:
              print 'persistent store took too long!', time.time() - t1
              return

      self.PollSockets()
项目:pypilot    作者:pypilot    | 项目源码 | 文件源码
def initialize(self):
        cnt = 0
        data = False
        while self.flags & ServoFlags.OVERCURRENT or \
          not self.flags & ServoFlags.SYNC:
            self.stop()
            if self.poll():
                data = True

            time.sleep(.001)
            cnt+=1
            if cnt == 400 and not data:
                return False
            if cnt == 1000:
                return False
        return True
项目:jira_worklog_scanner    作者:pgarneau    | 项目源码 | 文件源码
def _can_allocate(struct):
    """ Checks that select structs can be allocated by the underlying
    operating system, not just advertised by the select module. We don't
    check select() because we'll be hopeful that most platforms that
    don't have it available will not advertise it. (ie: GAE) """
    try:
        # select.poll() objects won't fail until used.
        if struct == 'poll':
            p = select.poll()
            p.poll(0)

        # All others will fail on allocation.
        else:
            getattr(select, struct)().close()
        return True
    except (OSError, AttributeError) as e:
        return False


# Choose the best implementation, roughly:
# kqueue == epoll > poll > select. Devpoll not supported. (See above)
# select() also can't accept a FD > FD_SETSIZE (usually around 1024)
项目:ave    作者:sonyxperiadev    | 项目源码 | 文件源码
def once(self):
        # check if there is a request to get and clear accumulated logs
        msg = self._recv(timeout=0)
        if msg == 'get':
             self._send(self.log_buf.getvalue())
             self.log_buf = StringIO()

        # is there new logcat output to read?
        if not self.poller.poll(500): # millisecond timeout
            return

        # read logcat output and store it in a buffer, optionally to file too
        log = os.read(self.cmd_fd, 1000)
        if self.log_file:
            self.log_file.write(log)
            self.log_file.flush()
        if self.log_buf.tell() > LOGBUF_MAXSIZE:
            self.log_buf = StringIO() # start over to avoid OOM
        self.log_buf.write(log)
项目:ave    作者:sonyxperiadev    | 项目源码 | 文件源码
def once(self):
        # check if there is a request to get and clear accumulated logs
        msg = self._recv(timeout=0)
        if msg == 'get':
             self._send(self.log_buf.getvalue())
             self.log_buf = StringIO()

        # is there new logcat output to read?
        if not self.poller.poll(500): # millisecond timeout
            return

        # read logcat output and store it in a buffer, optionally to file too
        log = os.read(self.cmd_fd, 1000)
        if self.log_file:
            self.log_file.write(log)
            self.log_file.flush()
        if self.log_buf.tell() > LOGBUF_MAXSIZE:
            self.log_buf = StringIO() # start over to avoid OOM
        self.log_buf.write(log)
项目:ave    作者:sonyxperiadev    | 项目源码 | 文件源码
def t4():
    pretty = '%s t4' % __file__
    print(pretty)

    pid, fd = ave.cmd.run_bg('echo hello')
    poller  = select.poll()
    poller.register(fd, select.POLLIN)
    events  = poller.poll(1000) # milliseconds
    tmp     = ''
    for e in events:
        if not (e[1] & select.POLLIN):
            print('FAIL %s: unexpected poll event: %d' % (pretty, e[1]))
            os.kill(pid, signal.SIGKILL)
        tmp += os.read(fd, 1024)
    if not tmp.startswith('hello'):
        print('FAIL %s: wrong result: "%s"' % (pretty, tmp))

    os.kill(pid, signal.SIGKILL)
    os.waitpid(pid, 0)
    return True

# check that return value from executed program is correct
项目:ave    作者:sonyxperiadev    | 项目源码 | 文件源码
def write(self, payload, timeout=None):
        size  = len(payload)
        done  = 0
        limit = None
        if timeout != None: # first and last test of 'timeout'
            limit = time.time() + timeout
        while done < size:
            try:
                done += Connection.write(self, payload[done:])
            except ConnectionAgain:
                if limit:
                    timeout == limit - time.time()
                else:
                    timeout = -1
                events = self.poll(select.POLLOUT, timeout)
                if not events:
                    raise ConnectionTimeout('write attempt timed out')
                if events[0][1] & (select.POLLHUP | select.POLLERR):
                    raise ConnectionClosed(
                        'write attempt failed with %d at %d %f'
                        % (events[0][1], done, timeout)
                    )
                if events[0][1] & select.POLLOUT:
                    continue
                raise Exception('unknown events: %s' % events)
项目:ave    作者:sonyxperiadev    | 项目源码 | 文件源码
def read(self, size, timeout=None):
        if timeout != None:
            limit = time.time() + timeout
        payload = ''
        while len(payload) < size:
            if timeout != None:
                events = self.poll(select.POLLIN, max(0, limit - time.time()))
            else:
                events = self.poll(select.POLLIN, -1)
            if not events:
                raise ConnectionTimeout()
            if events[0][1] & ERRMASK:
                raise ConnectionReset()
            tmp = os.read(self.r, size)
            if not tmp:
                raise ConnectionClosed()
            payload += tmp
        return tmp
项目:ave    作者:sonyxperiadev    | 项目源码 | 文件源码
def write(self, payload, timeout=None):
        size  = len(payload)
        done  = 0
        limit = None
        if timeout != None: # first and last test of 'timeout'
            limit = time.time() + timeout
        while done < size:
            try:
                done += Connection.write(self, payload[done:])
            except ConnectionAgain:
                if limit:
                    timeout == limit - time.time()
                else:
                    timeout = -1
                events = self.poll(select.POLLOUT, timeout)
                if not events:
                    raise ConnectionTimeout('write attempt timed out')
                if events[0][1] & (select.POLLHUP | select.POLLERR):
                    raise ConnectionClosed(
                        'write attempt failed with %d at %d %f'
                        % (events[0][1], done, timeout)
                    )
                if events[0][1] & select.POLLOUT:
                    continue
                raise Exception('unknown events: %s' % events)
项目:ave    作者:sonyxperiadev    | 项目源码 | 文件源码
def read(self, size, timeout=None):
        if timeout != None:
            limit = time.time() + timeout
        payload = ''
        while len(payload) < size:
            if timeout != None:
                events = self.poll(select.POLLIN, max(0, limit - time.time()))
            else:
                events = self.poll(select.POLLIN, -1)
            if not events:
                raise ConnectionTimeout()
            if events[0][1] & ERRMASK:
                raise ConnectionReset()
            tmp = os.read(self.r, size)
            if not tmp:
                raise ConnectionClosed()
            payload += tmp
        return tmp
项目:workflows.kyoyue    作者:wizyoung    | 项目源码 | 文件源码
def _can_allocate(struct):
    """ Checks that select structs can be allocated by the underlying
    operating system, not just advertised by the select module. We don't
    check select() because we'll be hopeful that most platforms that
    don't have it available will not advertise it. (ie: GAE) """
    try:
        # select.poll() objects won't fail until used.
        if struct == 'poll':
            p = select.poll()
            p.poll(0)

        # All others will fail on allocation.
        else:
            getattr(select, struct)().close()
        return True
    except (OSError, AttributeError) as e:
        return False


# Choose the best implementation, roughly:
# kqueue == epoll > poll > select. Devpoll not supported. (See above)
# select() also can't accept a FD > FD_SETSIZE (usually around 1024)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def __init__(self, host=None, port=0,
                 timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
        """Constructor.

        When called without arguments, create an unconnected instance.
        With a hostname argument, it connects the instance; port number
        and timeout are optional.
        """
        self.debuglevel = DEBUGLEVEL
        self.host = host
        self.port = port
        self.timeout = timeout
        self.sock = None
        self.rawq = ''
        self.irawq = 0
        self.cookedq = ''
        self.eof = 0
        self.iacseq = '' # Buffer for IAC sequence.
        self.sb = 0 # flag for SB and SE sequence.
        self.sbdataq = ''
        self.option_callback = None
        self._has_poll = hasattr(select, 'poll')
        if host is not None:
            self.open(host, port, timeout)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def loop(timeout=30.0, use_poll=False, map=None, count=None):
    if map is None:
        map = socket_map

    if use_poll and hasattr(select, 'poll'):
        poll_fun = poll2
    else:
        poll_fun = poll

    if count is None:
        while map:
            poll_fun(timeout, map)

    else:
        while map and count > 0:
            poll_fun(timeout, map)
            count = count - 1
项目:annotated-py-asyncio    作者:hhstore    | 项目源码 | 文件源码
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 = math.ceil(timeout * 1e3)
            ready = []
            try:
                fd_event_list = 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
项目:annotated-py-asyncio    作者:hhstore    | 项目源码 | 文件源码
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
项目:harbour-sailfinder    作者:DylanVanAssche    | 项目源码 | 文件源码
def select(self, timeout=None):
            if timeout is not None:
                if timeout <= 0:
                    timeout = 0.0
                else:
                    # select.epoll.poll() has a resolution of 1 millisecond
                    # but luckily takes seconds so we don't need a wrapper
                    # like PollSelector. Just for better rounding.
                    timeout = math.ceil(timeout * 1e3) * 1e-3
                timeout = float(timeout)
            else:
                timeout = -1.0  # epoll.poll() must have a float.

            # We always want at least 1 to ensure that select can be called
            # with no file descriptors registered. Otherwise will fail.
            max_events = max(len(self._fd_to_key), 1)

            ready = []
            fd_events = _syscall_wrapper(self._epoll.poll, True,
                                         timeout=timeout,
                                         maxevents=max_events)
            for fd, event_mask in fd_events:
                events = 0
                if event_mask & ~select.EPOLLIN:
                    events |= EVENT_WRITE
                if event_mask & ~select.EPOLLOUT:
                    events |= EVENT_READ

                key = self._key_from_fd(fd)
                if key:
                    ready.append((key, events & key.events))
            return ready
项目:wiicop    作者:barnabuskev    | 项目源码 | 文件源码
def __init__ (self,bb,cal_mod,BB_X,BB_Y):
        threading.Thread.__init__(self)
        self.runflag = True
        self.storeflag = False
        self.n_s = 4
        self.bbdev = xwiimote.iface(bb.sys_path)
        self.p = select.poll()
        self.p.register(self.bbdev.get_fd(), select.POLLIN)
        # open bb device
        self.bbdev.open(xwiimote.IFACE_BALANCE_BOARD)
        # create xwiimote event structure
        self.revt = xwiimote.event()
        # create numpy array to store data from board
        self.tmp_dat = np.empty((1,self.n_s))
        self.cop = np.empty((1,2))
        self.cop_dat = np.empty((0,2))
        self.cal_mod = cal_mod
        self.BB_X = BB_X
        self.BB_Y = BB_Y
项目:wow-addon-updater    作者:kuhnerdm    | 项目源码 | 文件源码
def _can_allocate(struct):
    """ Checks that select structs can be allocated by the underlying
    operating system, not just advertised by the select module. We don't
    check select() because we'll be hopeful that most platforms that
    don't have it available will not advertise it. (ie: GAE) """
    try:
        # select.poll() objects won't fail until used.
        if struct == 'poll':
            p = select.poll()
            p.poll(0)

        # All others will fail on allocation.
        else:
            getattr(select, struct)().close()
        return True
    except (OSError, AttributeError) as e:
        return False


# Choose the best implementation, roughly:
# kqueue == epoll > poll > select. Devpoll not supported. (See above)
# select() also can't accept a FD > FD_SETSIZE (usually around 1024)
项目:infraview    作者:a-dekker    | 项目源码 | 文件源码
def _can_allocate(struct):
    """ Checks that select structs can be allocated by the underlying
    operating system, not just advertised by the select module. We don't
    check select() because we'll be hopeful that most platforms that
    don't have it available will not advertise it. (ie: GAE) """
    try:
        # select.poll() objects won't fail until used.
        if struct == 'poll':
            p = select.poll()
            p.poll(0)

        # All others will fail on allocation.
        else:
            getattr(select, struct)().close()
        return True
    except (OSError, AttributeError) as e:
        return False


# Choose the best implementation, roughly:
# kqueue == epoll > poll > select. Devpoll not supported. (See above)
# select() also can't accept a FD > FD_SETSIZE (usually around 1024)
项目:krafters    作者:GianlucaBortoli    | 项目源码 | 文件源码
def poll(self, timeout):
        rlist, wlist, xlist = select.select(list(self.__descrsRead),
                                            list(self.__descrsWrite),
                                            list(self.__descrsError),
                                            timeout)

        allDescrs = set(rlist + wlist + xlist)
        rlist = set(rlist)
        wlist = set(wlist)
        xlist = set(xlist)
        for descr in allDescrs:
            event = 0
            if descr in rlist:
                event |= POLL_EVENT_TYPE.READ
            if descr in wlist:
                event |= POLL_EVENT_TYPE.WRITE
            if descr in xlist:
                event |= POLL_EVENT_TYPE.ERROR
            self.__descrToCallbacks[descr](descr, event)
项目:pycos    作者:pgiri    | 项目源码 | 文件源码
def __init__(self, iocp_notifier):
                self._poller_name = 'select'
                self._fds = {}
                self._events = {}
                self._terminate = False
                self.rset = set()
                self.wset = set()
                self.xset = set()
                self.iocp_notifier = iocp_notifier
                self.cmd_rsock, self.cmd_wsock = _AsyncPoller._socketpair()
                self.cmd_rsock.setblocking(0)
                self.cmd_wsock.setblocking(0)
                self.poller = select.select
                self._polling = False
                self._lock = threading.RLock()
                self.poll_thread = threading.Thread(target=self.poll)
                self.poll_thread.daemon = True
                self.poll_thread.start()
项目:pycos    作者:pgiri    | 项目源码 | 文件源码
def poll(self, timeout):
            rlist, wlist, xlist = self.poller(self.rset, self.wset, self.xset, timeout)
            events = {}
            for fid in rlist:
                events[fid] = _AsyncPoller._Read
            for fid in wlist:
                events[fid] = events.get(fid, 0) | _AsyncPoller._Write
            for fid in xlist:
                events[fid] = events.get(fid, 0) | _AsyncPoller._Error

            return events.iteritems()
项目:pycos    作者:pgiri    | 项目源码 | 文件源码
def __init__(self, iocp_notifier):
                self._poller_name = 'select'
                self._fds = {}
                self._events = {}
                self._terminate = False
                self.rset = set()
                self.wset = set()
                self.xset = set()
                self.iocp_notifier = iocp_notifier
                self.cmd_rsock, self.cmd_wsock = _AsyncPoller._socketpair()
                self.cmd_rsock.setblocking(0)
                self.cmd_wsock.setblocking(0)
                self.poller = select.select
                self._polling = False
                self._lock = threading.RLock()
                self.poll_thread = threading.Thread(target=self.poll)
                self.poll_thread.daemon = True
                self.poll_thread.start()
项目:pycos    作者:pgiri    | 项目源码 | 文件源码
def poll(self, timeout):
            kevents = self.poller.control(None, 500, timeout)
            events = [(kevent.ident,
                       _AsyncPoller._Read if kevent.filter == select.KQ_FILTER_READ else
                       _AsyncPoller._Write if kevent.filter == select.KQ_FILTER_WRITE else
                       _AsyncPoller._Hangup if kevent.flags == select.KQ_EV_EOF else
                       _AsyncPoller._Error if kevent.flags == select.KQ_EV_ERROR else 0)
                      for kevent in kevents]
            return events
项目:pycos    作者:pgiri    | 项目源码 | 文件源码
def poll(self, timeout):
            rlist, wlist, xlist = self.poller(self.rset, self.wset, self.xset, timeout)
            events = {}
            for fid in rlist:
                events[fid] = _AsyncPoller._Read
            for fid in wlist:
                events[fid] = events.get(fid, 0) | _AsyncPoller._Write
            for fid in xlist:
                events[fid] = events.get(fid, 0) | _AsyncPoller._Error

            return events.items()
项目:python-    作者:secondtonone1    | 项目源码 | 文件源码
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`.
# One additional modification is that we avoid binding to IPv6 servers
# discovered in DNS if the system doesn't have IPv6 functionality.
项目:sipxecs-voicemail-transcription    作者:andrewsauder    | 项目源码 | 文件源码
def __init__(self , sockstr , protocol , opts=0 , listenq=50 , 
            sockChmod=0o666):
        self.sock = None
        self.opts = opts
        self.protocol = protocol
        self.listenq = int(listenq)
        self.sockChmod = sockChmod
        self.sockStr = sockstr
        self.poll = select.poll()
        self.emask = select.POLLIN | select.POLLPRI
        self.regLock = threading.Lock()
        self.sockMap = {}
        self.protoMap = {}
        self._close = threading.Event()
    # }}}

    # runAccepts() {{{
项目:sipxecs-voicemail-transcription    作者:andrewsauder    | 项目源码 | 文件源码
def register(self , sock , proto):
        fileno = sock.fileno()
        self.regLock.acquire()
        self.sockMap[fileno] = sock
        self.protoMap[fileno] = proto
        self.poll.register(fileno , self.emask)
        self.regLock.release()
    # }}}

    # unregister() {{{
项目:sipxecs-voicemail-transcription    作者:andrewsauder    | 项目源码 | 文件源码
def unregister(self , fileno):
        self.regLock.acquire()
        self.poll.unregister(fileno)
        del self.sockMap[fileno]
        del self.protoMap[fileno]
        self.regLock.release()
    # }}}

    # run() {{{
项目:sipxecs-voicemail-transcription    作者:andrewsauder    | 项目源码 | 文件源码
def close(self):
        self._close.set()
        for i , s in list(self.sockMap.items()):
            self.poll.unregister(i)
            s.close()
            del self.sockMap[i]
        for i , p in list(self.protoMap.items()):
            p.connectionLost()
            del self.protoMap[i]
        self.sock.close()
    # }}}
# }}}

# class ThreadFactory {{{
项目:my-first-blog    作者:AnkurBegining    | 项目源码 | 文件源码
def __init__(self):
            super(PollSelector, self).__init__()
            self._poll = select.poll()
项目:my-first-blog    作者:AnkurBegining    | 项目源码 | 文件源码
def _wrap_poll(self, timeout=None):
            """ Wrapper function for select.poll.poll() so that
            _syscall_wrapper can work with only seconds. """
            if timeout is not None:
                if timeout <= 0:
                    timeout = 0
                else:
                    # select.poll.poll() has a resolution of 1 millisecond,
                    # round away from zero to wait *at least* timeout seconds.
                    timeout = math.ceil(timeout * 1e3)

            result = self._poll.poll(timeout)
            return result
项目:my-first-blog    作者:AnkurBegining    | 项目源码 | 文件源码
def select(self, timeout=None):
            if timeout is not None:
                if timeout <= 0:
                    timeout = 0.0
                else:
                    # select.epoll.poll() has a resolution of 1 millisecond
                    # but luckily takes seconds so we don't need a wrapper
                    # like PollSelector. Just for better rounding.
                    timeout = math.ceil(timeout * 1e3) * 1e-3
                timeout = float(timeout)
            else:
                timeout = -1.0  # epoll.poll() must have a float.

            # We always want at least 1 to ensure that select can be called
            # with no file descriptors registered. Otherwise will fail.
            max_events = max(len(self._fd_to_key), 1)

            ready = []
            fd_events = _syscall_wrapper(self._epoll.poll, True,
                                         timeout=timeout,
                                         maxevents=max_events)
            for fd, event_mask in fd_events:
                events = 0
                if event_mask & ~select.EPOLLIN:
                    events |= EVENT_WRITE
                if event_mask & ~select.EPOLLOUT:
                    events |= EVENT_READ

                key = self._key_from_fd(fd)
                if key:
                    ready.append((key, events & key.events))
            return ready
项目:my-first-blog    作者:AnkurBegining    | 项目源码 | 文件源码
def _can_allocate(struct):
    """ Checks that select structs can be allocated by the underlying
    operating system, not just advertised by the select module. We don't
    check select() because we'll be hopeful that most platforms that
    don't have it available will not advertise it. (ie: GAE) """
    try:
        # select.poll() objects won't fail until used.
        if struct == 'poll':
            p = select.poll()
            p.poll(0)

        # All others will fail on allocation.
        else:
            getattr(select, struct)().close()
        return True
    except (OSError, AttributeError) as e:
        return False


# Choose the best implementation, roughly:
# kqueue == epoll > poll > select. Devpoll not supported. (See above)
# select() also can't accept a FD > FD_SETSIZE (usually around 1024)
项目:my-first-blog    作者:AnkurBegining    | 项目源码 | 文件源码
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`.
# One additional modification is that we avoid binding to IPv6 servers
# discovered in DNS if the system doesn't have IPv6 functionality.
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
def check_output(*popenargs, **kwargs):
    r"""Run command with arguments and return its output as a byte string.

    If the exit code was non-zero it raises a CalledProcessError.  The
    CalledProcessError object will have the return code in the returncode
    attribute and output in the output attribute.

    The arguments are the same as for the Popen constructor.  Example:

    >>> check_output(["ls", "-l", "/dev/null"])
    'crw-rw-rw- 1 root root 1, 3 Oct 18  2007 /dev/null\n'

    The stdout argument is not allowed as it is used internally.
    To capture standard error in the result, use stderr=STDOUT.

    >>> check_output(["/bin/sh", "-c",
    ...               "ls -l non_existent_file ; exit 0"],
    ...              stderr=STDOUT)
    'ls: non_existent_file: No such file or directory\n'
    """
    if 'stdout' in kwargs:
        raise ValueError('stdout argument not allowed, it will be overridden.')
    process = Popen(stdout=PIPE, *popenargs, **kwargs)
    output, unused_err = process.communicate()
    retcode = process.poll()
    if retcode:
        cmd = kwargs.get("args")
        if cmd is None:
            cmd = popenargs[0]
        raise CalledProcessError(retcode, cmd, output=output)
    return output
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
def poll(self):
        return self._internal_poll()
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
def poll2(timeout=0.0, map=None):
    # Use the poll() support added to the select module in Python 2.0
    if map is None:
        map = socket_map
    if timeout is not None:
        # timeout is in milliseconds
        timeout = int(timeout*1000)
    pollster = select.poll()
    if map:
        for fd, obj in map.items():
            flags = 0
            if obj.readable():
                flags |= select.POLLIN | select.POLLPRI
            if obj.writable():
                flags |= select.POLLOUT
            if flags:
                # Only check for exceptions if object was either readable
                # or writable.
                flags |= select.POLLERR | select.POLLHUP | select.POLLNVAL
                pollster.register(fd, flags)
        try:
            r = pollster.poll(timeout)
        except select.error, err:
            if err.args[0] != EINTR:
                raise
            r = []
        for fd, flags in r:
            obj = map.get(fd)
            if obj is None:
                continue
            readwrite(obj, flags)
项目:googletranslate.popclipext    作者:wizyoung    | 项目源码 | 文件源码
def __init__(self):
            super(PollSelector, self).__init__()
            self._poll = select.poll()
项目:googletranslate.popclipext    作者:wizyoung    | 项目源码 | 文件源码
def _wrap_poll(self, timeout=None):
            """ Wrapper function for select.poll.poll() so that
            _syscall_wrapper can work with only seconds. """
            if timeout is not None:
                if timeout <= 0:
                    timeout = 0
                else:
                    # select.poll.poll() has a resolution of 1 millisecond,
                    # round away from zero to wait *at least* timeout seconds.
                    timeout = math.ceil(timeout * 1e3)

            result = self._poll.poll(timeout)
            return result
项目:googletranslate.popclipext    作者:wizyoung    | 项目源码 | 文件源码
def select(self, timeout=None):
            if timeout is not None:
                if timeout <= 0:
                    timeout = 0.0
                else:
                    # select.epoll.poll() has a resolution of 1 millisecond
                    # but luckily takes seconds so we don't need a wrapper
                    # like PollSelector. Just for better rounding.
                    timeout = math.ceil(timeout * 1e3) * 1e-3
                timeout = float(timeout)
            else:
                timeout = -1.0  # epoll.poll() must have a float.

            # We always want at least 1 to ensure that select can be called
            # with no file descriptors registered. Otherwise will fail.
            max_events = max(len(self._fd_to_key), 1)

            ready = []
            fd_events = _syscall_wrapper(self._epoll.poll, True,
                                         timeout=timeout,
                                         maxevents=max_events)
            for fd, event_mask in fd_events:
                events = 0
                if event_mask & ~select.EPOLLIN:
                    events |= EVENT_WRITE
                if event_mask & ~select.EPOLLOUT:
                    events |= EVENT_READ

                key = self._key_from_fd(fd)
                if key:
                    ready.append((key, events & key.events))
            return ready
项目:pscheduler    作者:perfsonar    | 项目源码 | 文件源码
def returncode(self):
        self.process.poll()
        return self.process.returncode
项目:pscheduler    作者:perfsonar    | 项目源码 | 文件源码
def running(self):
        self.process.poll()
        return self.process.returncode is None
项目:mongodb-monitoring    作者:jruaux    | 项目源码 | 文件源码
def socket_closed(sock):
    """Return True if we know socket has been closed, False otherwise.
    """
    try:
        if _HAS_POLL:
            _poller.register(sock, _EVENT_MASK)
            rd = _poller.poll(0)
            _poller.unregister(sock)
        else:
            rd, _, _ = select.select([sock], [], [], 0)
    # Any exception here is equally bad (select.error, ValueError, etc.).
    except:
        return True
    return len(rd) > 0
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def __init__(self):
            super(PollSelector, self).__init__()
            self._poll = select.poll()