本文整理汇总了Python中asyncio.FIRST_COMPLETED属性的典型用法代码示例。如果您正苦于以下问题:Python asyncio.FIRST_COMPLETED属性的具体用法?Python asyncio.FIRST_COMPLETED怎么用?Python asyncio.FIRST_COMPLETED使用的例子?那么恭喜您, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在类asyncio
的用法示例。
在下文中一共展示了asyncio.FIRST_COMPLETED属性的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: wait_for_first_response
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import FIRST_COMPLETED [as 别名]
def wait_for_first_response(tasks, converters):
"""given a list of unawaited tasks and non-coro result parsers to be called on the results,
this function returns the 1st result that is returned and converted
if it is possible for 2 tasks to complete at the same time,
only the 1st result deteremined by asyncio.wait will be returned
returns None if none successfully complete
returns 1st error raised if any occur (probably)
"""
primed = [wait_for_result(t, c) for t, c in zip(tasks, converters)]
done, pending = await asyncio.wait(primed, return_when=asyncio.FIRST_COMPLETED)
for p in pending:
p.cancel()
try:
return done.pop().result()
except NotImplementedError as e:
raise e
except:
return None
示例2: _handler
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import FIRST_COMPLETED [as 别名]
def _handler(self, websocket: websockets.WebSocketCommonProtocol, *unused_args):
"""Setup the consumer and producer response handlers with asyncio.
Args:
websocket: the websocket connection to the client
"""
asyncio.set_event_loop(self.loop)
consumer_task = asyncio.ensure_future(self._consumer_handler(websocket))
producer_task = asyncio.ensure_future(self._producer_handler(websocket))
done, pending = await asyncio.wait(
[consumer_task, producer_task], return_when=asyncio.FIRST_COMPLETED
)
for task in pending:
task.cancel()
示例3: stop
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import FIRST_COMPLETED [as 别名]
def stop(self):
"""Flush all pending data and close all connections to kafka cluster"""
if self._closed:
return
self._closed = True
# If the sender task is down there is no way for accumulator to flush
if self._sender is not None and self._sender.sender_task is not None:
await asyncio.wait([
self._message_accumulator.close(),
self._sender.sender_task],
return_when=asyncio.FIRST_COMPLETED,
loop=self._loop)
await self._sender.close()
await self.client.close()
log.debug("The Kafka producer has closed.")
示例4: _push_error_to_user
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import FIRST_COMPLETED [as 别名]
def _push_error_to_user(self, exc):
""" Most critical errors are not something we can continue execution
without user action. Well right now we just drop the Consumer, but
java client would certainly be ok if we just poll another time, maybe
it will need to rejoin, but not fail with GroupAuthorizationFailedError
till the end of days...
XXX: Research if we can't have the same error several times. For
example if user gets GroupAuthorizationFailedError and adds
permission for the group, would Consumer work right away or would
still raise exception a few times?
"""
exc = copy.copy(exc)
self._subscription.abort_waiters(exc)
self._pending_exception = exc
self._error_consumed_fut = create_future(loop=self._loop)
return asyncio.wait(
[self._error_consumed_fut, self._closing],
return_when=asyncio.FIRST_COMPLETED,
loop=self._loop
)
示例5: connect
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import FIRST_COMPLETED [as 别名]
def connect(self, timeout: Optional[float] = None) -> None:
"""Establish a connection with the WebSocket server.
Returns:
`(True, <chosen-subprotocol>)` if connection accepted.
`(False, None)` if connection rejected.
"""
connected = asyncio.Event()
self._message_processor = asyncio.ensure_future(
self._process_messages(connected, timeout or self.TIMEOUT)
)
await asyncio.wait(
[connected.wait(), self._message_processor],
return_when=asyncio.FIRST_COMPLETED,
)
if self._message_processor.done():
# Make sure to raise an exception from the task.
self._message_processor.result()
raise RuntimeError(f"Failed to connect to the server: {self._url}!")
示例6: onConnect
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import FIRST_COMPLETED [as 别名]
def onConnect (self, **kwargs):
self.logger.info ('connect', nick=self.nick, uuid='01f7b138-ea53-4609-88e9-61f3eca3e7e7')
self.send('NICK', nick=self.nick)
self.send('USER', user=self.nick, realname='https://github.com/PromyLOPh/crocoite')
# Don't try to join channels until the server has
# sent the MOTD, or signaled that there's no MOTD.
done, pending = await asyncio.wait(
[self.wait('RPL_ENDOFMOTD'), self.wait('ERR_NOMOTD')],
loop=self.loop, return_when=asyncio.FIRST_COMPLETED)
# Cancel whichever waiter's event didn't come in.
for future in pending:
future.cancel()
for c in self.channels:
self.logger.info ('join', channel=c, uuid='367063a5-9069-4025-907c-65ba88af8593')
self.send ('JOIN', channel=c)
# no need for NAMES here, server sends this automatically
示例7: poll
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import FIRST_COMPLETED [as 别名]
def poll(self, events, timeout=None,
return_when=asyncio.FIRST_COMPLETED):
"""Poll for any of a set of event types to be received for this session.
"""
awaitables = {}
for name in events:
awaitables[self.recv(name)] = name
done, pending = await asyncio.wait(
awaitables, timeout=timeout, return_when=return_when)
if done:
ev_dicts = []
for fut in done:
awaitables.pop(fut)
ev_dicts.append(fut.result())
return ev_dicts, awaitables.values()
else:
raise asyncio.TimeoutError(
"None of {} was received in {} seconds"
.format(events, timeout))
# call control / 'mod_commands' methods
# TODO: dynamically add @decorated functions to this class
# and wrap them using functools.update_wrapper ...?
示例8: cancellable_wait
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import FIRST_COMPLETED [as 别名]
def cancellable_wait(self, *awaitables: Awaitable[_R], timeout: float = None) -> _R:
futures = [asyncio.ensure_future(a, loop=self.loop) for a in awaitables + (self.wait(),)]
try:
done, pending = await asyncio.wait(
futures,
timeout=timeout,
return_when=asyncio.FIRST_COMPLETED,
loop=self.loop,
)
except CancelledError:
for future in futures:
future.cancel()
raise
for task in pending:
task.cancel()
await asyncio.wait(pending, return_when=asyncio.ALL_COMPLETED, loop=self.loop,)
if not done:
raise TimeoutError()
if self.triggered_token is not None:
for task in done:
task.exception()
raise OperationCancelled(f'Cancellation requested by {self.triggered_token} token')
return done.pop().result()
示例9: ws_handler
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import FIRST_COMPLETED [as 别名]
def ws_handler(self, request):
ws = web.WebSocketResponse()
await ws.prepare(request)
if self.ws is not None:
await self.ws.close()
self.ws = ws
_, unfinished = await asyncio.wait(
[
self._websocket_receive(ws),
self._websocket_send(ws)
],
return_when=asyncio.FIRST_COMPLETED
)
for task in unfinished:
task.cancel()
return ws
示例10: waiter
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import FIRST_COMPLETED [as 别名]
def waiter(client):
async def wait_for(*events, return_when=asyncio.FIRST_COMPLETED):
if not events:
return
done, pending = await asyncio.wait(
[client.wait(event) for event in events],
loop=client.loop,
return_when=return_when)
# Get the result(s) of the completed task(s).
ret = [future.result() for future in done]
# Cancel any events that didn't come in.
for future in pending:
future.cancel()
# Return list of completed event names.
return ret
return wait_for
# taken from :ref:`Patterns`
示例11: daemon
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import FIRST_COMPLETED [as 别名]
def daemon():
try_init_cgroup()
async with VJ4Session(config['server_url']) as session:
while True:
try:
await session.login_if_needed(config['uname'], config['password'])
done, pending = await wait([do_judge(session), do_noop(session)],
return_when=FIRST_COMPLETED)
for task in pending:
task.cancel()
await gather(*done)
except Exception as e:
logger.exception(e)
logger.info('Retrying after %d seconds', RETRY_DELAY_SEC)
await sleep(RETRY_DELAY_SEC)
示例12: _run
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import FIRST_COMPLETED [as 别名]
def _run(self):
first_completed = concurrent.FIRST_COMPLETED
if self._get_max_tasks() < 1:
raise RuntimeError("Executor has no workers")
try:
while not self.goal(self.learner):
futures = self._get_futures()
done, _ = concurrent.wait(futures, return_when=first_completed)
self._process_futures(done)
finally:
remaining = self._remove_unfinished()
if remaining:
concurrent.wait(remaining)
self._cleanup()
示例13: mqtt_connected
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import FIRST_COMPLETED [as 别名]
def mqtt_connected(func):
"""
MQTTClient coroutines decorator which will wait until connection before calling the decorated method.
:param func: coroutine to be called once connected
:return: coroutine result
"""
@asyncio.coroutine
@wraps(func)
def wrapper(self, *args, **kwargs):
if not self._connected_state.is_set():
base_logger.warning("Client not connected, waiting for it")
_, pending = yield from asyncio.wait([self._connected_state.wait(), self._no_more_connections.wait()], return_when=asyncio.FIRST_COMPLETED)
for t in pending:
t.cancel()
if self._no_more_connections.is_set():
raise ClientException("Will not reconnect")
return (yield from func(self, *args, **kwargs))
return wrapper
示例14: __call__
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import FIRST_COMPLETED [as 别名]
def __call__(self, receive: Callable, send: Callable) -> None:
request = self._create_request_from_scope(send)
receiver_task = asyncio.ensure_future(self.handle_messages(request, receive))
handler_task = asyncio.ensure_future(self.handle_request(request, send))
done, pending = await asyncio.wait(
[handler_task, receiver_task], return_when=asyncio.FIRST_COMPLETED
)
await _cancel_tasks(pending)
_raise_exceptions(done)
示例15: process
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import FIRST_COMPLETED [as 别名]
def process(self, queue, workflow):
try:
while queue.__futures__:
done, _ = await wait(queue.__futures__,
return_when=FIRST_COMPLETED)
queue.progress(done)
return workflow.result()
except CancelledError:
for task in queue.__futures__:
task.cancel()
await gather(*queue.__futures__)
raise