本文整理汇总了Python中selectors.EVENT_READ属性的典型用法代码示例。如果您正苦于以下问题:Python selectors.EVENT_READ属性的具体用法?Python selectors.EVENT_READ怎么用?Python selectors.EVENT_READ使用的例子?那么恭喜您, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在类selectors
的用法示例。
在下文中一共展示了selectors.EVENT_READ属性的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: events
# 需要导入模块: import selectors [as 别名]
# 或者: from selectors import EVENT_READ [as 别名]
def events(self, eventsockets):
"""handle events that occur on one of the sockets of this server"""
for s in eventsockets:
if self.shutting_down:
return
if s is self.sock:
# server socket, means new connection
conn = self._handleConnection(self.sock)
if conn:
self.selector.register(conn, selectors.EVENT_READ, self)
else:
# must be client socket, means remote call
active = self.handleRequest(s)
if not active:
try:
self.daemon._clientDisconnect(s)
except Exception as x:
log.warning("Error in clientDisconnect: " + str(x))
self.selector.unregister(s)
s.close()
self.daemon._housekeeping()
示例2: loop
# 需要导入模块: import selectors [as 别名]
# 或者: from selectors import EVENT_READ [as 别名]
def loop(self, loopCondition=lambda: True):
log.debug("entering multiplexed requestloop")
while loopCondition():
try:
try:
events = self.selector.select(config.POLLTIMEOUT)
except OSError:
events = []
# get all the socket connection objects that have a READ event
# (the WRITE events are ignored here, they're registered to let timeouts work etc)
events_per_server = defaultdict(list)
for key, mask in events:
if mask & selectors.EVENT_READ:
events_per_server[key.data].append(key.fileobj)
for server, fileobjs in events_per_server.items():
server.events(fileobjs)
if not events_per_server:
self.daemon._housekeeping()
except socket.timeout:
pass # just continue the loop on a timeout
except KeyboardInterrupt:
log.debug("stopping on break signal")
break
示例3: run
# 需要导入模块: import selectors [as 别名]
# 或者: from selectors import EVENT_READ [as 别名]
def run(self):
retry = True
self.logger.info("Connecting to Socket")
sel = selectors.DefaultSelector()
conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
conn.setsockopt(
socket.SOL_SOCKET, socket.SO_LINGER, struct.pack('ii', 1, 0))
conn.setblocking(False)
conn.connect_ex((self.ip, self.port))
sel.register(conn, selectors.EVENT_READ, data=None)
while retry:
events = sel.select()
for key, mask in events:
retry = self.__handle_client__(key, mask, sel)
sel.unregister(conn)
if self.result['success']:
conn.shutdown(socket.SHUT_RDWR)
self.qresult.put(self.result)
self.logger.info("Socket Closed")
示例4: register
# 需要导入模块: import selectors [as 别名]
# 或者: from selectors import EVENT_READ [as 别名]
def register(self, fileobj, events, data=None):
if (not events) or (events & ~(EVENT_READ | EVENT_WRITE)):
raise ValueError("Invalid events: {!r}".format(events))
key = selectors.SelectorKey(fileobj, self._fileobj_lookup(fileobj), events, data)
if key.fd in self._fd_to_key:
raise KeyError("{!r} (FD {}) is already registered".format(fileobj, key.fd))
self._fd_to_key[key.fd] = key
if events & EVENT_READ:
notifier = QtCore.QSocketNotifier(key.fd, QtCore.QSocketNotifier.Read)
notifier.activated.connect(self.__on_read_activated)
self.__read_notifiers[key.fd] = notifier
if events & EVENT_WRITE:
notifier = QtCore.QSocketNotifier(key.fd, QtCore.QSocketNotifier.Write)
notifier.activated.connect(self.__on_write_activated)
self.__write_notifiers[key.fd] = notifier
return key
示例5: _process_event
# 需要导入模块: import selectors [as 别名]
# 或者: from selectors import EVENT_READ [as 别名]
def _process_event(self, key, mask):
"""Selector has delivered us an event."""
self._logger.debug('Processing event with key {} and mask {}'.format(key, mask))
fileobj, (reader, writer) = key.fileobj, key.data
if mask & selectors.EVENT_READ and reader is not None:
if reader._cancelled:
self.remove_reader(fileobj)
else:
self._logger.debug('Invoking reader callback: {}'.format(reader))
reader._run()
if mask & selectors.EVENT_WRITE and writer is not None:
if writer._cancelled:
self.remove_writer(fileobj)
else:
self._logger.debug('Invoking writer callback: {}'.format(writer))
writer._run()
示例6: _run
# 需要导入模块: import selectors [as 别名]
# 或者: from selectors import EVENT_READ [as 别名]
def _run(self):
sock = self._socket
selector = selectors.DefaultSelector()
selector.register(sock, selectors.EVENT_READ)
while sock.fileno() > 0:
self.log.debug("Waiting for incoming connections ...")
events = selector.select(timeout=1.0)
if events:
try:
conn, addr = sock.accept()
except OSError as ex:
if ex.errno in (errno.EBADF, errno.EINVAL):
break
raise
self.log.debug("... got connection %s from %s", conn, addr)
handler = Handler(self, (conn, addr))
t = threading.Thread(target=handler.run)
t.setDaemon(True)
t.start()
示例7: interact
# 需要导入模块: import selectors [as 别名]
# 或者: from selectors import EVENT_READ [as 别名]
def interact(self):
"""Interaction function, emulates a very dumb telnet client."""
if sys.platform == "win32":
self.mt_interact()
return
with _TelnetSelector() as selector:
selector.register(self, selectors.EVENT_READ)
selector.register(sys.stdin, selectors.EVENT_READ)
while True:
for key, events in selector.select():
if key.fileobj is self:
try:
text = self.read_eager()
except EOFError:
print('*** Connection closed by remote host ***')
return
if text:
sys.stdout.write(text.decode('ascii'))
sys.stdout.flush()
elif key.fileobj is sys.stdin:
line = sys.stdin.readline().encode('ascii')
if not line:
return
self.write(line)
示例8: serve_forever
# 需要导入模块: import selectors [as 别名]
# 或者: from selectors import EVENT_READ [as 别名]
def serve_forever(self, poll_interval=0.5):
"""Handle one request at a time until shutdown.
Polls for shutdown every poll_interval seconds. Ignores
self.timeout. If you need to do periodic tasks, do them in
another thread.
"""
self.__is_shut_down.clear()
try:
# XXX: Consider using another file descriptor or connecting to the
# socket to wake this up instead of polling. Polling reduces our
# responsiveness to a shutdown request and wastes cpu at all other
# times.
with _ServerSelector() as selector:
selector.register(self, selectors.EVENT_READ)
while not self.__shutdown_request:
ready = selector.select(poll_interval)
if ready:
self._handle_request_noblock()
self.service_actions()
finally:
self.__shutdown_request = False
self.__is_shut_down.set()
示例9: test_register
# 需要导入模块: import selectors [as 别名]
# 或者: from selectors import EVENT_READ [as 别名]
def test_register(self):
s = self.SELECTOR()
self.addCleanup(s.close)
rd, wr = self.make_socketpair()
key = s.register(rd, selectors.EVENT_READ, "data")
self.assertIsInstance(key, selectors.SelectorKey)
self.assertEqual(key.fileobj, rd)
self.assertEqual(key.fd, rd.fileno())
self.assertEqual(key.events, selectors.EVENT_READ)
self.assertEqual(key.data, "data")
# register an unknown event
self.assertRaises(ValueError, s.register, 0, 999999)
# register an invalid FD
self.assertRaises(ValueError, s.register, -10, selectors.EVENT_READ)
# register twice
self.assertRaises(KeyError, s.register, rd, selectors.EVENT_READ)
# register the same FD, but with a different object
self.assertRaises(KeyError, s.register, rd.fileno(),
selectors.EVENT_READ)
示例10: test_unregister_after_fd_close_and_reuse
# 需要导入模块: import selectors [as 别名]
# 或者: from selectors import EVENT_READ [as 别名]
def test_unregister_after_fd_close_and_reuse(self):
s = self.SELECTOR()
self.addCleanup(s.close)
rd, wr = self.make_socketpair()
r, w = rd.fileno(), wr.fileno()
s.register(r, selectors.EVENT_READ)
s.register(w, selectors.EVENT_WRITE)
rd2, wr2 = self.make_socketpair()
rd.close()
wr.close()
os.dup2(rd2.fileno(), r)
os.dup2(wr2.fileno(), w)
self.addCleanup(os.close, r)
self.addCleanup(os.close, w)
s.unregister(r)
s.unregister(w)
示例11: test_get_map
# 需要导入模块: import selectors [as 别名]
# 或者: from selectors import EVENT_READ [as 别名]
def test_get_map(self):
s = self.SELECTOR()
self.addCleanup(s.close)
rd, wr = self.make_socketpair()
keys = s.get_map()
self.assertFalse(keys)
self.assertEqual(len(keys), 0)
self.assertEqual(list(keys), [])
key = s.register(rd, selectors.EVENT_READ, "data")
self.assertIn(rd, keys)
self.assertEqual(key, keys[rd])
self.assertEqual(len(keys), 1)
self.assertEqual(list(keys), [rd.fileno()])
self.assertEqual(list(keys.values()), [key])
# unknown file obj
with self.assertRaises(KeyError):
keys[999999]
# Read-only mapping
with self.assertRaises(TypeError):
del keys[rd]
示例12: test_select
# 需要导入模块: import selectors [as 别名]
# 或者: from selectors import EVENT_READ [as 别名]
def test_select(self):
s = self.SELECTOR()
self.addCleanup(s.close)
rd, wr = self.make_socketpair()
s.register(rd, selectors.EVENT_READ)
wr_key = s.register(wr, selectors.EVENT_WRITE)
result = s.select()
for key, events in result:
self.assertTrue(isinstance(key, selectors.SelectorKey))
self.assertTrue(events)
self.assertFalse(events & ~(selectors.EVENT_READ |
selectors.EVENT_WRITE))
self.assertEqual([(wr_key, selectors.EVENT_WRITE)], result)
示例13: test_timeout
# 需要导入模块: import selectors [as 别名]
# 或者: from selectors import EVENT_READ [as 别名]
def test_timeout(self):
s = self.SELECTOR()
self.addCleanup(s.close)
rd, wr = self.make_socketpair()
s.register(wr, selectors.EVENT_WRITE)
t = time()
self.assertEqual(1, len(s.select(0)))
self.assertEqual(1, len(s.select(-1)))
self.assertLess(time() - t, 0.5)
s.unregister(wr)
s.register(rd, selectors.EVENT_READ)
t = time()
self.assertFalse(s.select(0))
self.assertFalse(s.select(-1))
self.assertLess(time() - t, 0.5)
t0 = time()
self.assertFalse(s.select(1))
t1 = time()
dt = t1 - t0
# Tolerate 2.0 seconds for very slow buildbots
self.assertTrue(0.8 <= dt <= 2.0, dt)
示例14: test_select_interrupt_exc
# 需要导入模块: import selectors [as 别名]
# 或者: from selectors import EVENT_READ [as 别名]
def test_select_interrupt_exc(self):
s = self.SELECTOR()
self.addCleanup(s.close)
rd, wr = self.make_socketpair()
class InterruptSelect(Exception):
pass
def handler(*args):
raise InterruptSelect
orig_alrm_handler = signal.signal(signal.SIGALRM, handler)
self.addCleanup(signal.signal, signal.SIGALRM, orig_alrm_handler)
self.addCleanup(signal.alarm, 0)
signal.alarm(1)
s.register(rd, selectors.EVENT_READ)
t = time()
# select() is interrupted by a signal which raises an exception
with self.assertRaises(InterruptSelect):
s.select(30)
# select() was interrupted before the timeout of 30 seconds
self.assertLess(time() - t, 5.0)
示例15: test_select_interrupt_noraise
# 需要导入模块: import selectors [as 别名]
# 或者: from selectors import EVENT_READ [as 别名]
def test_select_interrupt_noraise(self):
s = self.SELECTOR()
self.addCleanup(s.close)
rd, wr = self.make_socketpair()
orig_alrm_handler = signal.signal(signal.SIGALRM, lambda *args: None)
self.addCleanup(signal.signal, signal.SIGALRM, orig_alrm_handler)
self.addCleanup(signal.alarm, 0)
signal.alarm(1)
s.register(rd, selectors.EVENT_READ)
t = time()
# select() is interrupted by a signal, but the signal handler doesn't
# raise an exception, so select() should by retries with a recomputed
# timeout
self.assertFalse(s.select(1.5))
self.assertGreaterEqual(time() - t, 1.0)