本文整理匯總了Python中gevent.select.select方法的典型用法代碼示例。如果您正苦於以下問題:Python select.select方法的具體用法?Python select.select怎麽用?Python select.select使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類gevent.select
的用法示例。
在下文中一共展示了select.select方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: run
# 需要導入模塊: from gevent import select [as 別名]
# 或者: from gevent.select import select [as 別名]
def run(self):
websocket_fd = uwsgi.connection_fd()
channel_fd = self.channel.connection._sock.fileno()
fds = [websocket_fd, channel_fd]
try:
while True:
readable, _, _ = select.select(fds, [], [], TIMEOUT)
if not readable:
self.recv()
continue
self.recv()
data = self.channel.get_message(ignore_subscribe_messages=True)
if data:
self.on_channel_data(data)
except self.WebSocketError:
return HttpResponse('ws ok')
finally:
self.channel.unsubscribe()
self.on_connection_lost()
示例2: can_read
# 需要導入模塊: from gevent import select [as 別名]
# 或者: from gevent.select import select [as 別名]
def can_read(self, timeout=0.0):
"""
Checks if there is data that can be read from the
socket (if open). Returns True if there is data and
False if not.
It returns None if something very bad happens such as
a dead connection (bad file descriptor), etc
"""
# rs = Read Sockets
# ws = Write Sockets
# es = Error Sockets
if self.socket is not None:
try:
rs, _, es = select([self.socket], [], [], timeout)
except (SelectError, socket.error), e:
if e[0] == errno.EBADF:
# Bad File Descriptor... hmm
self.close()
return None
if len(es) > 0:
# Bad File Descriptor
self.close()
return None
return len(rs) > 0
# no socket or no connection
return None
示例3: can_write
# 需要導入模塊: from gevent import select [as 別名]
# 或者: from gevent.select import select [as 別名]
def can_write(self, timeout=0):
"""
Checks if there is data that can be written to the
socket (if open). Returns True if writing is possible and
False if not.
It returns None if something very bad happens such as
a dead connection (bad file descriptor), etc
"""
# rs = Read Sockets
# ws = Write Sockets
# es = Error Sockets
if self.socket is not None:
try:
_, ws, es = select([], [self.socket], [], timeout)
except (SelectError, socket.error), e:
if e[0] == errno.EBADF:
# Bad File Descriptor... hmm
self.close()
return None
if len(es) > 0:
# Bad File Descriptor
self.close()
return None
return len(ws) > 0
# no socket or no connection
return None
示例4: _handle_socket_read
# 需要導入模塊: from gevent import select [as 別名]
# 或者: from gevent.select import select [as 別名]
def _handle_socket_read(handler, sock):
collected = b''
while True:
# a full packet before calling on_packet in the handler class
ready = select.select([sock], [], [], 0.0)
try:
if ready[0]:
data = sock.recv(4096)
# print("data in: %s" % hex_bytes(data))
collected += data
# Try and consume repeatedly if multiple messages arrived
# in the same packet
while True:
collected1 = handler.consume(collected)
if collected1 is None:
print("Protocol requested to disconnect the socket")
break
if collected1 == collected:
break # could not consume any more
collected = collected1
else:
handler.handle_inbox()
except select.error:
# Disconnected probably or another error
break
sock.close()
handler.on_connection_lost()
示例5: _get_descriptors
# 需要導入模塊: from gevent import select [as 別名]
# 或者: from gevent.select import select [as 別名]
def _get_descriptors(self):
"""Returns three elements tuple with socket descriptors ready
for gevent.select.select
"""
rlist = []
wlist = []
xlist = []
for socket, flags in self.sockets:
if isinstance(socket, zmq.Socket):
rlist.append(socket.getsockopt(zmq.FD))
continue
elif isinstance(socket, int):
fd = socket
elif hasattr(socket, 'fileno'):
try:
fd = int(socket.fileno())
except:
raise ValueError('fileno() must return an valid integer fd')
else:
raise TypeError('Socket must be a 0MQ socket, an integer fd '
'or have a fileno() method: %r' % socket)
if flags & zmq.POLLIN:
rlist.append(fd)
if flags & zmq.POLLOUT:
wlist.append(fd)
if flags & zmq.POLLERR:
xlist.append(fd)
return (rlist, wlist, xlist)
示例6: getChar
# 需要導入模塊: from gevent import select [as 別名]
# 或者: from gevent.select import select [as 別名]
def getChar():
if geventSelect.select([sys.stdin], [], [], 0) == ([sys.stdin], [], []): # non blocking raw_input, unix only
return sys.stdin.read(1)
示例7: gr1
# 需要導入模塊: from gevent import select [as 別名]
# 或者: from gevent.select import select [as 別名]
def gr1():
# Busy waits for a second, but we don't want to stick around...
print('Started Polling: ', tic())
select.select([], [], [], 2)
print('Ended Polling: ', tic())
示例8: gr2
# 需要導入模塊: from gevent import select [as 別名]
# 或者: from gevent.select import select [as 別名]
def gr2():
# Busy waits for a second, but we don't want to stick around...
print('Started Polling: ', tic())
select.select([], [], [], 2)
print('Ended Polling: ', tic())
示例9: __call__
# 需要導入模塊: from gevent import select [as 別名]
# 或者: from gevent.select import select [as 別名]
def __call__(self, environ, start_response):
self.environ = environ
uwsgi.websocket_handshake()
self._req_ctx = None
if hasattr(uwsgi, 'request_context'):
# uWSGI >= 2.1.x with support for api access across-greenlets
self._req_ctx = uwsgi.request_context()
else:
# use event and queue for sending messages
from gevent.event import Event
from gevent.queue import Queue
from gevent.select import select
self._event = Event()
self._send_queue = Queue()
# spawn a select greenlet
def select_greenlet_runner(fd, event):
"""Sets event when data becomes available to read on fd."""
while True:
event.set()
try:
select([fd], [], [])[0]
except ValueError:
break
self._select_greenlet = gevent.spawn(
select_greenlet_runner,
uwsgi.connection_fd(),
self._event)
self.app(self)
示例10: gr1
# 需要導入模塊: from gevent import select [as 別名]
# 或者: from gevent.select import select [as 別名]
def gr1():
# Busy waits for a second, but we don't want to stick around...
print('Started Polling: %s' % tic())
select.select([], [], [], 2)
print('Ended Polling: %s' % tic())
示例11: gr2
# 需要導入模塊: from gevent import select [as 別名]
# 或者: from gevent.select import select [as 別名]
def gr2():
# Busy waits for a second, but we don't want to stick around...
print('Started Polling: %s' % tic())
select.select([], [], [], 2)
print('Ended Polling: %s' % tic())
示例12: run_parallel
# 需要導入模塊: from gevent import select [as 別名]
# 或者: from gevent.select import select [as 別名]
def run_parallel(self, hosts, cmd):
codes = {"total": 0, "error": 0, "success": 0}
def worker(host, cmd):
p = Popen(self.get_parallel_ssh_options(host, cmd), stdout=PIPE, stderr=PIPE)
while True:
outs, _, _ = select([p.stdout, p.stderr], [], [])
if p.stdout in outs:
outline = p.stdout.readline()
else:
outline = ""
if p.stderr in outs:
errline = p.stderr.readline()
else:
errline = ""
if outline == "" and errline == "" and p.poll() is not None:
break
if outline != "":
print("%s: %s" % (colored(host, "blue", attrs=["bold"]), outline.strip()))
if errline != "":
print("%s: %s" % (colored(host, "blue", attrs=["bold"]), colored(errline.strip(), "red")))
if p.poll() == 0:
codes["success"] += 1
else:
codes["error"] += 1
codes["total"] += 1
pool = Pool(self.ssh_threads)
for host in hosts:
pool.start(Greenlet(worker, host, cmd))
pool.join()
self.print_exec_results(codes)
示例13: ping_parallel
# 需要導入模塊: from gevent import select [as 別名]
# 或者: from gevent.select import select [as 別名]
def ping_parallel(self, hosts, pc):
"""ping:\n pings host (using shell cmd)"""
codes = {"total": 0, "error": 0, "success": 0}
def worker(host):
if pc == 0:
args = ["ping", host]
else:
args = ["ping", "-c", str(pc), host]
p = Popen(args, stdout=PIPE, stderr=PIPE)
while True:
outs, _, _ = select([p.stdout, p.stderr], [], [])
if p.stdout in outs:
outline = p.stdout.readline()
else:
outline = ""
if p.stderr in outs:
errline = p.stderr.readline()
else:
errline = ""
if outline == "" and errline == "" and p.poll() is not None:
break
if outline != "":
print("%s: %s" % (colored(host, "blue", attrs=["bold"]), outline.strip()))
if errline != "":
print("%s: %s" % (colored(host, "blue", attrs=["bold"]), colored(errline.strip(), "red")))
if p.poll() == 0:
codes["success"] += 1
else:
codes["error"] += 1
codes["total"] += 1
pool = Pool(self.ssh_threads)
for host in hosts:
pool.start(Greenlet(worker, host))
pool.join()
self.print_exec_results(codes)
示例14: poll
# 需要導入模塊: from gevent import select [as 別名]
# 或者: from gevent.select import select [as 別名]
def poll(self, timeout=-1):
"""Overridden method to ensure that the green version of
Poller is used.
Behaves the same as :meth:`zmq.core.Poller.poll`
"""
if timeout is None:
timeout = -1
if timeout < 0:
timeout = -1
rlist = None
wlist = None
xlist = None
if timeout > 0:
tout = gevent.Timeout.start_new(timeout/1000.0)
else:
tout = None
try:
# Loop until timeout or events available
rlist, wlist, xlist = self._get_descriptors()
while True:
events = super(_Poller, self).poll(0)
if events or timeout == 0:
return events
# wait for activity on sockets in a green way
# set a minimum poll frequency,
# because gevent < 1.0 cannot be trusted to catch edge-triggered FD events
_bug_timeout = gevent.Timeout.start_new(self._gevent_bug_timeout)
try:
select.select(rlist, wlist, xlist)
except gevent.Timeout as t:
if t is not _bug_timeout:
raise
finally:
_bug_timeout.cancel()
except gevent.Timeout as t:
if t is not tout:
raise
return []
finally:
if timeout > 0:
tout.cancel()
示例15: poll
# 需要導入模塊: from gevent import select [as 別名]
# 或者: from gevent.select import select [as 別名]
def poll(self, timeout=-1):
"""Overridden method to ensure that the green version of
Poller is used.
Behaves the same as :meth:`zmq.core.Poller.poll`
"""
if timeout is None:
timeout = -1
if timeout < 0:
timeout = -1
rlist = None
wlist = None
xlist = None
if timeout > 0:
tout = gevent.Timeout.start_new(timeout/1000.0)
try:
# Loop until timeout or events available
rlist, wlist, xlist = self._get_descriptors()
while True:
events = super(_Poller, self).poll(0)
if events or timeout == 0:
return events
# wait for activity on sockets in a green way
# set a minimum poll frequency,
# because gevent < 1.0 cannot be trusted to catch edge-triggered FD events
_bug_timeout = gevent.Timeout.start_new(self._gevent_bug_timeout)
try:
select.select(rlist, wlist, xlist)
except gevent.Timeout as t:
if t is not _bug_timeout:
raise
finally:
_bug_timeout.cancel()
except gevent.Timeout as t:
if t is not tout:
raise
return []
finally:
if timeout > 0:
tout.cancel()