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


Python asyncio.all_tasks方法代碼示例

本文整理匯總了Python中asyncio.all_tasks方法的典型用法代碼示例。如果您正苦於以下問題:Python asyncio.all_tasks方法的具體用法?Python asyncio.all_tasks怎麽用?Python asyncio.all_tasks使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在asyncio的用法示例。


在下文中一共展示了asyncio.all_tasks方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: _cancel_all_tasks

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import all_tasks [as 別名]
def _cancel_all_tasks(loop: asyncio.AbstractEventLoop) -> None:
    tasks = [task for task in asyncio.all_tasks(loop) if not task.done()]
    if not tasks:
        return

    for task in tasks:
        task.cancel()
    loop.run_until_complete(asyncio.gather(*tasks, loop=loop, return_exceptions=True))

    for task in tasks:
        if not task.cancelled() and task.exception() is not None:
            loop.call_exception_handler(
                {
                    "message": "unhandled exception during shutdown",
                    "exception": task.exception(),
                    "task": task,
                }
            ) 
開發者ID:pgjones,項目名稱:quart,代碼行數:20,代碼來源:app.py

示例2: _threads

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import all_tasks [as 別名]
def _threads(self):
        threads = list(threading.enumerate())
        d = {
            "num_threads": len(threads),
            "threads": [
                {"name": t.name, "ident": t.ident, "daemon": t.daemon} for t in threads
            ],
        }
        # Only available in Python 3.7+
        if hasattr(asyncio, "all_tasks"):
            tasks = asyncio.all_tasks()
            d.update(
                {
                    "num_tasks": len(tasks),
                    "tasks": [_cleaner_task_str(t) for t in tasks],
                }
            )
        return d 
開發者ID:simonw,項目名稱:datasette,代碼行數:20,代碼來源:app.py

示例3: _patch_asyncio

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import all_tasks [as 別名]
def _patch_asyncio():
    """
    Patch asyncio module to use pure Python tasks and futures,
    use module level _current_tasks, all_tasks and patch run method.
    """
    def run(future, *, debug=False):
        loop = asyncio.get_event_loop()
        loop.set_debug(debug)
        return loop.run_until_complete(future)

    if sys.version_info >= (3, 6, 0):
        asyncio.Task = asyncio.tasks._CTask = asyncio.tasks.Task = \
            asyncio.tasks._PyTask
        asyncio.Future = asyncio.futures._CFuture = asyncio.futures.Future = \
            asyncio.futures._PyFuture
    if sys.version_info < (3, 7, 0):
        asyncio.tasks._current_tasks = asyncio.tasks.Task._current_tasks  # noqa
        asyncio.all_tasks = asyncio.tasks.Task.all_tasks  # noqa
    if not hasattr(asyncio, '_run_orig'):
        asyncio._run_orig = getattr(asyncio, 'run', None)
        asyncio.run = run 
開發者ID:erdewit,項目名稱:nest_asyncio,代碼行數:23,代碼來源:nest_asyncio.py

示例4: exception_handler

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import all_tasks [as 別名]
def exception_handler(loop, context):
    # first, handle with default handler
    loop.default_exception_handler(context)
    logger.debug('handle exception')
    exception = context.get('exception')
    logger.exception(exception)
    errors = (KeyboardInterrupt,)
    if isinstance(exception, errors):
        print(context)
        print('now exit loop')
        pending = asyncio.all_tasks(loop)
        for task in pending:
            task.cancel()
        try:
            loop.run_until_complete(asyncio.gather(
                *pending, loop=loop, return_exceptions=True))
        except:
            pass 
開發者ID:gxtrobot,項目名稱:aspider,代碼行數:20,代碼來源:aspider.py

示例5: get_asyncio_tasks

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import all_tasks [as 別名]
def get_asyncio_tasks(self, _):
        current = current_task()
        tasks = []
        for task in all_tasks():
            # Only in Python 3.8+ will we have a get_name function
            name = task.get_name() if hasattr(task, 'get_name') else getattr(task, 'name', f'Task-{id(task)}')

            task_dict = {"name": name,
                         "running": task == current,
                         "stack": [str(f) for f in task.get_stack()]}

            # Add info specific to tasks owner by TaskManager
            if hasattr(task, "start_time"):
                # Only TaskManager tasks have a start_time attribute
                cls, tsk = name.split(":")
                task_dict.update({"name": tsk, "taskmanager": cls, "start_time": task.start_time})
                if task.interval:
                    task_dict["interval"] = task.interval
            tasks.append(task_dict)
        return Response({"tasks": tasks}) 
開發者ID:Tribler,項目名稱:py-ipv8,代碼行數:22,代碼來源:asyncio_endpoint.py

示例6: deliver_messages

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import all_tasks [as 別名]
def deliver_messages(self, timeout=.1):
        """
        Allow peers to communicate.

        The strategy is as follows:
         1. Measure the amount of existing asyncio tasks
         2. After 10 milliseconds, check if we are below 2 tasks twice in a row
         3. If not, go back to handling calls (step 2) or return, if the timeout has been reached

        :param timeout: the maximum time to wait for messages to be delivered
        """
        rtime = 0
        probable_exit = False

        while (rtime < timeout):
            await sleep(.01)
            rtime += .01
            if len([task for task in all_tasks() if not self.is_background_task(task)]) < 2:
                if probable_exit:
                    break
                probable_exit = True
            else:
                probable_exit = False 
開發者ID:Tribler,項目名稱:py-ipv8,代碼行數:25,代碼來源:base.py

示例7: run

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import all_tasks [as 別名]
def run(self, *args, **kwargs):
        try:
            self.loop.run_until_complete(self.start(self.token))
        except KeyboardInterrupt:
            pass
        except discord.LoginFailure:
            logger.critical("Invalid token")
        except Exception:
            logger.critical("Fatal exception", exc_info=True)
        finally:
            self.loop.run_until_complete(self.logout())
            for task in asyncio.all_tasks(self.loop):
                task.cancel()
            try:
                self.loop.run_until_complete(asyncio.gather(*asyncio.all_tasks(self.loop)))
            except asyncio.CancelledError:
                logger.debug("All pending tasks has been cancelled.")
            finally:
                self.loop.run_until_complete(self.session.close())
                logger.error(" - Shutting down bot - ") 
開發者ID:kyb3r,項目名稱:modmail,代碼行數:22,代碼來源:bot.py

示例8: clean

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import all_tasks [as 別名]
def clean(hub, signal: int = None):
    '''
    Clean up the connections
    '''
    if signal:
        log.warning(f'Got signal {signal}! Cleaning up connections')
    coros = []
    # First clean up the remote systems
    for _, r_vals in hub.heist.ROSTERS.items():
        if not r_vals.get('bootstrap'):
            for t_name, vals in hub.heist.CONS.items():
                manager = vals['manager']
                coros.append(getattr(hub, f'heist.{manager}.clean')(t_name))
                await asyncio.gather(*coros)
    # Then shut down connections
    coros = []
    for t_name, vals in hub.heist.CONS.items():
        t_type = vals['t_type']
        coros.append(getattr(hub, f'tunnel.{t_type}.destroy')(t_name))
    await asyncio.gather(*coros)
    tasks = [t for t in asyncio.all_tasks() if t is not
             asyncio.current_task()]
    for task in tasks:
        log.warning('Task remains that were not cleaned up, shutting down violently')
        task.cancel() 
開發者ID:saltstack,項目名稱:heist,代碼行數:27,代碼來源:init.py

示例9: test_publish

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import all_tasks [as 別名]
def test_publish(
    mock_put, mock_queue, mock_sleep, mocker, mock_uuid, mock_choices, caplog
):
    with pytest.raises(RuntimeError):  # exhausted mock_uuid list
        await mayhem.publish(mock_queue)

    exp_mock_put_calls = [
        mocker.call(mayhem.PubSubMessage(message_id="1", instance_name="cattle-1234")),
        mocker.call(mayhem.PubSubMessage(message_id="2", instance_name="cattle-5678")),
        mocker.call(mayhem.PubSubMessage(message_id="3", instance_name="cattle-9876")),
    ]
    ret_tasks = [
        t for t in asyncio.all_tasks() if t is not asyncio.current_task()
    ]
    assert 3 == len(ret_tasks)
    assert 3 == len(caplog.records)
    mock_put.assert_not_called()
    await asyncio.gather(*ret_tasks)
    assert exp_mock_put_calls == mock_put.call_args_list 
開發者ID:econchick,項目名稱:mayhem,代碼行數:21,代碼來源:test_mayhem_full.py

示例10: test_consume

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import all_tasks [as 別名]
def test_consume(
    mock_get, mock_queue, message, create_mock_coro, caplog
):
    mock_get.side_effect = [message, Exception("break while loop")]
    mock_handle_message, _ = create_mock_coro("mayhem.handle_message")

    with pytest.raises(Exception, match="break while loop"):
        await mayhem.consume(mock_queue)

    ret_tasks = [
        t for t in asyncio.all_tasks() if t is not asyncio.current_task()
    ]
    assert 1 == len(ret_tasks)
    assert 1 == len(caplog.records)
    mock_handle_message.assert_not_called()
    await asyncio.gather(*ret_tasks)
    mock_handle_message.assert_called_once_with(message)


# avoid `loop.close` to actually _close_ when called in main code 
開發者ID:econchick,項目名稱:mayhem,代碼行數:22,代碼來源:test_mayhem_full.py

示例11: test_consume

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import all_tasks [as 別名]
def test_consume(mock_get, mock_queue, message, create_mock_coro):
    mock_get.side_effect = [message, Exception("break while loop")]
    mock_handle_message, _ = create_mock_coro("mayhem.handle_message")

    with pytest.raises(Exception, match="break while loop"):
        await mayhem.consume(mock_queue)

    ret_tasks = [
        t for t in asyncio.all_tasks() if t is not asyncio.current_task()
    ]
    # should be 1 per side effect minus the Exception (i.e. messages consumed)
    assert 1 == len(ret_tasks)
    mock_handle_message.assert_not_called()  # <-- sanity check

    # explicitly await tasks scheduled by `asyncio.create_task`
    await asyncio.gather(*ret_tasks)

    mock_handle_message.assert_called_once_with(message) 
開發者ID:econchick,項目名稱:mayhem,代碼行數:20,代碼來源:test_mayhem_5.py

示例12: shutdown

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import all_tasks [as 別名]
def shutdown(loop, executor, signal=None):
    """Cleanup tasks tied to the service's shutdown."""
    if signal:
        logging.info(f"Received exit signal {signal.name}...")
    logging.info("Closing database connections")
    logging.info("Nacking outstanding messages")
    tasks = [t for t in asyncio.all_tasks() if t is not
             asyncio.current_task()]

    [task.cancel() for task in tasks]

    logging.info(f"Cancelling {len(tasks)} outstanding tasks")
    await asyncio.gather(*tasks, return_exceptions=True)

    logging.info("Shutting down executor")
    executor.shutdown(wait=False)

    logging.info(f"Flushing metrics")
    loop.stop() 
開發者ID:econchick,項目名稱:mayhem,代碼行數:21,代碼來源:mayhem_4.py

示例13: test_unlock_with_watchdog_failed

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import all_tasks [as 別名]
def test_unlock_with_watchdog_failed(self):
        with asynctest.patch("aioredlock.algorithm.Redis", CoroutineMock) as mock_redis:
            mock_redis.set_lock = CoroutineMock(return_value=0.005)
            mock_redis.unset_lock = CoroutineMock(return_value=0.005)
            mock_redis.clear_connections = CoroutineMock()
            lock_manager = Aioredlock(internal_lock_timeout=1.0)

            lock = await lock_manager.lock("resource")
            await real_sleep(lock_manager.internal_lock_timeout)

            if sys.version_info.major == 3 and sys.version_info.minor <= 6:
                tasks = asyncio.Task.all_tasks()
            else:
                tasks = asyncio.all_tasks()
            for index, task in enumerate(tasks):
                if "_auto_extend" in str(task):
                    auto_frame = task.get_stack()[-1]
                    auto_frame.clear()

            await lock_manager.unlock(lock)
            assert lock.valid is False 
開發者ID:joanvila,項目名稱:aioredlock,代碼行數:23,代碼來源:test_algorithm.py

示例14: _no_asyncio_pending_tasks

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import all_tasks [as 別名]
def _no_asyncio_pending_tasks():
    """
    Ensure there are no unattended asyncio tasks after the test.

    It looks  both in the test's main event-loop, and in all other event-loops,
    such as the background thread of `KopfRunner` (used in e2e tests).

    Current solution uses some internals of asyncio, since there is no public
    interface for that. The warnings are printed only at the end of pytest.

    An alternative way: set event-loop's exception handler, force garbage
    collection after every test, and check messages from `asyncio.Task.__del__`.
    This, however, requires intercepting all event-loop creation in the code.
    """
    # See `asyncio.all_tasks()` implementation for reference.
    before = {t for t in list(asyncio.tasks._all_tasks) if not t.done()}
    yield
    after = {t for t in list(asyncio.tasks._all_tasks) if not t.done()}
    remains = after - before
    if remains:
        pytest.fail(f"Unattended asyncio tasks detected: {remains!r}") 
開發者ID:zalando-incubator,項目名稱:kopf,代碼行數:23,代碼來源:conftest.py

示例15: run

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import all_tasks [as 別名]
def run(self) -> None:
        self._logger.info('Starting async event loop thread')
        self._done.clear()
        asyncio.set_event_loop(self.loop)
        set_running_loop(self.loop)
        try:
            self._logger.info('Async event loop thread available and running')
            self.loop.run_forever()
        finally:
            try:
                pending_tasks = all_tasks(self.loop)
                if pending_tasks:
                    self._logger.info('Completing uncompleted async tasks')
                self.loop.run_until_complete(asyncio.gather(*pending_tasks))
            finally:
                self._logger.info('Closing async event loop')
                self.loop.close()
                # noinspection PyTypeChecker
                asyncio.set_event_loop(None)  # type: ignore
                set_running_loop(None)
                self._done.set() 
開發者ID:eventbrite,項目名稱:pysoa,代碼行數:23,代碼來源:event_loop.py


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