當前位置: 首頁>>代碼示例>>Python>>正文


Python asyncio.tasks方法代碼示例

本文整理匯總了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. 
開發者ID:nokia,項目名稱:moler,代碼行數:24,代碼來源:asyncio_runner.py

示例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)) 
開發者ID:hbldh,項目名稱:bleak,代碼行數:22,代碼來源:__init__.py

示例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() 
開發者ID:fetchai,項目名稱:agents-aea,代碼行數:20,代碼來源:multiple_executor.py

示例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) 
開發者ID:fetchai,項目名稱:agents-aea,代碼行數:26,代碼來源:multiple_executor.py

示例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 
開發者ID:firdaus,項目名稱:cadence-python,代碼行數:26,代碼來源:decision_loop.py

示例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) 
開發者ID:nokia,項目名稱:moler,代碼行數:16,代碼來源:asyncio_runner.py

示例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) 
開發者ID:nokia,項目名稱:moler,代碼行數:13,代碼來源:asyncio_runner.py

示例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) 
開發者ID:nokia,項目名稱:moler,代碼行數:11,代碼來源:asyncio_runner.py

示例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()) 
開發者ID:fetchai,項目名稱:agents-aea,代碼行數:7,代碼來源:multiple_executor.py

示例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)
            ) 
開發者ID:fetchai,項目名稱:agents-aea,代碼行數:11,代碼來源:multiple_executor.py

示例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 
開發者ID:fetchai,項目名稱:agents-aea,代碼行數:8,代碼來源:multiple_executor.py

示例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) 
開發者ID:fetchai,項目名稱:agents-aea,代碼行數:15,代碼來源:multiple_executor.py

示例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 
開發者ID:fetchai,項目名稱:agents-aea,代碼行數:5,代碼來源:multiple_executor.py

示例14: _set_tasks

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import tasks [as 別名]
def _set_tasks(self) -> None:
        """Set run loop tasks."""
        raise NotImplementedError 
開發者ID:fetchai,項目名稱:agents-aea,代碼行數:5,代碼來源:agent_loop.py

示例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
        ) 
開發者ID:fetchai,項目名稱:agents-aea,代碼行數:7,代碼來源:agent_loop.py


注:本文中的asyncio.tasks方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。