當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。