本文整理汇总了Python中selectors.DefaultSelector方法的典型用法代码示例。如果您正苦于以下问题:Python selectors.DefaultSelector方法的具体用法?Python selectors.DefaultSelector怎么用?Python selectors.DefaultSelector使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类selectors
的用法示例。
在下文中一共展示了selectors.DefaultSelector方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run
# 需要导入模块: import selectors [as 别名]
# 或者: from selectors import DefaultSelector [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")
示例2: _run
# 需要导入模块: import selectors [as 别名]
# 或者: from selectors import DefaultSelector [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()
示例3: _wait_for_io_events
# 需要导入模块: import selectors [as 别名]
# 或者: from selectors import DefaultSelector [as 别名]
def _wait_for_io_events(socks, events, timeout):
""" Waits for IO events to be available from a list of sockets
or optionally a single socket if passed in. Returns a list of
sockets that can be interacted with immediately. """
if not isinstance(socks, list):
# Probably just a single socket.
if hasattr(socks, "fileno"):
socks = [socks]
# Otherwise it might be a non-list iterable.
else:
socks = list(socks)
with DefaultSelector() as selector:
for sock in socks:
try:
selector.register(sock, events)
except Exception as e:
raise SocketValueError("SocketValueError", e)
return [key[0].fileobj for key in
selector.select(timeout) if key[1] & events]
示例4: select_recv
# 需要导入模块: import selectors [as 别名]
# 或者: from selectors import DefaultSelector [as 别名]
def select_recv(conn, buff_size, timeout=None):
"""add timeout for socket.recv()
:type conn: socket.socket
:type buff_size: int
:type timeout: float
:rtype: Union[bytes, None]
"""
if selectors:
sel = selectors.DefaultSelector()
sel.register(conn, EVENT_READ)
events = sel.select(timeout)
sel.close()
if not events:
# timeout
raise RuntimeError("recv timeout")
else:
rlist, _, _ = select.select([conn], [], [], timeout)
buff = conn.recv(buff_size)
if not buff:
raise RuntimeError("received zero bytes, socket was closed")
return buff
示例5: start_server
# 需要导入模块: import selectors [as 别名]
# 或者: from selectors import DefaultSelector [as 别名]
def start_server(path: str, host: str, port: int, terminated: threading.Event):
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.settimeout(1)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
server_socket.bind((host, port))
server_socket.listen(1)
stub_cls = type('StubSFTPServer', (StubSFTPServer,), {'ROOT': path})
host_key = RSAKey.generate(1024)
def accept(server_socket, mask):
conn, addr = server_socket.accept()
transport = Transport(conn)
transport.add_server_key(host_key)
transport.set_subsystem_handler('sftp', SFTPServer, stub_cls)
server = StubServer(path)
transport.start_server(server=server)
while not terminated.is_set():
channel = transport.accept(1)
if channel is not None and not terminated.is_set():
while transport.is_active() and not terminated.is_set():
terminated.wait(1)
break
sel = selectors.DefaultSelector()
sel.register(server_socket, selectors.EVENT_READ, accept)
last_used = time.time()
while not terminated.is_set() and last_used + 10 > time.time():
events = sel.select(1)
for key, mask in events:
key.data(key.fileobj, mask)
last_used = time.time()
示例6: __init__
# 需要导入模块: import selectors [as 别名]
# 或者: from selectors import DefaultSelector [as 别名]
def __init__(self):
self.sock = self.daemon = self.locationStr = None
self.selector = selectors.DefaultSelector()
self.shutting_down = False
示例7: __init__
# 需要导入模块: import selectors [as 别名]
# 或者: from selectors import DefaultSelector [as 别名]
def __init__(self):
self.daemon = self.sock = self._socketaddr = self.locationStr = self.pool = None
self.shutting_down = False
self.housekeeper = None
self._selector = selectors.DefaultSelector()
示例8: poll_streams
# 需要导入模块: import selectors [as 别名]
# 或者: from selectors import DefaultSelector [as 别名]
def poll_streams(*files, line_timeout=None, global_timeout=None):
"""
Poll a set of file objects for new data and return it line by line.
The file objects should be line-buffered or unbuffered. Regular files won't
work on some systems (notably Linux, where DefaultSelector uses epoll() by
default; this function is pointless for regular files anyway, since they are
always ready for reading and writing).
Each line returned is a 2-items tuple, with the first item being the object
implementing the file interface, and the second the text read.
The optional parameters line_timeout and global_timeout specify how long in
seconds to wait at most for a single line or for all lines. If no timeout
is specified, this function will block indefintely for each line.
"""
selector = selectors.DefaultSelector()
for fileobj in files:
selector.register(fileobj, selectors.EVENT_READ)
timeout = _line_timeout_generator(line_timeout, global_timeout)
while selector.get_map():
try:
next_timeout = next(timeout)
except StopIteration:
logger.error('_line_timeout_generator returned (should never happen).'
'line_timeout: %s, global_timeout: %s',
line_timeout, global_timeout)
next_timeout = 0
available = selector.select(next_timeout)
if not available:
# TODO(smarnach): This can also mean that the process received a signal.
raise TimeoutError('Could not read line before timeout: {timeout}'.format(timeout=timeout))
for key, unused_mask in available:
line = key.fileobj.readline()
if line:
yield (key.fileobj, line)
else:
selector.unregister(key.fileobj)
示例9: __init__
# 需要导入模块: import selectors [as 别名]
# 或者: from selectors import DefaultSelector [as 别名]
def __init__(self, selector=None):
super().__init__()
if selector is None:
selector = selectors.DefaultSelector()
logger.debug('Using selector: %s', selector.__class__.__name__)
self._selector = selector
self._make_self_pipe()
self._transports = weakref.WeakValueDictionary()
示例10: test_select
# 需要导入模块: import selectors [as 别名]
# 或者: from selectors import DefaultSelector [as 别名]
def test_select(self):
import select
self.assertFalse(hasattr(select, "kevent"))
self.assertFalse(hasattr(select, "kqueue"))
import selectors
self.assertIs(selectors.DefaultSelector, selectors.EpollSelector)
示例11: redirect
# 需要导入模块: import selectors [as 别名]
# 或者: from selectors import DefaultSelector [as 别名]
def redirect(fd, callback):
save_fd = os.dup(fd)
s_in, s_out = socket.socketpair()
os.dup2(s_in.fileno(), fd)
os.close(s_in.fileno())
s_out.setblocking(False)
sel = DefaultSelector()
sel.register(s_out, EVENT_READ)
def target():
while running:
_, = sel.select() # There's only one event.
callback(s_out.recv(4096))
running = True
thread = Thread(target=target, daemon=True)
thread.start()
try:
yield
finally:
running = False
os.dup2(save_fd, fd)
os.close(save_fd)
示例12: run
# 需要导入模块: import selectors [as 别名]
# 或者: from selectors import DefaultSelector [as 别名]
def run(self, *args, **kwargs):
# TODO: enable TCP_QUICKACK?
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((self.host, self.port))
sock.listen()
logger.debug('Tcp server running at %s:%d' % (self.host, self.port))
self._sock = sock
# TODO: choose a better selector?
with selectors.DefaultSelector() as sel:
# NOTE: use selector timeout and server status flag(threading.Event)
# to make tcp server stoppable
sel.register(self._sock, selectors.EVENT_READ)
while not self._close_event.is_set():
# TODO: better default interval settings?
ready = sel.select(0.5)
if not ready:
continue
try:
conn, addr = sock.accept()
except OSError: # sock is closed
logger.debug('Tcp server is closed.')
break
except ConnectionError as e:
logger.warning(e)
break
else:
logger.debug('%s:%d connected.' % addr)
Thread(target=self.handle_func, args=(conn, addr, *args),
kwargs=kwargs, name='TcpClientThread').start()
logger.debug('Tcp server is stopped.')
示例13: __init__
# 需要导入模块: import selectors [as 别名]
# 或者: from selectors import DefaultSelector [as 别名]
def __init__(self, server_status_datasource: ServerStatusDatasource):
self.server_status_datasource = server_status_datasource
self.sel = selectors.DefaultSelector()
self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
示例14: __init__
# 需要导入模块: import selectors [as 别名]
# 或者: from selectors import DefaultSelector [as 别名]
def __init__(self, host: str, port: int):
self.sel = selectors.DefaultSelector()
self.host = host
self.port = port
self.uuid = uuid.uuid4()
示例15: __init__
# 需要导入模块: import selectors [as 别名]
# 或者: from selectors import DefaultSelector [as 别名]
def __init__(self, our_sock, send_func):
super().__init__(name='SocketLoop{:x}'.format(our_sock.fileno()))
self._our_sock = our_sock
self._send_func = send_func
self._do_loop = True
self._cntrl_r, self._cntrl_w = socket.socketpair()
self._selector = DefaultSelector()
self._selector.register(self._our_sock, EVENT_READ, self._do_recv)
self._selector.register(self._cntrl_r, EVENT_READ, self._do_stop)