我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用select.POLLHUP。
def event_str(event): r = [] if event & select.POLLIN: r.append('IN') if event & select.POLLOUT: r.append('OUT') if event & select.POLLPRI: r.append('PRI') if event & select.POLLERR: r.append('ERR') if event & select.POLLHUP: r.append('HUP') if event & select.POLLNVAL: r.append('NVAL') return ' '.join(r)
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() except _reraised_exceptions: raise except: obj.handle_error()
def read(self, size=1): """Read size bytes from the serial port. If a timeout is set it may return less characters as requested. With no timeout it will block until the requested number of bytes is read.""" if self.fd is None: raise portNotOpenError read = bytearray() poll = select.poll() poll.register(self.fd, select.POLLIN|select.POLLERR|select.POLLHUP|select.POLLNVAL) if size > 0: while len(read) < size: # print "\tread(): size",size, "have", len(read) #debug # wait until device becomes ready to read (or something fails) for fd, event in poll.poll(self._timeout*1000): if event & (select.POLLERR|select.POLLHUP|select.POLLNVAL): raise SerialException('device reports error (poll)') # we don't care if it is select.POLLIN or timeout, that's # handled below buf = os.read(self.fd, size - len(read)) read.extend(buf) if ((self._timeout is not None and self._timeout >= 0) or (self._interCharTimeout is not None and self._interCharTimeout > 0)) and not buf: break # early abort on timeout return bytes(read)
def __init__(self, nmea): self.nmea = nmea self.process = False self.devices = [] nmea.serialprobe.gpsdevices = self.devices self.process = GpsProcess() self.process.start() READ_ONLY = select.POLLIN | select.POLLHUP | select.POLLERR self.poller = select.poll() self.poller.register(self.process.pipe.fileno(), READ_ONLY)
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)
def test_poll2(self): cmd = 'for i in 0 1 2 3 4 5 6 7 8 9; do echo testing...; sleep 1; done' p = os.popen(cmd, 'r') pollster = select.poll() pollster.register( p, select.POLLIN ) for tout in (0, 1000, 2000, 4000, 8000, 16000) + (-1,)*10: fdlist = pollster.poll(tout) if (fdlist == []): continue fd, flags = fdlist[0] if flags & select.POLLHUP: line = p.readline() if line != "": self.fail('error: pipe seems to be closed, but still returns data') continue elif flags & select.POLLIN: line = p.readline() if not line: break continue else: self.fail('Unexpected return value from select.poll: %s' % fdlist) p.close()
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 as e: if e.args[0] not in _DISCONNECTED: obj.handle_error() else: obj.handle_close() except _reraised_exceptions: raise except: obj.handle_error()
def start_loop(self): self.poll = select.poll() self.poll.register(sys.stdin, select.POLLIN | select.POLLHUP | select.POLLPRI) self.poll.register(self.fileno(), select.POLLIN | select.POLLHUP | select.POLLPRI) self.start_of_line = False self.read_escape = False with WINCHHandler(self): try: self.setup_tty() self.run_forever() except socket.error as e: raise exceptions.ConnectionFailed(e) except websocket.WebSocketConnectionClosedException as e: raise exceptions.Disconnected(e) finally: self.restore_tty()
def read(self, size=1): """\ Read size bytes from the serial port. If a timeout is set it may return less characters as requested. With no timeout it will block until the requested number of bytes is read. """ if self.fd is None: raise portNotOpenError read = bytearray() poll = select.poll() poll.register(self.fd, select.POLLIN|select.POLLERR|select.POLLHUP|select.POLLNVAL) if size > 0: while len(read) < size: # print "\tread(): size",size, "have", len(read) #debug # wait until device becomes ready to read (or something fails) for fd, event in poll.poll(self._timeout*1000): if event & (select.POLLERR|select.POLLHUP|select.POLLNVAL): raise SerialException('device reports error (poll)') # we don't care if it is select.POLLIN or timeout, that's # handled below buf = os.read(self.fd, size - len(read)) read.extend(buf) if ((self._timeout is not None and self._timeout >= 0) or (self._interCharTimeout is not None and self._interCharTimeout > 0)) and not buf: break # early abort on timeout return bytes(read)
def __init__(self, server_address): self.server_address = server_address # ?????IP??? self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # ??TCP??socket self.__setblock = False # ?????????? self.message_queue = {} # ?????? self.rlist = (select.POLLIN or select.POLLHUP or select.POLLPRI or select.POLLERR) # ???? self.wlist = (self.rlist or select.POLLOUT) # ???? self.fd_socket = {} # ??????????socket???? self.poll = select.poll() # ???????? self.logger = logging.getLogger(__name__) # ?????? if self.output_console: self.console_handler = logging.StreamHandler() # ??????????? if self.logfile: # ???????,???????? self.file_handler = logging.FileHandler(filename=self.logfile, encoding=self.encoding) # ???????? self.set_log() # ???? self.bind() # ????IP???
def __init__(self, server_address): """?????,socket??? :param server_address: :return: """ self.server_address = server_address # ?????IP??? self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # ??TCP??socket self.__setblock = False # ?????????? self.message_queue = {} # ?????? self.rlist = (select.POLLIN or select.POLLHUP or select.POLLPRI or select.POLLERR) # ???? self.wlist = (self.rlist or select.POLLOUT) # ???? self.fd_socket = {} # ??????????socket???? self.poll = select.poll() # ???????? self.logger = logging.getLogger(__name__) # ?????? if self.output_console: self.console_handler = logging.StreamHandler() # ??????????? if self.logfile: # ???????,???????? self.file_handler = logging.FileHandler(filename=self.logfile, encoding=self.encoding) # ???????? self.set_log() # ???? self.bind() # ????IP???
def __init__(self, server_address): self.server_address = server_address # ?????IP??? self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # ??TCP??socket self.message_queue = {} # ?????? self.rlist = (select.POLLIN or select.POLLHUP or select.POLLPRI or select.POLLERR) # ???? self.wlist = (self.rlist or select.POLLOUT) # ???? self.fd_socket = {} # ??????????socket???? self.poll = select.poll() # ???????? self.logger = logging.getLogger(__name__) # ?????? if self.output_console: self.console_handler = logging.StreamHandler() # ??????????? if self.logfile: # ???????,???????? self.file_handler = logging.FileHandler(filename=self.logfile, encoding=self.encoding) # ???????? self.set_log() # ???? self.connect_server() self.is_send = None # ????????,????None,???????????
def __init__(self, server_address): self.server_address = server_address # ?????IP??? self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # ??TCP??socket self.message_queue = {} # ?????? self.rlist = (select.POLLIN or select.POLLHUP or select.POLLPRI or select.POLLERR) # ???? self.wlist = (self.rlist or select.POLLOUT) # ???? self.fd_socket = {} # ??????????socket???? self.poll = select.poll() # ???????? self.logger = logging.getLogger(__name__) # ?????? if self.output_console: self.console_handler = logging.StreamHandler() # ??????????? if self.logfile: # ???????,???????? self.file_handler = logging.FileHandler(filename=self.logfile, encoding=self.encoding) # ???????? self.set_log() # ???? self.connect_server() self.is_send = None # ????????,????None,??????????? self.local_file = None self.remote_file = None
def events_from_poll(events): ret = 0 if events & select.POLLIN: ret |= libvirt.VIR_EVENT_HANDLE_READABLE if events & select.POLLOUT: ret |= libvirt.VIR_EVENT_HANDLE_WRITABLE if events & select.POLLNVAL: ret |= libvirt.VIR_EVENT_HANDLE_ERROR if events & select.POLLERR: ret |= libvirt.VIR_EVENT_HANDLE_ERROR if events & select.POLLHUP: ret |= libvirt.VIR_EVENT_HANDLE_HANGUP return ret ########################################################################### # Now glue an instance of the general event loop into libvirt's event loop ########################################################################### # This single global instance of the event loop wil be used for # monitoring libvirt events
def poll(self, timeout=None): """Performs a poll and dispatches the resulting events.""" if not self.readmap and not self.writemap: return try: event_list = self._poller.poll(timeout) except select.error: _, e, _ = sys.exc_info() errno = e.args[0] if errno == EINTR: return else: raise for fd, event in event_list: if event & (select.POLLIN | select.POLLHUP): handler = self.readmap[fd] handler(fd, self) if event & (select.POLLOUT | select.POLLERR): handler = self.writemap[fd] handler(fd, self)
def one_poll_loop(self): if self.futures: for (fd, ev) in self.poll.poll(1): future = self.futures[fd] if ev & select.POLLOUT: if not future.writable(): self.poll.modify(fd, select.POLLIN) if ev & select.POLLIN: if not future.readable(): self.unregister(fd) if ev & (select.POLLERR | select.POLLHUP): self.unregister(fd) for fd, future in self.futures.items(): if future.ready(): self.unregister(fd)
def poll(self, timeout): if timeout is not None: # convert from seconds to milliseconds timeout *= 1000 changes = self._poll.poll(timeout) results = [] for fd, events in changes: f = self._get_file_object(fd) if events & (select.POLLIN | select.POLLPRI): results.append((f, POLLER_EVENT_READ)) elif events & (select.POLLOUT): results.append((f, POLLER_EVENT_WRITE)) elif events & (select.POLLHUP): results.append((f, POLLER_EVENT_HUP)) elif events & (select.POLLERR | select.POLLNVAL): results.append((f, POLLER_EVENT_ERROR)) return results
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 OSError as e: if e.args[0] not in _DISCONNECTED: obj.handle_error() else: obj.handle_close() except _reraised_exceptions: raise except: obj.handle_error()
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)
def PollSockets(self): events = self.poller.poll(0) while events: event = events.pop() fd, flag = event socket = self.fd_to_socket[fd] if socket == self.server_socket: connection, address = socket.accept() if len(self.sockets) == max_connections: print 'max connections reached!!!', len(self.sockets) self.RemoveSocket(self.sockets[0]) # dump first socket?? socket = LineBufferedNonBlockingSocket(connection) self.sockets.append(socket) fd = socket.socket.fileno() # print 'new client', address, fd self.fd_to_socket[fd] = socket self.poller.register(fd, select.POLLIN) elif flag & (select.POLLHUP | select.POLLERR | select.POLLNVAL): self.RemoveSocket(socket) elif flag & select.POLLIN: if not socket.recv(): self.RemoveSocket(socket) while True: line = socket.readline() if not line: break try: self.HandleRequest(socket, line) except: print 'invalid request from socket', line socket.send('invalid request: ' + line + '\n') # flush all sockets for socket in self.sockets: socket.flush()
def run(self): poll = select.poll() poll.register(self._read_fd, select.POLLIN | select.POLLPRI | select.POLLHUP) poll.register(self._quit_pipe, select.POLLHUP) reader = LineReader() def process_line(readbytes): reader.append(readbytes) line = reader.readline() if line is None: return if self._next_flag.is_set(): self._lines.put(line) self._next_flag.clear() reader.skiplines() self._processed.set() while True: events = poll.poll() if not events: continue for e in events: fd, ev = e[0], e[1] if fd == self._quit_pipe and (ev & select.POLLHUP) != 0: # quit return elif fd == self._read_fd and (ev & (select.POLLIN | select.POLLPRI)) != 0: # there are some data readbytes = os.read(fd, 1024) if not readbytes: # EOF return process_line(readbytes) elif fd == self._read_fd and (ev & select.POLLHUP) != 0: # read_fd closed return else: self.log(msg)
def connect(self, timeout=None, optimist=False): if timeout != None: limit = time.time() + timeout while True: if timeout != None and time.time() > limit: raise ConnectionTimeout('connection attempt timed out') try: Connection.connect(self) except ConnectionInProgress: if timeout == None: events = self.poll(select.POLLOUT, -1) else: events = self.poll(select.POLLOUT, timeout) if not events: raise ConnectionTimeout('connection attempt timed out') if events[0][1] & (select.POLLERR | select.POLLHUP): if optimist: time.sleep(0.1) continue raise ConnectionRefused() if events[0][1] & select.POLLOUT: e = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if e == errno.ECONNREFUSED: raise ConnectionRefused() return return # good
def accept(self, timeout=None): if timeout == None: timeout = -1 events = self.poll(select.POLLIN | errmask, timeout) if not events: raise ConnectionTimeout('nothing to accept') if events[0][1] & (select.POLLHUP | select.POLLERR): raise ConnectionClosed('error condition on socket') return Connection.accept(self, Class=BlockingConnection)
def register(self, fd): ''' Register a file decriptor with the spool. ''' if not self.fds: self.fds = select.poll() mask = ( select.POLLERR | select.POLLHUP | select.POLLNVAL | select.POLLIN | select.POLLPRI ) self.fds.register(fd, mask)