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


Python asyncio.current_task方法代碼示例

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


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

示例1: block_check

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import current_task [as 別名]
def block_check(loop):
    while True:
        try:
            time.sleep(1)
            future = asyncio.run_coroutine_threadsafe(asyncio.sleep(0), loop)
            blocked_for = 0
            while True:
                try:
                    future.result(1)
                    break
                except asyncio.TimeoutError:
                    blocked_for += 1
                    task = asyncio.current_task(loop)
                    buffer = io.StringIO()
                    task.print_stack(file=buffer)
                    buffer.seek(0)
                    log.warning("Event loop blocked for longer than %d seconds (%s)\n%s\n%s" % (
                        blocked_for,
                        str(task),
                        str(last_commands),
                        buffer.read()
                    ))
        except Exception:
            pass 
開發者ID:Xenon-Bot,項目名稱:xenon,代碼行數:26,代碼來源:bot.py

示例2: __aenter__

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import current_task [as 別名]
def __aenter__(self):
        if self._entered:
            raise RuntimeError(
                f"TaskGroup {self!r} has been already entered")
        self._entered = True

        if self._loop is None:
            self._loop = asyncio.get_running_loop()

        self._parent_task = asyncio.current_task(self._loop)
        if self._parent_task is None:
            raise RuntimeError(
                f'TaskGroup {self!r} cannot determine the parent task')
        self._patch_task(self._parent_task)

        return self 
開發者ID:edgedb,項目名稱:edgedb,代碼行數:18,代碼來源:taskgroup.py

示例3: get_asyncio_tasks

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import current_task [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

示例4: clean

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import current_task [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

示例5: _do_enter

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import current_task [as 別名]
def _do_enter(self) -> 'timeout':
        # Support Tornado 5- without timeout
        # Details: https://github.com/python/asyncio/issues/392
        if self._timeout is None:
            return self

        self._task = current_task(self._loop)
        if self._task is None:
            raise RuntimeError('Timeout context manager should be used '
                               'inside a task')

        if self._timeout <= 0:
            self._loop.call_soon(self._cancel_task)
            return self

        self._cancel_at = self._loop.time() + self._timeout
        self._cancel_handler = self._loop.call_at(
            self._cancel_at, self._cancel_task)
        return self 
開發者ID:TouwaStar,項目名稱:Galaxy_Plugin_Bethesda,代碼行數:21,代碼來源:__init__.py

示例6: __setattr__

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import current_task [as 別名]
def __setattr__(self, name, value):
        if name in ('_loop',):
            # Set normal attributes
            object.__setattr__(self, name, value)

        else:
            # Set task local attributes
            if _GTE_PY37:
                task = asyncio.current_task(loop=self._loop)
            else:
                task = asyncio.Task.current_task(loop=self._loop)
            if task is None:
                return None

            if not hasattr(task, 'context'):
                task.context = {}

            task.context[name] = value 
開發者ID:aws,項目名稱:aws-xray-sdk-python,代碼行數:20,代碼來源:async_context.py

示例7: __getattribute__

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import current_task [as 別名]
def __getattribute__(self, item):
        if item in ('_loop', 'clear'):
            # Return references to local objects
            return object.__getattribute__(self, item)

        if _GTE_PY37:
            task = asyncio.current_task(loop=self._loop)
        else:
            task = asyncio.Task.current_task(loop=self._loop)
        if task is None:
            return None

        if hasattr(task, 'context') and item in task.context:
            return task.context[item]

        raise AttributeError('Task context does not have attribute {0}'.format(item)) 
開發者ID:aws,項目名稱:aws-xray-sdk-python,代碼行數:18,代碼來源:async_context.py

示例8: task_factory

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import current_task [as 別名]
def task_factory(loop, coro):
    """
    Task factory function

    Fuction closely mirrors the logic inside of
    asyncio.BaseEventLoop.create_task. Then if there is a current
    task and the current task has a context then share that context
    with the new task
    """
    task = asyncio.Task(coro, loop=loop)
    if task._source_traceback:  # flake8: noqa
        del task._source_traceback[-1]  # flake8: noqa

    # Share context with new task if possible
    if _GTE_PY37:
        current_task = asyncio.current_task(loop=loop)
    else:
        current_task = asyncio.Task.current_task(loop=loop)
    if current_task is not None and hasattr(current_task, 'context'):
        setattr(task, 'context', current_task.context)

    return task 
開發者ID:aws,項目名稱:aws-xray-sdk-python,代碼行數:24,代碼來源:async_context.py

示例9: test_publish

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import current_task [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 current_task [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 current_task [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 current_task [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: __aenter__

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import current_task [as 別名]
def __aenter__(self):
        if self._entered:
            raise RuntimeError(
                f"TaskGroup {self!r} has been already entered")
        self._entered = True

        if self._loop is None:
            self._loop = asyncio.get_event_loop()

        if hasattr(asyncio, 'current_task'):
            self._parent_task = asyncio.current_task(self._loop)
        else:
            self._parent_task = asyncio.Task.current_task(self._loop)

        if self._parent_task is None:
            raise RuntimeError(
                f'TaskGroup {self!r} cannot determine the parent task')
        self._patch_task(self._parent_task)

        return self 
開發者ID:edgedb,項目名稱:edgedb-python,代碼行數:22,代碼來源:_taskgroup.py

示例14: _result_listener

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import current_task [as 別名]
def _result_listener(
        self,
        result_transport: TransportPool,
        timeout: float,
        rpc_message: RpcMessage,
        return_path: str,
        options: dict,
        result_queue: InternalQueue,
    ):
        try:
            logger.debug("Result listener is waiting")
            result = await asyncio.wait_for(
                result_transport.receive_result(
                    rpc_message=rpc_message, return_path=return_path, options=options
                ),
                timeout=timeout,
            )
        except asyncio.TimeoutError as e:
            logger.debug("Result listener timed out")
            await result_queue.put(e)
        else:
            logger.debug("Result listener received result, putting onto result queue")
            await result_queue.put(result)
        finally:
            self.listener_tasks.discard(asyncio.current_task()) 
開發者ID:adamcharnock,項目名稱:lightbus,代碼行數:27,代碼來源:rpc_result.py

示例15: promote

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import current_task [as 別名]
def promote(self, name, user, info=None):
        '''
        Promote the currently running task.
        '''
        task = asyncio.current_task()

        synt = getattr(task, '_syn_task', None)

        if synt is not None:

            if synt.root is None:
                return synt

            synt.root.kids.pop(synt.iden)
            synt.root = None
            return synt

        return await s_task.Task.anit(self, task, name, user, info=info) 
開發者ID:vertexproject,項目名稱:synapse,代碼行數:20,代碼來源:boss.py


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