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


Python asyncio.futures方法代碼示例

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


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

示例1: wait_for_iterator

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

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import futures [as 別名]
def run_async_coroutine(self, coroutine_to_run, timeout):
        """Start coroutine in dedicated thread and await its result with timeout"""
        start_time = time.time()
        coro_future = self.start_async_coroutine(coroutine_to_run)
        # run_coroutine_threadsafe returns future as concurrent.futures.Future() and not asyncio.Future
        # so, we can await it with timeout inside current thread
        try:
            coro_result = coro_future.result(timeout=timeout)
            self.logger.debug("scheduled {} returned {}".format(coroutine_to_run, coro_result))
            return coro_result
        except concurrent.futures.TimeoutError:
            passed = time.time() - start_time
            raise MolerTimeout(timeout=timeout,
                               kind="run_async_coroutine({})".format(coroutine_to_run),
                               passed_time=passed)
        except concurrent.futures.CancelledError:
            raise 
開發者ID:nokia,項目名稱:moler,代碼行數:19,代碼來源:asyncio_runner.py

示例3: test_copy_state

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import futures [as 別名]
def test_copy_state(self):
        from asyncio.futures import _copy_future_state

        f = asyncio.Future(loop=self.loop)
        f.set_result(10)

        newf = asyncio.Future(loop=self.loop)
        _copy_future_state(f, newf)
        self.assertTrue(newf.done())
        self.assertEqual(newf.result(), 10)

        f_exception = asyncio.Future(loop=self.loop)
        f_exception.set_exception(RuntimeError())

        newf_exception = asyncio.Future(loop=self.loop)
        _copy_future_state(f_exception, newf_exception)
        self.assertTrue(newf_exception.done())
        self.assertRaises(RuntimeError, newf_exception.result)

        f_cancelled = asyncio.Future(loop=self.loop)
        f_cancelled.cancel()

        newf_cancelled = asyncio.Future(loop=self.loop)
        _copy_future_state(f_cancelled, newf_cancelled)
        self.assertTrue(newf_cancelled.cancelled()) 
開發者ID:Microvellum,項目名稱:Fluid-Designer,代碼行數:27,代碼來源:test_futures.py

示例4: _run_coroutine_threadsafe

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import futures [as 別名]
def _run_coroutine_threadsafe(coro, loop):
    """
    Patch to create task in the same thread instead of in the callback.
    This ensures that contextvars get copied. Python 3.7 copies contextvars
    without this.
    """
    if not asyncio.coroutines.iscoroutine(coro):
        raise TypeError("A coroutine object is required")
    future = concurrent.futures.Future()
    task = asyncio.ensure_future(coro, loop=loop)

    def callback() -> None:
        try:
            # noinspection PyProtectedMember,PyUnresolvedReferences
            # pylint:disable=protected-access
            asyncio.futures._chain_future(task, future)
        except Exception as exc:
            if future.set_running_or_notify_cancel():
                future.set_exception(exc)
            raise

    loop.call_soon_threadsafe(callback)
    return future 
開發者ID:open-telemetry,項目名稱:opentelemetry-python,代碼行數:25,代碼來源:aiocontextvarsfix.py

示例5: stream_from_fd

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import futures [as 別名]
def stream_from_fd(fd, loop):
    """Recieve a streamer for a given file descriptor."""
    reader = asyncio.StreamReader(loop=loop)
    protocol = asyncio.StreamReaderProtocol(reader, loop=loop)
    waiter = asyncio.futures.Future(loop=loop)

    transport = UnixFileDescriptorTransport(
        loop=loop,
        fileno=fd,
        protocol=protocol,
        waiter=waiter,
    )

    try:
        yield from waiter
    except Exception:
        transport.close()

    if loop.get_debug():
        logger.debug("Read fd %r connected: (%r, %r)", fd, transport, protocol)
    return reader, transport 
開發者ID:rbarrois,項目名稱:aionotify,代碼行數:23,代碼來源:aioutils.py

示例6: _run_coroutine_threadsafe

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import futures [as 別名]
def _run_coroutine_threadsafe(coro, loop):
        """
        Patch to create task in the same thread instead of in the callback. This ensures that contextvars get copied.
        Python 3.7 copies contextvars without this.
        """
        if not asyncio.coroutines.iscoroutine(coro):
            raise TypeError('A coroutine object is required')
        future = concurrent.futures.Future()  # type: concurrent.futures.Future

        # This is the only change to this function: Creating the task here, in the caller thread, instead of within
        # `callback`, which is executed in the loop's thread. This does not run the task; it just _creates_ it.
        task = asyncio.ensure_future(coro, loop=loop)

        def callback():
            try:
                # noinspection PyProtectedMember,PyUnresolvedReferences
                asyncio.futures._chain_future(task, future)  # type: ignore
            except Exception as exc:
                if future.set_running_or_notify_cancel():
                    future.set_exception(exc)
                raise

        loop.call_soon_threadsafe(callback)
        return future 
開發者ID:eventbrite,項目名稱:pysoa,代碼行數:26,代碼來源:compatibility.py

示例7: test_copy_state

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import futures [as 別名]
def test_copy_state(self):
        from asyncio.futures import _copy_future_state

        f = self._new_future(loop=self.loop)
        f.set_result(10)

        newf = self._new_future(loop=self.loop)
        _copy_future_state(f, newf)
        self.assertTrue(newf.done())
        self.assertEqual(newf.result(), 10)

        f_exception = self._new_future(loop=self.loop)
        f_exception.set_exception(RuntimeError())

        newf_exception = self._new_future(loop=self.loop)
        _copy_future_state(f_exception, newf_exception)
        self.assertTrue(newf_exception.done())
        self.assertRaises(RuntimeError, newf_exception.result)

        f_cancelled = self._new_future(loop=self.loop)
        f_cancelled.cancel()

        newf_cancelled = self._new_future(loop=self.loop)
        _copy_future_state(f_cancelled, newf_cancelled)
        self.assertTrue(newf_cancelled.cancelled()) 
開發者ID:bkerler,項目名稱:android_universal,代碼行數:27,代碼來源:test_futures.py

示例8: check_system_resources_limit

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import futures [as 別名]
def check_system_resources_limit(connection_observer, observer_lock, logger):
    # The number of file descriptors currently opened by this process
    curr_fds_open, curr_threads_nb = system_resources_usage()

    if curr_fds_open > max_open_files_limit_soft - 10:
        err_cause = "Can't run new asyncio loop - ALMOST REACHED MAX OPEN FILES LIMIT"
        msg = "{} ({}). Now {} FDs open, {} threads active.".format(err_cause, max_open_files_limit_soft,
                                                                    curr_fds_open, curr_threads_nb)
        logger.warning(msg)
        limit_exception = MolerException(msg)
        # make future done and observer done-with-exception
        with observer_lock:
            connection_observer.set_exception(limit_exception)
        # We need to return future informing "it's impossible to create new event loop"
        # However, it can't be asyncio.Future() since it requires event loop ;-)
        # We would get something like:
        #
        #    impossible_future = asyncio.Future()
        #  File "/opt/ute/python3/lib/python3.6/asyncio/events.py", line 676, in get_event_loop
        #    return get_event_loop_policy().get_event_loop()
        #  File "/opt/ute/python3/lib/python3.6/asyncio/events.py", line 584, in get_event_loop
        #    % threading.current_thread().name)
        # RuntimeError: There is no current event loop in thread 'Thread-5090'.
        #
        # So, we use concurrent.futures.Future - it has almost same API (duck typing for runner.wait_for() below)
        impossible_future = concurrent.futures.Future()
        impossible_future.set_result(None)
        return impossible_future
    return None 
開發者ID:nokia,項目名稱:moler,代碼行數:31,代碼來源:asyncio_runner.py

示例9: __process_message

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import futures [as 別名]
def __process_message(self, message: object) -> asyncio.futures:
        if self._props.receive_middleware_chain is not None:
            return await self._props.receive_middleware_chain(self._ensure_extras().context,
                                                              MessageEnvelope.wrap(message))
        if self._props.context_decorator_chain is not None:
            return await self._ensure_extras().context.receive(MessageEnvelope.wrap(message))

        self._message_or_envelope = message
        return await self.__default_receive() 
開發者ID:AsynkronIT,項目名稱:protoactor-python,代碼行數:11,代碼來源:actor_context.py

示例10: test_wrap_future

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import futures [as 別名]
def test_wrap_future(self):

        def run(arg):
            return (arg, threading.get_ident())
        ex = concurrent.futures.ThreadPoolExecutor(1)
        f1 = ex.submit(run, 'oi')
        f2 = asyncio.wrap_future(f1, loop=self.loop)
        res, ident = self.loop.run_until_complete(f2)
        self.assertIsInstance(f2, asyncio.Future)
        self.assertEqual(res, 'oi')
        self.assertNotEqual(ident, threading.get_ident()) 
開發者ID:Microvellum,項目名稱:Fluid-Designer,代碼行數:13,代碼來源:test_futures.py

示例11: test_wrap_future_use_global_loop

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import futures [as 別名]
def test_wrap_future_use_global_loop(self, m_events):
        def run(arg):
            return (arg, threading.get_ident())
        ex = concurrent.futures.ThreadPoolExecutor(1)
        f1 = ex.submit(run, 'oi')
        f2 = asyncio.wrap_future(f1)
        self.assertIs(m_events.get_event_loop.return_value, f2._loop) 
開發者ID:Microvellum,項目名稱:Fluid-Designer,代碼行數:9,代碼來源:test_futures.py

示例12: test_wrap_future_cancel

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import futures [as 別名]
def test_wrap_future_cancel(self):
        f1 = concurrent.futures.Future()
        f2 = asyncio.wrap_future(f1, loop=self.loop)
        f2.cancel()
        test_utils.run_briefly(self.loop)
        self.assertTrue(f1.cancelled())
        self.assertTrue(f2.cancelled()) 
開發者ID:Microvellum,項目名稱:Fluid-Designer,代碼行數:9,代碼來源:test_futures.py

示例13: test_wrap_future_cancel2

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import futures [as 別名]
def test_wrap_future_cancel2(self):
        f1 = concurrent.futures.Future()
        f2 = asyncio.wrap_future(f1, loop=self.loop)
        f1.set_result(42)
        f2.cancel()
        test_utils.run_briefly(self.loop)
        self.assertFalse(f1.cancelled())
        self.assertEqual(f1.result(), 42)
        self.assertTrue(f2.cancelled()) 
開發者ID:Microvellum,項目名稱:Fluid-Designer,代碼行數:11,代碼來源:test_futures.py

示例14: test_wrap_future_use_global_loop

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import futures [as 別名]
def test_wrap_future_use_global_loop(self):
        with mock.patch('asyncio.futures.events') as events:
            events.get_event_loop = lambda: self.loop
            def run(arg):
                return (arg, threading.get_ident())
            ex = concurrent.futures.ThreadPoolExecutor(1)
            f1 = ex.submit(run, 'oi')
            f2 = asyncio.wrap_future(f1)
            self.assertIs(self.loop, f2._loop) 
開發者ID:ShikyoKira,項目名稱:Project-New-Reign---Nemesis-Main,代碼行數:11,代碼來源:test_futures.py

示例15: test_wrap_future

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import futures [as 別名]
def test_wrap_future(self):

        def run(arg):
            return (arg, threading.get_ident())
        ex = concurrent.futures.ThreadPoolExecutor(1)
        f1 = ex.submit(run, 'oi')
        f2 = asyncio.wrap_future(f1, loop=self.loop)
        res, ident = self.loop.run_until_complete(f2)
        self.assertTrue(asyncio.isfuture(f2))
        self.assertEqual(res, 'oi')
        self.assertNotEqual(ident, threading.get_ident())
        ex.shutdown(wait=True) 
開發者ID:bkerler,項目名稱:android_universal,代碼行數:14,代碼來源:test_futures.py


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