我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用select.POLLPRI。
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 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 __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 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 list(map.items()): flags = 0 if obj.readable(): flags |= select.POLLIN | select.POLLPRI # accepting sockets should not be writable if obj.writable() and not obj.accepting: flags |= select.POLLOUT if flags: pollster.register(fd, flags) r = pollster.poll(timeout) for fd, flags in r: obj = map.get(fd) if obj is None: continue readwrite(obj, flags)
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() {{{
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 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 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)
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 # accepting sockets should not be writable if obj.writable() and not obj.accepting: 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 _generate_lists(self): self._pool_in = [ fd for fd, events in self._events.iteritems() if events & Poller.POLLIN ] self._pool_out = [ fd for fd, events in self._events.iteritems() if events & Poller.POLLOUT ] self._pool_pri = [ fd for fd, events in self._events.iteritems() if events & Poller.POLLPRI ]
def poll(self, timeout=0.01): inn, out, pri = select.select( self._pool_in, self._pool_out, self._pool_pri, timeout ) for fd in inn: self._callbacks.get(fd, DO_NOTHING)(fd, Poller.POLLIN) for fd in out: self._callbacks.get(fd, DO_NOTHING)(fd, Poller.POLLOUT) for fd in pri: self._callbacks.get(fd, DO_NOTHING)(fd, Poller.POLLPRI)
def __init__(self, ifname): self.ifname = ifname self.poll = select.epoll() self.sock = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(pnet.ETH_P_ALL)) self.poll.register(self.sock, select.POLLIN | select.POLLPRI | select.POLLHUP | select.POLLERR) attach_filter(self.sock, bootp_filter()) self.sock.setblocking(0) self.sock.bind((ifname, 3)) ifreq = get_ifreq(self.sock, ifname) self.src = pnet.HWAddress(ifreq[18:24])
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 list(map.items()): flags = 0 if obj.readable(): flags |= select.POLLIN | select.POLLPRI # accepting sockets should not be writable if obj.writable() and not obj.accepting: 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 as 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 initialize(self): self._poller = select.poll() self.READ = select.POLLIN | select.POLLPRI | select.POLLHUP self.readables_fd_map = {}
def _readline(self, timeout=0): if not self.proc: return None p = select.poll() flag_err = select.POLLERR | select.POLLHUP rfile = self.proc.stdout p.register(rfile, flag_err | select.POLLIN | select.POLLPRI) buf = StringIO.StringIO() while self.playing: lst = p.poll(timeout) if not lst: line = buf.getvalue() buf.close() self.log.debug("Time out!: %r" % line) return line for fd, flags in lst: if flags & flag_err: self.log.debug("Error reading MPlayer: %s, flags=%x" % (fd, flags)) self.emit("error", "Problems reading MPlayer output") return None c = rfile.read(1) buf.write(c) if c == "\n" or c == "\r": line = buf.getvalue() buf.close() return line # _readline()
def hasMorePollPri(fd): p = epoll() p.register(fd, select.POLLPRI | select.POLLERR) r = p.poll(0) return (fd in r)
def register_read(self, f): self._register(f, select.POLLIN | select.POLLPRI)
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 list(map.items()): flags = 0 if obj.readable(): flags |= select.POLLIN | select.POLLPRI # accepting sockets should not be writable if obj.writable() and not obj.accepting: flags |= select.POLLOUT if flags: pollster.register(fd, flags) try: r = pollster.poll(timeout) except InterruptedError: r = [] for fd, flags in r: obj = map.get(fd) if obj is None: continue readwrite(obj, flags)
def register(self, fd, eventmask=None): """Register a file descriptor with the fake polling object.""" if eventmask is None: eventmask = (select_lib.POLLIN | select_lib.POLLOUT | select_lib.POLLPRI) self.poll_events[fd] = eventmask
def __init__(self): self.timeout_multiplier = 1 if hasattr(select, 'epoll'): self._poller_name = 'epoll' self._poller = select.epoll() _AsyncPoller._Read = select.EPOLLIN | select.EPOLLPRI _AsyncPoller._Write = select.EPOLLOUT _AsyncPoller._Hangup = select.EPOLLHUP _AsyncPoller._Error = select.EPOLLERR _AsyncPoller._Block = -1 elif hasattr(select, 'kqueue'): self._poller_name = 'kqueue' self._poller = _KQueueNotifier() # kqueue filter values are negative numbers so using # them as flags won't work, so define them as necessary _AsyncPoller._Read = 0x01 _AsyncPoller._Write = 0x02 _AsyncPoller._Hangup = 0x04 _AsyncPoller._Error = 0x08 _AsyncPoller._Block = None elif hasattr(select, 'devpoll'): self._poller_name = 'devpoll' self._poller = select.devpoll() _AsyncPoller._Read = select.POLLIN | select.POLLPRI _AsyncPoller._Write = select.POLLOUT _AsyncPoller._Hangup = select.POLLHUP _AsyncPoller._Error = select.POLLERR _AsyncPoller._Block = -1 self.timeout_multiplier = 1000 elif hasattr(select, 'poll'): self._poller_name = 'poll' self._poller = select.poll() _AsyncPoller._Read = select.POLLIN | select.POLLPRI _AsyncPoller._Write = select.POLLOUT _AsyncPoller._Hangup = select.POLLHUP _AsyncPoller._Error = select.POLLERR _AsyncPoller._Block = -1 self.timeout_multiplier = 1000 else: self._poller_name = 'select' self._poller = _SelectNotifier() _AsyncPoller._Read = 0x01 _AsyncPoller._Write = 0x02 _AsyncPoller._Hangup = 0x04 _AsyncPoller._Error = 0x08 _AsyncPoller._Block = None self._fds = {} self._events = {} self._timeouts = [] self.cmd_read, self.cmd_write = _AsyncPoller._cmd_read_write_fds(self) if hasattr(self.cmd_write, 'getsockname'): self.cmd_read = AsyncSocket(self.cmd_read) self.cmd_read._read_fn = lambda: self.cmd_read._rsock.recv(128) self.interrupt = lambda: self.cmd_write.send('I') else: self.interrupt = lambda: os.write(self.cmd_write._fileno, 'I') self.add(self.cmd_read, _AsyncPoller._Read)
def __init__(self): self.timeout_multiplier = 1 if hasattr(select, 'epoll'): self._poller_name = 'epoll' self._poller = select.epoll() _AsyncPoller._Read = select.EPOLLIN | select.EPOLLPRI _AsyncPoller._Write = select.EPOLLOUT _AsyncPoller._Hangup = select.EPOLLHUP _AsyncPoller._Error = select.EPOLLERR _AsyncPoller._Block = -1 elif hasattr(select, 'kqueue'): self._poller_name = 'kqueue' self._poller = _KQueueNotifier() # kqueue filter values are negative numbers so using # them as flags won't work, so define them as necessary _AsyncPoller._Read = 0x01 _AsyncPoller._Write = 0x02 _AsyncPoller._Hangup = 0x04 _AsyncPoller._Error = 0x08 _AsyncPoller._Block = None elif hasattr(select, 'devpoll'): self._poller_name = 'devpoll' self._poller = select.devpoll() _AsyncPoller._Read = select.POLLIN | select.POLLPRI _AsyncPoller._Write = select.POLLOUT _AsyncPoller._Hangup = select.POLLHUP _AsyncPoller._Error = select.POLLERR _AsyncPoller._Block = -1 self.timeout_multiplier = 1000 elif hasattr(select, 'poll'): self._poller_name = 'poll' self._poller = select.poll() _AsyncPoller._Read = select.POLLIN | select.POLLPRI _AsyncPoller._Write = select.POLLOUT _AsyncPoller._Hangup = select.POLLHUP _AsyncPoller._Error = select.POLLERR _AsyncPoller._Block = -1 self.timeout_multiplier = 1000 else: self._poller_name = 'select' self._poller = _SelectNotifier() _AsyncPoller._Read = 0x01 _AsyncPoller._Write = 0x02 _AsyncPoller._Hangup = 0x04 _AsyncPoller._Error = 0x08 _AsyncPoller._Block = None self._fds = {} self._events = {} self._timeouts = [] self.cmd_read, self.cmd_write = _AsyncPoller._cmd_read_write_fds(self) if hasattr(self.cmd_write, 'getsockname'): self.cmd_read = AsyncSocket(self.cmd_read) self.cmd_read._read_fn = lambda: self.cmd_read._rsock.recv(128) self.interrupt = lambda: self.cmd_write.send(b'I') else: self.interrupt = lambda: os.write(self.cmd_write._fileno, b'I') self.add(self.cmd_read, _AsyncPoller._Read)
def _communicate_with_poll(self, input): stdout = None # Return stderr = None # Return fd2file = {} fd2output = {} poller = select.poll() def register_and_append(file_obj, eventmask): poller.register(file_obj.fileno(), eventmask) fd2file[file_obj.fileno()] = file_obj def close_unregister_and_remove(fd): poller.unregister(fd) fd2file[fd].close() fd2file.pop(fd) if self.stdin and input: register_and_append(self.stdin, select.POLLOUT) select_POLLIN_POLLPRI = select.POLLIN | select.POLLPRI if self.stdout: register_and_append(self.stdout, select_POLLIN_POLLPRI) fd2output[self.stdout.fileno()] = stdout = [] if self.stderr: register_and_append(self.stderr, select_POLLIN_POLLPRI) fd2output[self.stderr.fileno()] = stderr = [] input_offset = 0 while fd2file: try: ready = poller.poll() except select.error, e: if e.args[0] == errno.EINTR: continue raise for fd, mode in ready: if mode & select.POLLOUT: chunk = input[input_offset : input_offset + _PIPE_BUF] try: input_offset += os.write(fd, chunk) except OSError as e: if e.errno == errno.EPIPE: close_unregister_and_remove(fd) else: raise else: if input_offset >= len(input): close_unregister_and_remove(fd) elif mode & select_POLLIN_POLLPRI: data = os.read(fd, 4096) if not data: close_unregister_and_remove(fd) fd2output[fd].append(data) else: # Ignore hang up or errors. close_unregister_and_remove(fd) return (stdout, stderr)
def read(self, timeout=0): ''' Read the contents of the spool. This may cause reads on the registered file descriptors. ''' if not self.fds: raise Exception('no file descriptors registered') if timeout > 0: start = datetime.now() io = StringIO() stop = False while (not stop): stop = True if timeout > 0: limit = timeout - ((datetime.now() - start).microseconds / 1000) if limit < 0: raise Exception('time out') else: limit = 0 events = self.fds.poll(limit) if not events: raise Exception('time out') for e in events: if (e[1] & select.POLLIN or e[1] & select.POLLPRI): tmp = os.read(e[0], 4096) if tmp: io.write(tmp) if self.log: self.log.write(tmp) continue if e[1] & select.POLLERR: self.fds.unregister(e[0]) raise Exception('POLLERR') if e[1] & select.POLLHUP: self.fds.unregister(e[0]) raise Exception('POLLHUP') if e[1] & select.POLLNVAL: self.fds.unregister(e[0]) raise Exception('POLLNVAL') if self.log: self.log.flush() return io.getvalue()
def _read_until_with_poll(self, match, timeout): """Read until a given string is encountered or until timeout. This method uses select.poll() to implement the timeout. """ n = len(match) call_timeout = timeout if timeout is not None: from time import time time_start = time() self.process_rawq() i = self.cookedq.find(match) if i < 0: poller = select.poll() poll_in_or_priority_flags = select.POLLIN | select.POLLPRI poller.register(self, poll_in_or_priority_flags) while i < 0 and not self.eof: try: # Poll takes its timeout in milliseconds. ready = poller.poll(None if timeout is None else 1000 * call_timeout) except select.error as e: if e.errno == errno.EINTR: if timeout is not None: elapsed = time() - time_start call_timeout = timeout-elapsed continue raise for fd, mode in ready: if mode & poll_in_or_priority_flags: i = max(0, len(self.cookedq)-n) self.fill_rawq() self.process_rawq() i = self.cookedq.find(match, i) if timeout is not None: elapsed = time() - time_start if elapsed >= timeout: break call_timeout = timeout-elapsed poller.unregister(self) if i >= 0: i = i + n buf = self.cookedq[:i] self.cookedq = self.cookedq[i:] return buf return self.read_very_lazy()