本文整理汇总了Python中selectors.DefaultSelector类的典型用法代码示例。如果您正苦于以下问题:Python DefaultSelector类的具体用法?Python DefaultSelector怎么用?Python DefaultSelector使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了DefaultSelector类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: selector
def selector():
sel = DefaultSelector()
sel.register(proc.stdout, EVENT_READ, 0)
sel.register(proc.stderr, EVENT_READ, 1)
while True:
for key, mask in sel.select():
yield key.data, decode(key.fileobj.readline(linesize))
示例2: redirect
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)
示例3: selector
def selector():
sel = DefaultSelector()
sel.register(proc.stdout, EVENT_READ, 0)
sel.register(proc.stderr, EVENT_READ, 1)
while True:
ready = sel.select(line_timeout)
if not ready and line_timeout:
raise ProcessLineTimedOut("popen line timeout expired", getattr(proc, "argv", None), getattr(proc, "machine", None))
for key, mask in ready:
yield key.data, decode(key.fileobj.readline(linesize))
示例4: __init__
class Loop:
def __init__(self):
self.ready = deque()
self.selector = DefaultSelector()
self.futures = {}
def create_task(self, task):
self.ready.append(task)
def run_forever(self):
while True:
while not self.ready:
completed_futures = [future for future in self.futures if not future.running()]
for future in completed_futures:
self.ready.append(self.futures.pop(future))
# so select() is blocking. If set a negative time out it won't block.
events = self.selector.select(-1)
# add these socket events and unregister them from listened to:
for key, _ in events:
self.ready.append(key.data) # add the task to the ready queue
self.selector.unregister(key.fileobj)
while self.ready:
self.current_task = self.ready.popleft()
# try to run current_task...
try:
# run task to next yield point
reason, what = self.current_task.send(None)
# reason, what = self.current_task.send(None)
if reason == 'waiting_to_accept':
self.selector.register(what, EVENT_READ, self.current_task)
elif reason == 'waiting_to_read':
self.selector.register(what, EVENT_READ, self.current_task)
elif reason == 'waiting_to_write':
self.selector.register(what, EVENT_WRITE, self.current_task)
elif reason == 'waiting_for_future':
self.futures[what] = self.current_task
else:
raise RuntimeError(
'Something bad happened... er. reason={}'.format(reason))
except StopIteration:
pass
async def sock_recv(self, sock, maxbytes):
# wait to read from the socket
await read_wait(sock)
return sock.recv(maxbytes)
async def sock_accept(self, sock):
# wait to read/hear from the socket
await accept_wait(sock)
return sock.accept()
async def sock_sendall(self, sock, data):
while data:
# wait to be able to write to the socket
await write_wait(sock)
nsent = sock.send(data)
data = data[nsent:]
def run_in_executor(self, executor, func, *args):
return executor.submit(func, *args)
示例5: __init__
class Loop:
def __init__(self):
self.sel = DefaultSelector()
self.queue = deque()
def create_task(self, coro):
sock = coro.send(None)
self.sel.register(sock, EVENT_WRITE, coro)
self.queue.append(coro)
def run(self):
while self.queue:
events = self.sel.select()
for key, _ in events:
coro = key.data
event = key.events
file_obj = key.fileobj
self.sel.unregister(file_obj)
try:
if event == EVENT_WRITE:
self.sel.register(file_obj, EVENT_READ, coro)
elif event == EVENT_READ:
self.sel.register(file_obj, EVENT_WRITE, coro)
coro.send(None)
except StopIteration:
self.queue.popleft()
except:
pass
else: return
示例6: IRC
class IRC(Service):
DEFAULT_PORT = 6667
TIMEOUT = 3
def __init__(self,events):
super().__init__(events,'irc')
self.servers = set()
self.selector = DefaultSelector()
self.events = events
self.has_servers = Event()
self.channels = {}#server:[channels]
def respond(self,addr,command):
if command['action']=='connect':
server = command['host']
nick = command['nick']
port = command.get('port',self.DEFAULT_PORT)
self.connect((server,port),nick)
if command['action']=='status':
print(self.servers)
self.broadcast({
'kind':'status',
'status':{
'servers':{
s: {
'channels':v
} for s,v in self.channels.items()
}
}
})
def connect(self,addr,nick):
host = addr[0]
if host not in self.servers:
print(nick)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print(addr)
sock.connect(addr)
self.events.listen(host,self.check_channels)
self.selector.register(sock,EVENT_READ|EVENT_WRITE,ChatServerInterface(addr[0],nick,self.events))
self.servers.add(host)
self.channels[host] = list()
if not self.has_servers.is_set():
self.has_servers.set()
def check_channels(self,addr,event):
if event['kind']=='irc':
if event['command']=='332':
print(event['event'],event['arguments'])
self.channels[event['event']].append(event['arguments'][1].lower())
def loop(self):
while True:
self.has_servers.wait()
for key,mask in self.selector.select():
if mask&EVENT_READ==EVENT_READ:
key.data.read_data(key.fileobj)
if mask&EVENT_WRITE==EVENT_WRITE:
key.data.write_data(key.fileobj)
示例7: get
def get(path, jobs):
jobs += 1
selector = DefaultSelector()
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.setblocking(False)
try:
client.connect(('localhost', 5000))
except BlockingIOError:
pass
f = Future()
selector.register(client.fileno(), EVENT_READ, f)
示例8: loop
def loop():
pre_loop_barrier.wait(1)
selector = DefaultSelector()
selector.register(sig_r_fd, EVENT_READ)
with suppress(StopIteration):
while True:
events = selector.select(timeout=5)
if len(events) == 0:
raise StopIteration
for key, mask in events:
if key.fd == sig_r_fd:
data = os.read(sig_r_fd, 4)
self._sigchld_caught = True
raise StopIteration
self._post_loop_barrier.wait(1)
示例9: __init__
def __init__(self):
"""
Конструктор событийного цикла, который хранит очередь
:return:
"""
self.ready = deque()
self.selector = DefaultSelector()
示例10: __init__
def __init__(self,events):
super().__init__(events,'irc')
self.servers = set()
self.selector = DefaultSelector()
self.events = events
self.has_servers = Event()
self.channels = {}#server:[channels]
示例11: __init__
def __init__(self, port):
self.port = port
self.sock = None
self.selector = DefaultSelector()
# Advance self.listen() method. A future has been attached to the
# server socket, that has been registered in selector. And a callback
# has been attached to this future.
Task(self.listen())
示例12: __init__
def __init__(self, port, callback):
logging.basicConfig(level=logging.INFO)
self.clients_kept_for_sending = []
self.selector = DefaultSelector()
self.callback = callback
self.server_socket = socket.socket(family=socket.AF_INET6,
type=socket.SOCK_STREAM)
self.server_socket.bind(("::0", port))
self.server_socket.listen(5)
self.selector.register(self.server_socket, EVENT_READ, data=None)
self.server_socket.setblocking(False)
示例13: __init__
class Loop:
def __init__(self):
self.ready = deque()
self.selectors = DefaultSelector() # a way to watch socket IO
async def sock_recv(self, sock, maxbytes):
await read_wait(sock) # wait for something happen
return sock.recv(maxbytes)
async def sock_accept(self, sock):
await read_wait(sock)
return sock.sock_accept()
async def sock_sendall(self, sock, data):
while data :
try:
nsent = sock.send(data)
data = data[nsent:] # send partial data
except BlockingIOError:
await write_wait(sock)
def create_task(self, coro):
self.ready.append(coro)
def run_forever(self):
while True:
while not self.ready:
events = self.selectors.select()
for key, _ in events:
self.ready.append(key.data)
self.selectors.unregister(key.fileobj)
while self.ready:
self.current_task = self.ready.popleft()
try:
op, *args = self.current_task.send(None) # run to the yield
getattr(self,op)(*args) # Sneaky method call
except StopIteration:
pass
def read_wait(self, sock):
self.selectors.register(sock, EVENT_READ, self.current_task)
def write_wait(self, sock):
self.selectors.register
示例14: __init__
class Loop:
def __init__(self):
self.ready = deque()
self.selector = DefaultSelector()
def create_task(self, task):
self.ready.append(task)
def run_forever(self):
while True:
# hmmn, nothing to run -> must be waiting on stuff...
while not self.ready:
events = self.selector.select()
# add these events and unregister them from listened to:
for key, _ in events:
self.ready.append(key.data)
self.selector.unregister(key.fileobj)
while self.ready:
self.current_task = self.ready.popleft()
# try to run current_task...
try:
# run task to next yield point
reason, sock = next(self.current_task)
if reason == 'waiting_to_accept':
self.selector.register(sock, EVENT_READ, self.current_task)
elif reason == 'waiting_to_read':
self.selector.register(sock, EVENT_READ, self.current_task)
elif reason == 'waiting_to_write':
self.selector.register(sock, EVENT_WRITE, self.current_task)
else:
raise RuntimeError('Something bad happened... er. reason={}'.format(reason))
except StopIteration:
pass
def sock_recv(self, sock, maxbytes):
# wait to read from the socket
return sock.recv(maxbytes)
def sock_accept(self, sock):
# wait to read/hear from the socket
return sock.accept()
def sock_sendall(self, sock, data):
while data:
# wait to be able to write to the socket
nsent = sock.send(data)
data = data[nsent:]
示例15: __init__
def __init__(self, fb):
assert isinstance(fb, Framebuffer)
self._fb = fb
# get all input devices
devices = [InputDevice(fn) for fn in evdev.list_devices()]
# filter out non key devices
for device in devices.copy():
cap = device.capabilities()
if ecodes.EV_KEY not in cap:
devices.remove(device)
continue
self._selector = DefaultSelector()
# This works because InputDevice has a `fileno()` method.
for device in devices:
self._selector.register(device, EVENT_READ)