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)
python类POLLIN的实例源码
def _doReadOrWrite(self, selectable, fd, event, POLLIN, POLLOUT, log,
faildict={
error.ConnectionDone: failure.Failure(error.ConnectionDone()),
error.ConnectionLost: failure.Failure(error.ConnectionLost())
}):
why = None
inRead = False
if event & POLL_DISCONNECTED and not (event & POLLIN):
why = main.CONNECTION_LOST
else:
try:
if event & POLLIN:
why = selectable.doRead()
inRead = True
if not why and event & POLLOUT:
why = selectable.doWrite()
inRead = False
if not selectable.fileno() == fd:
why = error.ConnectionFdescWentAway('Filedescriptor went away')
inRead = False
except:
log.deferr()
why = sys.exc_info()[1]
if why:
self._disconnectSelectable(selectable, why, inRead)
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 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 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 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 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()
def new_socket_connection(self, server):
connection, address = server.accept()
max_connections = 10
if len(self.sockets) == max_connections:
connection.close()
print 'nmea server has too many connections'
return
if not self.sockets:
self.setup_watches()
self.pipe.send('sockets')
sock = NMEASocket(connection)
self.sockets.append(sock)
#print 'new connection: ', address
self.addresses[sock] = address
fd = sock.socket.fileno()
self.fd_to_socket[fd] = sock
self.poller.register(sock.socket, select.POLLIN)
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 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
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
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
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
def _updateRegistration(self, fd):
"""Register/unregister an fd with the poller."""
try:
poller.unregister(fd)
except KeyError:
pass
mask = 0
if fd in reads:
mask = mask | select.POLLIN
if fd in writes:
mask = mask | select.POLLOUT
if mask != 0:
poller.register(fd, mask)
else:
if fd in selectables:
del selectables[fd]
poller.eApp.interruptPoll()
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
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
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
def read_line(self, time_limit=None):
"""
Read a line from the process.
Block or wait for time_limit secs. Timeout does not work on Windows.
"""
if self.proc is not None:
poll_obj = select.poll()
poll_obj.register(self.proc.stdout, select.POLLIN)
start = time.time()
while time_limit is None or time.time() - start < time_limit:
poll_result = poll_obj.poll(0)
if poll_result:
line = self.proc.stdout.readline().decode()
return line
else:
time.sleep(0.05)
raise TimeoutError()
else:
return None
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
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
def register(self, fd, eventmask=_NONE):
if eventmask is _NONE:
flags = _EV_READ | _EV_WRITE
else:
flags = 0
if eventmask & POLLIN:
flags = _EV_READ
if eventmask & POLLOUT:
flags |= _EV_WRITE
# If they ask for POLLPRI, we can't support
# that. Should we raise an error?
fileno = get_fileno(fd)
watcher = self.loop.io(fileno, flags)
watcher.priority = self.loop.MAXPRI
self.fds[fileno] = watcher
def _updateRegistration(self, fd):
"""Register/unregister an fd with the poller."""
try:
poller.unregister(fd)
except KeyError:
pass
mask = 0
if reads.has_key(fd): mask = mask | select.POLLIN
if writes.has_key(fd): mask = mask | select.POLLOUT
if mask != 0:
poller.register(fd, mask)
else:
if selectables.has_key(fd): del selectables[fd]
poller.eApp.interruptPoll()
def _doReadOrWrite(self, selectable, fd, event, POLLIN, POLLOUT, log,
faildict={
error.ConnectionDone: failure.Failure(error.ConnectionDone()),
error.ConnectionLost: failure.Failure(error.ConnectionLost())
}):
why = None
inRead = False
if event & POLL_DISCONNECTED and not (event & POLLIN):
why = main.CONNECTION_LOST
else:
try:
if event & POLLIN:
why = selectable.doRead()
inRead = True
if not why and event & POLLOUT:
why = selectable.doWrite()
inRead = False
if not selectable.fileno() == fd:
why = error.ConnectionFdescWentAway('Filedescriptor went away')
inRead = False
except:
log.deferr()
why = sys.exc_info()[1]
if why:
self._disconnectSelectable(selectable, why, inRead)
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 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.
libmilter.py 文件源码
项目:sipxecs-voicemail-transcription
作者: andrewsauder
项目源码
文件源码
阅读 33
收藏 0
点赞 0
评论 0
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 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
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