本文整理汇总了Python中asyncio.Future方法的典型用法代码示例。如果您正苦于以下问题:Python asyncio.Future方法的具体用法?Python asyncio.Future怎么用?Python asyncio.Future使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类asyncio
的用法示例。
在下文中一共展示了asyncio.Future方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _patch_asyncio
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import Future [as 别名]
def _patch_asyncio() -> None:
# This patches asyncio to add a sync_wait method to the event
# loop. This method can then be called from within a task
# including a synchronous function called from a task. Sadly it
# requires the python Task and Future implementations, which
# invokes some performance cost.
asyncio.Task = asyncio.tasks._CTask = asyncio.tasks.Task = asyncio.tasks._PyTask # type: ignore
asyncio.Future = ( # type: ignore
asyncio.futures._CFuture # type: ignore
) = asyncio.futures.Future = asyncio.futures._PyFuture # type: ignore # noqa
current_policy = asyncio.get_event_loop_policy()
if hasattr(asyncio, "unix_events"):
target_policy = asyncio.unix_events._UnixDefaultEventLoopPolicy
else:
target_policy = object # type: ignore
if not isinstance(current_policy, target_policy):
raise RuntimeError("Flask Patching only works with the default event loop policy")
_patch_loop()
_patch_task()
示例2: _parse_sdcard_list
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import Future [as 别名]
def _parse_sdcard_list(self, done_cb):
self.log.debug('Comms: _parse_sdcard_list')
# setup callback to receive and parse listing data
files = []
f = asyncio.Future()
self.redirect_incoming(lambda x: self._rcv_sdcard_line(x, files, f))
# issue command
self._write('M20\n')
# wait for it to complete and get all the lines
# add a long timeout in case it fails and we don't want to wait for ever
try:
await asyncio.wait_for(f, 10)
except asyncio.TimeoutError:
self.log.warning("Comms: Timeout waiting for sd card list")
files = []
self.redirect_incoming(None)
# call upstream callback with results
done_cb(files)
示例3: wait_for_iterator
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import Future [as 别名]
def wait_for_iterator(self, connection_observer, connection_observer_future):
"""
Version of wait_for() intended to be used by Python3 to implement awaitable object.
Note: we don't have timeout parameter here. If you want to await with timeout please do use asyncio machinery.
For ex.: await asyncio.wait_for(connection_observer, timeout=10)
:param connection_observer: The one we are awaiting for.
:param connection_observer_future: Future of connection-observer returned from submit().
:return: iterator
"""
self.logger.debug("go foreground: {!r}".format(connection_observer))
# assuming that connection_observer.start() / runner.submit(connection_observer)
# has already scheduled future via asyncio.ensure_future
assert asyncio.futures.isfuture(connection_observer_future)
return connection_observer_future.__iter__()
# Note: even if code is so simple we can't move it inside ConnectionObserver.__await__() since different runners
# may provide different iterator implementing awaitable
# Here we know, connection_observer_future is asyncio.Future (precisely asyncio.tasks.Task)
# and we know it has __await__() method.
示例4: run_async_coroutine
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import Future [as 别名]
def run_async_coroutine(self, coroutine_to_run, timeout):
"""Start coroutine in dedicated thread and await its result with timeout"""
start_time = time.time()
coro_future = self.start_async_coroutine(coroutine_to_run)
# run_coroutine_threadsafe returns future as concurrent.futures.Future() and not asyncio.Future
# so, we can await it with timeout inside current thread
try:
coro_result = coro_future.result(timeout=timeout)
self.logger.debug("scheduled {} returned {}".format(coroutine_to_run, coro_result))
return coro_result
except concurrent.futures.TimeoutError:
passed = time.time() - start_time
raise MolerTimeout(timeout=timeout,
kind="run_async_coroutine({})".format(coroutine_to_run),
passed_time=passed)
except concurrent.futures.CancelledError:
raise
示例5: open
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import Future [as 别名]
def open(self):
"""Open TCP connection."""
self._debug('connecting to {}'.format(self))
# If a task is canceled while it is waiting for another concurrent operation,
# the task is notified of its cancellation by having a CancelledError exception
# raised at the point where it is waiting
try:
self._stream_reader, self._stream_writer = await asyncio.open_connection(host=self.host, port=self.port)
# self._stream_reader, self._stream_writer = await asyncio.wait_for(asyncio.open_connection(host=self.host, port=self.port), timeout=10)
except asyncio.CancelledError as err:
self._debug("CancelledError while awaiting for open_connection({}), err: {}".format(self, err))
# TODO: stop child task of asyncio.open_connection
raise
else:
self.connection_lost = asyncio.Future() # delayed to be created in same loop as open()
asyncio.ensure_future(self.forward_connection_read_data())
self._debug('connection {} is open'.format(self))
示例6: data_received
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import Future [as 别名]
def data_received(self, data, recv_time):
"""
Await initial prompt of started shell command.
After that - do real forward
"""
if not self._shell_operable.done():
decoded_data = self.moler_connection.decode(data)
self.logger.debug("<|{}".format(data))
assert isinstance(decoded_data, str)
self.read_buffer += decoded_data
if re.search(self.prompt, self.read_buffer, re.MULTILINE):
self._notify_on_connect()
self._shell_operable.set_result(True) # makes Future done
# TODO: should we remove initial prompt as it is inside raw.terminal?
# TODO: that way (maybe) we won't see it in logs
data_str = re.sub(self.prompt, '', self.read_buffer, re.MULTILINE)
data = self.moler_connection.encode(data_str)
else:
return
self.logger.debug("<|{}".format(data))
super(AsyncioTerminal, self).data_received(data)
示例7: channel
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import Future [as 别名]
def channel(key=None):
global _channel_futures
if key:
if key in _channel_futures:
return await _channel_futures[key]
future = asyncio.Future()
_channel_futures[key] = future
try:
channel = await (await _connect()).channel()
if key:
future.set_result(channel)
asyncio.get_event_loop().create_task(_wait_channel(channel, key))
return channel
except Exception as e:
future.set_exception(e)
del _channel_futures[key]
raise
示例8: wait_for
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import Future [as 别名]
def wait_for(self, event, predicate, result=None):
"""Waits for a DISPATCH'd event that meets the predicate.
Parameters
-----------
event: :class:`str`
The event name in all upper case to wait for.
predicate
A function that takes a data parameter to check for event
properties. The data parameter is the 'd' key in the JSON message.
result
A function that takes the same data parameter and executes to send
the result to the future. If ``None``, returns the data.
Returns
--------
asyncio.Future
A future to wait for.
"""
future = self.loop.create_future()
entry = EventListener(event=event, predicate=predicate, result=result, future=future)
self._dispatch_listeners.append(entry)
return future
示例9: admin_apps_approve
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import Future [as 别名]
def admin_apps_approve(
self, *, app_id: str = None, request_id: str = None, **kwargs
) -> Union[Future, SlackResponse]:
"""Approve an app for installation on a workspace.
Either app_id or request_id is required.
These IDs can be obtained either directly via the app_requested event,
or by the admin.apps.requests.list method.
Args:
app_id (str): The id of the app to approve. e.g. 'A12345'
request_id (str): The id of the request to approve. e.g. 'Ar12345'
Raises:
SlackRequestError: If neither or both the `app_id` and `request_id` args are specified.
"""
if app_id:
kwargs.update({"app_id": app_id})
elif request_id:
kwargs.update({"request_id": request_id})
else:
raise e.SlackRequestError(
"The app_id or request_id argument must be specified."
)
return self.api_call("admin.apps.approve", json=kwargs)
示例10: admin_teams_settings_setDefaultChannels
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import Future [as 别名]
def admin_teams_settings_setDefaultChannels(
self, *, team_id: str, channel_ids: Union[str, List[str]], **kwargs
) -> Union[Future, SlackResponse]:
"""Set the default channels of a workspace.
Args:
team_id (str): ID of the team.
channel_ids (str or list): A list of channel_ids.
At least one channel is required. e.g. ['C1A2B3C4D', 'C26Z25Y24']
"""
kwargs.update({"team_id": team_id})
if isinstance(channel_ids, list):
kwargs.update({"channel_ids": ",".join(channel_ids)})
else:
kwargs.update({"channel_ids": channel_ids})
return self.api_call(
"admin.teams.settings.setDefaultChannels", http_verb="GET", params=kwargs
)
示例11: admin_usergroups_addChannels
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import Future [as 别名]
def admin_usergroups_addChannels(
self,
*,
team_id: str,
usergroup_id: str,
channel_ids: Union[str, List[str]],
**kwargs
) -> Union[Future, SlackResponse]:
"""Add one or more default channels to an IDP group.
Args:
team_id (str): The workspace to add default channels in. e.g. 'T1234'
usergroup_id (str): ID of the IDP group to add default channels for. e.g. 'S1234'
channel_ids (str or list): Comma separated string of channel IDs. e.g. 'C123,C234' or ['C123', 'C234']
"""
kwargs.update({"team_id": team_id, "usergroup_id": usergroup_id})
if isinstance(channel_ids, list):
kwargs.update({"channel_ids": ",".join(channel_ids)})
else:
kwargs.update({"channel_ids": channel_ids})
return self.api_call("admin.usergroups.addChannels", json=kwargs)
示例12: admin_users_invite
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import Future [as 别名]
def admin_users_invite(
self, *, team_id: str, email: str, channel_ids: Union[str, List[str]], **kwargs
) -> Union[Future, SlackResponse]:
"""Invite a user to a workspace.
Args:
team_id (str): ID of the team. e.g. 'T1234'
email (str): The email address of the person to invite. e.g. 'joe@email.com'
channel_ids (str or list): A list of channel_ids for this user to join.
At least one channel is required. e.g. ['C1A2B3C4D', 'C26Z25Y24']
"""
kwargs.update({"team_id": team_id, "email": email})
if isinstance(channel_ids, list):
kwargs.update({"channel_ids": ",".join(channel_ids)})
else:
kwargs.update({"channel_ids": channel_ids})
return self.api_call("admin.users.invite", json=kwargs)
示例13: myFuture
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import Future [as 别名]
def myFuture(future):
await asyncio.sleep(1)
future.set_result("My Future Has Completed")
示例14: main
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import Future [as 别名]
def main():
future = asyncio.Future()
await asyncio.ensure_future(myFuture(future))
print(future.result())
示例15: __init__
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import Future [as 别名]
def __init__(self, *args, **kwargs):
self._loop = kwargs['loop'] if 'loop' in kwargs \
else asyncio.get_event_loop()
self._is_running = False
self._run_complete = asyncio.Future(loop = self._loop)