当前位置: 首页>>代码示例>>Python>>正文


Python asyncio.Task方法代码示例

本文整理汇总了Python中asyncio.Task方法的典型用法代码示例。如果您正苦于以下问题:Python asyncio.Task方法的具体用法?Python asyncio.Task怎么用?Python asyncio.Task使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在asyncio的用法示例。


在下文中一共展示了asyncio.Task方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _patch_asyncio

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import Task [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() 
开发者ID:pgjones,项目名称:quart,代码行数:24,代码来源:_patch.py

示例2: _patch_task

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import Task [as 别名]
def _patch_task() -> None:
    # Patch the asyncio task to allow it to be re-entered.
    def enter_task(loop, task):  # type: ignore
        asyncio.tasks._current_tasks[loop] = task

    asyncio.tasks._enter_task = enter_task  # type: ignore

    def leave_task(loop, task):  # type: ignore
        del asyncio.tasks._current_tasks[loop]

    asyncio.tasks._leave_task = leave_task  # type: ignore

    def step(self, exception=None):  # type: ignore
        current_task = asyncio.tasks._current_tasks.get(self._loop)
        try:
            self._Task__step_orig(exception)
        finally:
            if current_task is None:
                asyncio.tasks._current_tasks.pop(self._loop, None)
            else:
                asyncio.tasks._current_tasks[self._loop] = current_task

    asyncio.Task._Task__step_orig = asyncio.Task._Task__step  # type: ignore
    asyncio.Task._Task__step = step  # type: ignore 
开发者ID:pgjones,项目名称:quart,代码行数:26,代码来源:_patch.py

示例3: __init__

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import Task [as 别名]
def __init__(self, bot: Bot):
        super().__init__()

        self.bot = bot

        # Categories
        self.available_category: discord.CategoryChannel = None
        self.in_use_category: discord.CategoryChannel = None
        self.dormant_category: discord.CategoryChannel = None

        # Queues
        self.channel_queue: asyncio.Queue[discord.TextChannel] = None
        self.name_queue: t.Deque[str] = None

        self.name_positions = self.get_names()
        self.last_notification: t.Optional[datetime] = None

        # Asyncio stuff
        self.queue_tasks: t.List[asyncio.Task] = []
        self.ready = asyncio.Event()
        self.on_message_lock = asyncio.Lock()
        self.init_task = self.bot.loop.create_task(self.init_cog()) 
开发者ID:python-discord,项目名称:bot,代码行数:24,代码来源:help_channels.py

示例4: wait_for_iterator

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import Task [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

示例5: __new__

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import Task [as 别名]
def __new__(cls, name, bases, attrs, **kwargs):
        """ put the :class:`~peony.commands.tasks.Task`s in the right place """
        tasks = {'tasks': set()}

        for base in bases:
            if hasattr(base, '_tasks'):
                for key, value in base._tasks.items():
                    tasks[key] |= value

        for attr in attrs.values():
            if isinstance(attr, task):
                tasks['tasks'].add(attr)

        attrs['_tasks'] = tasks
        attrs['_streams'] = EventStreams()

        return super().__new__(cls, name, bases, attrs) 
开发者ID:odrling,项目名称:peony-twitter,代码行数:19,代码来源:client.py

示例6: test_changes_continuous_reading

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import Task [as 别名]
def test_changes_continuous_reading(self):
        ids = [utils.uuid() for _ in range(3)]

        @asyncio.coroutine
        def task():
            for idx in ids:
                yield from self.db[idx].update({})
        asyncio.Task(task())

        with (yield from self.db.changes(feed='continuous',
                                         timeout=1000)) as feed:

            while True:
                self.assertTrue(feed.is_active())
                event = yield from feed.next()
                if event is None:
                    break
                self.assertIsInstance(event, dict)
                self.assertIn(event['id'], ids)

            self.assertFalse(feed.is_active()) 
开发者ID:aio-libs,项目名称:aiocouchdb,代码行数:23,代码来源:test_database.py

示例7: test_changes_eventsource

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import Task [as 别名]
def test_changes_eventsource(self):
        ids = [utils.uuid() for _ in range(3)]

        @asyncio.coroutine
        def task():
            for idx in ids:
                yield from self.db[idx].update({})
        asyncio.Task(task())

        with (yield from self.db.changes(feed='eventsource',
                                         timeout=1000)) as feed:

            while True:
                self.assertTrue(feed.is_active())
                event = yield from feed.next()
                if event is None:
                    break
                self.assertIsInstance(event, dict)
                self.assertIn(event['id'], ids) 
开发者ID:aio-libs,项目名称:aiocouchdb,代码行数:21,代码来源:test_database.py

示例8: _patch_asyncio

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import Task [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

示例9: __init__

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import Task [as 别名]
def __init__(self,
                 impl:           SubscriberImpl[MessageClass],
                 loop:           asyncio.AbstractEventLoop,
                 queue_capacity: typing.Optional[int]):
        """
        Do not call this directly! Use :meth:`Presentation.make_subscriber`.
        """
        if queue_capacity is None:
            queue_capacity = 0      # This case is defined by the Queue API. Means unlimited.
        else:
            queue_capacity = int(queue_capacity)
            if queue_capacity < 1:
                raise ValueError(f'Invalid queue capacity: {queue_capacity}')

        self._closed = False
        self._impl = impl
        self._loop = loop
        self._maybe_task: typing.Optional[asyncio.Task[None]] = None
        self._rx: _Listener[MessageClass] = _Listener(asyncio.Queue(maxsize=queue_capacity, loop=loop))
        impl.add_listener(self._rx)

    # ----------------------------------------  HANDLER-BASED API  ---------------------------------------- 
开发者ID:UAVCAN,项目名称:pyuavcan,代码行数:24,代码来源:_subscriber.py

示例10: __init__

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import Task [as 别名]
def __init__(self,
                 dtype:                            typing.Type[ServiceClass],
                 input_transport_session:          pyuavcan.transport.InputSession,
                 output_transport_session_factory: OutputTransportSessionFactory,
                 finalizer:                        TypedSessionFinalizer,
                 loop:                             asyncio.AbstractEventLoop):
        """
        Do not call this directly! Use :meth:`Presentation.get_server`.
        """
        self._dtype = dtype
        self._input_transport_session = input_transport_session
        self._output_transport_session_factory = output_transport_session_factory
        self._finalizer = finalizer
        self._loop = loop

        self._output_transport_sessions: typing.Dict[int, pyuavcan.transport.OutputSession] = {}
        self._maybe_task: typing.Optional[asyncio.Task[None]] = None
        self._closed = False
        self._send_timeout = DEFAULT_SERVICE_REQUEST_TIMEOUT

        self._served_request_count = 0
        self._deserialization_failure_count = 0
        self._malformed_request_count = 0

    # ----------------------------------------  MAIN API  ---------------------------------------- 
开发者ID:UAVCAN,项目名称:pyuavcan,代码行数:27,代码来源:_server.py

示例11: create_utilitary_tasks

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import Task [as 别名]
def create_utilitary_tasks(loop):
    tasks = []

    stats_printer_task = asyncio.Task(stats_printer())
    tasks.append(stats_printer_task)

    if config.USE_MIDDLE_PROXY:
        middle_proxy_updater_task = asyncio.Task(update_middle_proxy_info())
        tasks.append(middle_proxy_updater_task)

        if config.GET_TIME_PERIOD:
            time_get_task = asyncio.Task(get_srv_time())
            tasks.append(time_get_task)

    get_cert_len_task = asyncio.Task(get_mask_host_cert_len())
    tasks.append(get_cert_len_task)

    clear_resolving_cache_task = asyncio.Task(clear_ip_resolving_cache())
    tasks.append(clear_resolving_cache_task)

    return tasks 
开发者ID:alexbers,项目名称:mtprotoproxy,代码行数:23,代码来源:mtprotoproxy.py

示例12: _patch_task

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import Task [as 别名]
def _patch_task(self, task):
        # In Python 3.8 we'll need proper API on asyncio.Task to
        # make TaskGroups possible. We need to be able to access
        # information about task cancellation, more specifically,
        # we need a flag to say if a task was cancelled or not.
        # We also need to be able to flip that flag.

        def _task_cancel(task, orig_cancel):
            task.__cancel_requested__ = True
            return orig_cancel()

        if hasattr(task, '__cancel_requested__'):
            return

        task.__cancel_requested__ = False
        # confirm that we were successful at adding the new attribute:
        assert not task.__cancel_requested__

        orig_cancel = task.cancel
        task.cancel = functools.partial(_task_cancel, task, orig_cancel) 
开发者ID:edgedb,项目名称:edgedb,代码行数:22,代码来源:taskgroup.py

示例13: test_proxy_connect_http

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import Task [as 别名]
def test_proxy_connect_http(loop):
    tr, proto = mock.Mock(name='transport'), mock.Mock(name='protocol')
    loop_mock = mock.Mock()
    loop_mock.getaddrinfo = make_mocked_coro([
        [0, 0, 0, 0, ['127.0.0.1', 1080]]])
    loop_mock.create_connection = make_mocked_coro((tr, proto))
    loop_mock.create_task.return_value = asyncio.Task(
        make_mocked_coro([
            {'host': 'host', 'port': 80, 'family': 1,
             'hostname': 'hostname', 'flags': 11, 'proto': 'proto'}])())

    req = ProxyClientRequest(
        'GET', URL('http://python.org'), loop=loop,
        proxy=URL('http://127.0.0.1'))
    connector = ProxyConnector(loop=loop_mock)

    await connector.connect(req, [], ClientTimeout()) 
开发者ID:nibrag,项目名称:aiosocks,代码行数:19,代码来源:test_connector.py

示例14: __init__

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import Task [as 别名]
def __init__(
        self, max_active: int = 0, timed: bool = False, trace_fn: Callable = None
    ):
        """
        Initialize the task queue.

        Args:
            max_active: The maximum number of tasks to automatically run
            timed: A flag indicating that timing should be collected for tasks
            trace_fn: A callback for all completed tasks
        """
        self.loop = asyncio.get_event_loop()
        self.active_tasks = []
        self.pending_tasks = []
        self.timed = timed
        self.total_done = 0
        self.total_failed = 0
        self.total_started = 0
        self._trace_fn = trace_fn
        self._cancelled = False
        self._drain_evt = asyncio.Event()
        self._drain_task: asyncio.Task = None
        self._max_active = max_active 
开发者ID:hyperledger,项目名称:aries-cloudagent-python,代码行数:25,代码来源:task_queue.py

示例15: add_active

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import Task [as 别名]
def add_active(
        self,
        task: asyncio.Task,
        task_complete: Callable = None,
        ident: str = None,
        timing: dict = None,
    ) -> asyncio.Task:
        """
        Register an active async task with an optional completion callback.

        Args:
            task: The asyncio task instance
            task_complete: An optional callback to run on completion
            ident: A string identifer for the task
            timing: An optional dictionary of timing information
        """
        self.active_tasks.append(task)
        task.add_done_callback(
            lambda fut: self.completed_task(task, task_complete, ident, timing)
        )
        self.total_started += 1
        return task 
开发者ID:hyperledger,项目名称:aries-cloudagent-python,代码行数:24,代码来源:task_queue.py


注:本文中的asyncio.Task方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。