本文整理汇总了Python中selectors.DefaultSelector类的典型用法代码示例。如果您正苦于以下问题:Python DefaultSelector类的具体用法?Python DefaultSelector怎么用?Python DefaultSelector使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了DefaultSelector类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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))
开发者ID:henryiii,项目名称:plumbum,代码行数:7,代码来源:processes.py
示例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)
开发者ID:anntzer,项目名称:matlab_kernel,代码行数:26,代码来源:_redirection.py
示例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))
开发者ID:weka-io,项目名称:plumbum,代码行数:10,代码来源:processes.py
示例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)
开发者ID:hargriffle,项目名称:pyne_concurrency_talk,代码行数:60,代码来源:server_1.6.py
示例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
开发者ID:pandafeeder,项目名称:python_stuff,代码行数:29,代码来源:coroutine_async_get.py
示例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)
开发者ID:tyler-elric,项目名称:ircp2p,代码行数:54,代码来源:irc.py
示例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)
开发者ID:arheo,项目名称:python_core,代码行数:14,代码来源:app2.py
示例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)
开发者ID:ubuntu-libertine,项目名称:libertine,代码行数:15,代码来源:test_launcher.py
示例9: __init__
def __init__(self):
"""
Конструктор событийного цикла, который хранит очередь
:return:
"""
self.ready = deque()
self.selector = DefaultSelector()
开发者ID:arheo,项目名称:python_core,代码行数:7,代码来源:play.py
示例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]
开发者ID:tyler-elric,项目名称:ircp2p,代码行数:7,代码来源:irc.py
示例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())
开发者ID:yevhen-m,项目名称:async_practice,代码行数:9,代码来源:server_jessie.py
示例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)
开发者ID:JonasT,项目名称:miraclecrafter,代码行数:11,代码来源:server.py
示例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
开发者ID:KentChun33333,项目名称:Night_Graden,代码行数:39,代码来源:SomeHistory.py
示例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:]
开发者ID:hargriffle,项目名称:pyne_concurrency_talk,代码行数:43,代码来源:server_1.0.py
示例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)
开发者ID:dlech,项目名称:ev3dev-photo-booth,代码行数:17,代码来源:ev3dev-photo-booth.py
示例16: __init__
def __init__(self):
self.selector = DefaultSelector()
self.init_hardware()
self.mouseevents = []
self.prev_value = 1
self.keynames = {
127: "menu",
28: "ok",
103: "up",
108: "down",
105: "left",
106: "right",
1: "back",
172: "home",
114: "volumedown",
115: "volumeup",
116: "power",
272: "btn_left"}
开发者ID:zteifel,项目名称:raspberry_remote,代码行数:18,代码来源:remote.py
示例17: __init__
class Loop:
def __init__(self):
self.ready = deque()
self.selector = DefaultSelector()
async def sock_recv(self, sock, maxbytes):
await read_wait(sock)
return sock.recv(maxbytes)
async def sock_accept(self, sock):
await read_wait(sock)
return sock.accept()
async def sock_sendall(self, sock, data):
while data:
try:
nsent = sock.send(data)
data = data[nsent:]
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.selector.select()
for key, _ in events:
self.ready.append(key.data)
self.selector.unregister(key.fileobj)
while self.ready:
self.current_task = self.ready.popleft()
try:
op, *args = self.current_task.send(None)
getattr(self, op)(*args)
except StopIteration:
pass
def read_wait(self, sock):
self.selector.register(sock, EVENT_READ, self.current_task)
def write_wait(self, sock):
self.selector.register(sock, EVENT_WRITE, self.current_task)
开发者ID:suzp1984,项目名称:parrot,代码行数:45,代码来源:play2.py
示例18: DefaultSelector
#python3.4 or higher is required in order to use selectors
import socket
from selectors import DefaultSelector, EVENT_READ, EVENT_WRITE
from datetime import datetime
sel = DefaultSelector()
request = "GET / HTTP/1.0\r\n\r\n"
request_callback = lambda sock: sock.send(request.encode())
response_callback = lambda sock: \
print((sock.recv(1000)).decode().split("\n")[-1], 'finish at %s' % str(datetime.now())[:-7])
def get():
sock = socket.socket()
sock.setblocking(False)
try:
sock.connect(('localhost', 3000))
except:
pass
sel.register(sock, EVENT_WRITE, lambda: request_callback(sock))
get_count = 4
print("starts at %s" % str(datetime.now())[:-7])
for i in range(get_count):
get()
while True:
events = sel.select()
for key, _ in events:
callback = key.data
event = key.events
开发者ID:pandafeeder,项目名称:python_stuff,代码行数:31,代码来源:non_coroutine_async_get.py
示例19: __init__
class EventLoop:
def __init__(self):
self.tasks = deque()
self.selector = DefaultSelector()
def run_until_complete(self, task):
self.tasks.append(task)
self.run()
def pause(self):
return "pause", None
def schedule(self, target):
return "schedule", target
def sock_accept(self, sock):
yield ("read", sock)
return sock.accept()
def sock_recv(self, sock):
yield ("read", sock)
return sock.recv(1024)
def sock_sendall(self, sock, data):
yield ("write", sock)
return sock.sendall(data)
def start_server(self, handler, host, port, backlog=0):
handler = partial(handler, self)
with socket.socket() as sock:
sock.bind((host, port))
sock.listen(backlog)
print("Listening on {}:{}".format(host, port))
while True:
conn, addr = yield from self.sock_accept(sock)
print("Accepted client from", addr)
yield self.schedule(handler(conn))
def run(self):
while self.tasks or self.selector.get_map():
for _ in range(len(self.tasks)):
try:
task = self.tasks.popleft()
tag, value = next(task)
if tag == "schedule":
self.tasks.append(value)
self.tasks.append(task)
elif tag == "read":
self.selector.register(value, EVENT_READ, data=task)
elif tag == "write":
self.selector.register(value, EVENT_WRITE, data=task)
elif tag == "pause":
self.tasks.append(task)
else:
raise ValueError("Incorrect tag")
except StopIteration:
continue
if self.selector.get_map():
for key, event in self.selector.select():
if event & EVENT_READ or event & EVENT_WRITE:
self.tasks.append(key.data)
self.selector.unregister(key.fileobj)
开发者ID:swarog46,项目名称:Python,代码行数:64,代码来源:file_server.py
示例20: selector
def selector():
sel = DefaultSelector()
sel.register(proc.stdout.channel, EVENT_READ)
while True:
for key, mask in sel.select():
yield
开发者ID:AinuX,项目名称:plumbum,代码行数:6,代码来源:paramiko_machine.py
注:本文中的selectors.DefaultSelector类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论