本文整理汇总了Python中asyncio.tasks方法的典型用法代码示例。如果您正苦于以下问题:Python asyncio.tasks方法的具体用法?Python asyncio.tasks怎么用?Python asyncio.tasks使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类asyncio
的用法示例。
在下文中一共展示了asyncio.tasks方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: wait_for_iterator
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import tasks [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.
示例2: cli
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import tasks [as 别名]
def cli():
import argparse
from asyncio.tasks import ensure_future
loop = asyncio.get_event_loop()
parser = argparse.ArgumentParser(
description="Perform Bluetooth Low Energy device scan"
)
parser.add_argument("-i", dest="dev", default="hci0", help="HCI device")
parser.add_argument(
"-t", dest="timeout", type=int, default=5, help="Duration to scan for"
)
args = parser.parse_args()
out = loop.run_until_complete(
ensure_future(discover(device=args.dev, timeout=float(args.timeout)))
)
for o in out:
print(str(o))
示例3: __init__
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import tasks [as 别名]
def __init__(
self,
tasks: Sequence[AbstractExecutorTask],
task_fail_policy=ExecutorExceptionPolicies.propagate,
) -> None:
"""
Init executor.
:param tasks: sequence of AbstractExecutorTask instances to run.
:param task_fail_policy: the exception policy of all the tasks
"""
self._task_fail_policy: ExecutorExceptionPolicies = task_fail_policy
self._tasks: Sequence[AbstractExecutorTask] = tasks
self._is_running: bool = False
self._future_task: Dict[Awaitable, AbstractExecutorTask] = {}
self._loop: AbstractEventLoop = asyncio.new_event_loop()
self._executor_pool: Optional[Executor] = None
self._set_executor_pool()
示例4: _wait_tasks_complete
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import tasks [as 别名]
def _wait_tasks_complete(self, skip_exceptions: bool = False) -> None:
"""
Wait tasks execution to complete.
:param skip_exceptions: skip exceptions if raised in tasks
"""
done, pending = await asyncio.wait(
self._future_task.keys(), return_when=FIRST_EXCEPTION
)
async def wait_future(future):
try:
await future
except Exception as e:
if not skip_exceptions:
await self._handle_exception(self._future_task[future], e)
for future in done:
await wait_future(future)
if pending:
done, _ = await asyncio.wait(pending)
for task in done:
await wait_future(task)
示例5: query
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import tasks [as 别名]
def query(self, decision_task: PollForDecisionTaskResponse, query: WorkflowQuery) -> bytes:
query_args = query.query_args
if query_args is None:
args = []
else:
args = json_to_args(query_args)
task = QueryMethodTask(task_id=self.execution_id,
workflow_instance=self.workflow_task.workflow_instance,
query_name=query.query_type,
query_input=args,
decider=self)
self.tasks.append(task)
task.start()
self.event_loop.run_event_loop_once()
if task.status == Status.DONE:
if task.exception_thrown:
raise task.exception_thrown
else: # ret_value might be None, need to put it in else
return task.ret_value
else:
raise QueryDidNotComplete(f"Query method {query.query_type} with args {query.query_args} did not complete")
# noinspection PyUnusedLocal
示例6: cancel_remaining_feeders
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import tasks [as 别名]
def cancel_remaining_feeders(loop, logger_name="moler.runner.asyncio", in_shutdown=False):
remaining = [task for task in asyncio.Task.all_tasks(loop=loop) if (not task.done()) and (is_feeder(task))]
if remaining:
logger = logging.getLogger(logger_name)
loop_id = instance_id(loop)
log_level = logging.WARNING if in_shutdown else logging.DEBUG
logger.log(level=log_level, msg="cancelling all remaining feeders of loop {}:".format(loop_id))
remaining_tasks = asyncio.gather(*remaining, loop=loop, return_exceptions=True)
for feeder in remaining:
logger.log(level=log_level, msg=" remaining {}:{}".format(instance_id(feeder), feeder))
remaining_tasks.cancel()
if not loop.is_running():
# Keep the event loop running until it is either destroyed or all tasks have really terminated
loop.run_until_complete(remaining_tasks)
示例7: cleanup_remaining_tasks
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import tasks [as 别名]
def cleanup_remaining_tasks(loop, logger):
# https://stackoverflow.com/questions/30765606/whats-the-correct-way-to-clean-up-after-an-interrupted-event-loop
# https://medium.com/python-pandemonium/asyncio-coroutine-patterns-beyond-await-a6121486656f
# Handle shutdown gracefully by waiting for all tasks to be cancelled
all_tasks = [task for task in asyncio.Task.all_tasks(loop=loop)]
not_done_tasks = [task for task in asyncio.Task.all_tasks(loop=loop) if not task.done()]
if not_done_tasks:
logger.info("cancelling all remaining tasks")
# NOTE: following code cancels all tasks - possibly not ours as well
cleanup_selected_tasks(tasks2cancel=not_done_tasks, loop=loop, logger=logger)
示例8: cleanup_selected_tasks
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import tasks [as 别名]
def cleanup_selected_tasks(tasks2cancel, loop, logger):
logger.debug("tasks to cancel: {}".format(tasks2cancel))
remaining_tasks = asyncio.gather(*tasks2cancel, loop=loop, return_exceptions=True)
remaining_tasks.add_done_callback(lambda t: loop.stop())
remaining_tasks.cancel()
# Keep the event loop running until it is either destroyed or all
# tasks have really terminated
loop.run_until_complete(remaining_tasks)
示例9: start
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import tasks [as 别名]
def start(self) -> None:
"""Start tasks."""
self._is_running = True
self._start_tasks()
self._loop.run_until_complete(self._wait_tasks_complete())
示例10: stop
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import tasks [as 别名]
def stop(self) -> None:
"""Stop tasks."""
self._is_running = False
for task in self._tasks:
self._stop_task(task)
if not self._loop.is_running():
self._loop.run_until_complete(
self._wait_tasks_complete(skip_exceptions=True)
)
示例11: _start_tasks
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import tasks [as 别名]
def _start_tasks(self) -> None:
"""Schedule tasks."""
for task in self._tasks:
future = self._start_task(task)
task.future = future
self._future_task[future] = task
示例12: _make_executor
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import tasks [as 别名]
def _make_executor(
self, mode: str, fail_policy: ExecutorExceptionPolicies
) -> AbstractMultipleExecutor:
"""
Make an executor instance to run agents with.
:param mode: executor mode to use.
:param fail_policy: one of ExecutorExceptionPolicies to be used with Executor
:return: aea executor instance
"""
executor_cls = self.SUPPORTED_MODES[mode]
return executor_cls(tasks=self._make_tasks(), task_fail_policy=fail_policy)
示例13: _make_tasks
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import tasks [as 别名]
def _make_tasks(self) -> Sequence[AbstractExecutorTask]:
"""Make tasks to run with executor."""
raise NotImplementedError
示例14: _set_tasks
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import tasks [as 别名]
def _set_tasks(self) -> None:
"""Set run loop tasks."""
raise NotImplementedError
示例15: wait_run_loop_stopped
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import tasks [as 别名]
def wait_run_loop_stopped(self) -> None:
"""Wait all tasks stopped."""
return await asyncio.gather(
*self._tasks, loop=self._loop, return_exceptions=True
)