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


Python gen.coroutine函数代码示例

本文整理汇总了Python中tornado.gen.coroutine函数的典型用法代码示例。如果您正苦于以下问题:Python coroutine函数的具体用法?Python coroutine怎么用?Python coroutine使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


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

示例1: test_Militia

	def test_Militia(self):
		tu.print_test_header("test Militia")

		player2_discard_future = gen.Future()
		player3_discard_future = gen.Future()
		select_mock2 = unittest.mock.MagicMock(return_value=player2_discard_future)
		select_mock3 = unittest.mock.MagicMock(return_value=player3_discard_future)
		discard_mock2 =unittest.mock.Mock()
		discard_mock3 =unittest.mock.Mock()

		self.player2.select = select_mock2
		self.player3.select = select_mock3
		self.player2.discard = gen.coroutine(discard_mock2)
		self.player3.discard = gen.coroutine(discard_mock3)

		base.Militia(self.game, self.player1).play()
		self.assertTrue(select_mock2.called)
		self.assertTrue(select_mock3.called)
		select_mock2.assert_called_with(unittest.mock.ANY, unittest.mock.ANY, 
			crd.card_list_to_titles(self.player2.hand.card_array()), unittest.mock.ANY)

		player2_selection = crd.card_list_to_titles(self.player2.hand.card_array())[:2]
		player2_discard_future.set_result(player2_selection)
		yield gen.moment
		discard_mock2.assert_called_once_with(player2_selection, self.player2.discard_pile)
		self.assertTrue(self.player1.last_mode["mode"] == "wait")
		player3_selection = ["Copper", "Copper"]
		player3_discard_future.set_result(player3_selection)
		yield gen.moment
		discard_mock3.assert_called_once_with(player3_selection, self.player3.discard_pile)
开发者ID:HPRC,项目名称:Dominet,代码行数:30,代码来源:base_tests.py

示例2: coroutine

def coroutine(func, replace_callback=True):
    """Tornado-JSON compatible wrapper for ``tornado.gen.coroutine``

    Annotates original argspec.args of ``func`` as attribute ``__argspec_args``
    """
    # gen.coroutine in tornado 3.x.x and 5.x.x have a different signature than 4.x.x
    if TORNADO_MAJOR != 4:
        wrapper = gen.coroutine(func)
    else:
        wrapper = gen.coroutine(func, replace_callback)
    wrapper.__argspec_args = inspect.getargspec(func).args
    return wrapper
开发者ID:hfaran,项目名称:Tornado-JSON,代码行数:12,代码来源:gen.py

示例3: __init__

    def __init__(self, *args, **kwargs):
        super(Handler, self).__init__(*args, **kwargs)

        self.get_context  = self.application.asynchronize(self.get_context)

        self.can_get  = self.application.asynchronize(self.can_get)
        self.can_post = self.application.asynchronize(self.can_post)

        self.do_get   = gen.coroutine(self.do_get)
        self.do_post  = gen.coroutine(self.do_post)

        self.initkw = kwargs
开发者ID:veeloox,项目名称:ramen,代码行数:12,代码来源:handlers.py

示例4: test_singleton

 def test_singleton(self):
     # Class "constructor" reuses objects on the same IOLoop
     self.assertTrue(SimpleAsyncHTTPClient() is
                     SimpleAsyncHTTPClient())
     # unless force_instance is used
     self.assertTrue(SimpleAsyncHTTPClient() is not
                     SimpleAsyncHTTPClient(force_instance=True))
     # different IOLoops use different objects
     with closing(IOLoop()) as io_loop2:
         client1 = self.io_loop.run_sync(gen.coroutine(SimpleAsyncHTTPClient))
         client2 = io_loop2.run_sync(gen.coroutine(SimpleAsyncHTTPClient))
         self.assertTrue(client1 is not client2)
开发者ID:dkdenza,项目名称:tornado,代码行数:12,代码来源:simple_httpclient_test.py

示例5: generate_async

 def generate_async(self, **kwargs):
     namespace = self._get_namespace(**kwargs)
     exec_in(self.compiled, namespace)
     execute = gen.coroutine(namespace["_tt_execute"])
     linecache.clearcache()
     result = yield execute()
     return result
开发者ID:vuamitom,项目名称:tornado,代码行数:7,代码来源:template.py

示例6: wrap

    def wrap(f):
        # Stack up several decorators to allow us to access the generator
        # object itself.  In the innermost wrapper, we capture the generator
        # and save it in an attribute of self.  Next, we run the wrapped
        # function through @gen.coroutine.  Finally, the coroutine is
        # wrapped again to make it synchronous with run_sync.
        #
        # This is a good case study arguing for either some sort of
        # extensibility in the gen decorators or cancellation support.
        @functools.wraps(f)
        def pre_coroutine(self):
            result = f(self)
            if isinstance(result, types.GeneratorType):
                self._test_generator = result
            else:
                self._test_generator = None
            return result

        coro = gen.coroutine(pre_coroutine)

        @functools.wraps(coro)
        def post_coroutine(self):
            try:
                return self.io_loop.run_sync(
                    functools.partial(coro, self), timeout=timeout)
            except TimeoutError as e:
                # run_sync raises an error with an unhelpful traceback.
                # If we throw it back into the generator the stack trace
                # will be replaced by the point where the test is stopped.
                self._test_generator.throw(e)
                # In case the test contains an overly broad except clause,
                # we may get back here.  In this case re-raise the original
                # exception, which is better than nothing.
                raise
        return post_coroutine
开发者ID:Lozy,项目名称:tornado,代码行数:35,代码来源:testing.py

示例7: _

    def _(func):
        cor = gen.coroutine(func)

        def test_func():
            with pristine_loop() as loop:
                with check_active_rpc(loop, active_rpc_timeout):
                    s, workers = loop.run_sync(lambda: start_cluster(ncores, loop,
                                    Worker=Worker, scheduler_kwargs=scheduler_kwargs,
                                    worker_kwargs=worker_kwargs))
                    args = [s] + workers

                    if client:
                        e = Client((s.ip, s.port), loop=loop, start=False)
                        loop.run_sync(e._start)
                        args = [e] + args
                    try:
                        return loop.run_sync(lambda: cor(*args), timeout=timeout)
                    finally:
                        if client:
                            loop.run_sync(e._shutdown)
                        loop.run_sync(lambda: end_cluster(s, workers))

                    for w in workers:
                        assert not w._listen_streams

        return test_func
开发者ID:dask,项目名称:distributed,代码行数:26,代码来源:utils_test.py

示例8: wdb_tornado

def wdb_tornado(application, start_disabled=False):
    from tornado.web import RequestHandler, HTTPError
    from tornado import gen
    Wdb.enabled = not start_disabled

    class WdbOn(RequestHandler):
        def get(self):
            Wdb.enabled = True
            self.write('Wdb is now on')
    application.add_handlers(r'.*', ((r'/__wdb/on', WdbOn),))
    old_execute = RequestHandler._execute
    under = getattr(RequestHandler._execute, '__wrapped__', None)
    below = 1

    def _wdb_execute(*args, **kwargs):
        from wdb import trace, Wdb
        if Wdb.enabled:
            with trace(close_on_exit=True, below=below, under=under):
                old_execute(*args, **kwargs)
        else:
            old_execute(*args, **kwargs)
            # Close set_trace debuggers
            stop_trace(close_on_exit=True)

    RequestHandler._execute = gen.coroutine(_wdb_execute)

    def _wdb_error_writter(self, status_code, **kwargs):
        silent = False
        ex = kwargs.get('exc_info')
        if ex:
            silent = issubclass(ex[0], HTTPError)
        self.finish(_handle_off(silent=silent))

    RequestHandler.write_error = _wdb_error_writter
开发者ID:kaka19ace,项目名称:wdb,代码行数:34,代码来源:ext.py

示例9: test_func

 def test_func():
     with pristine_loop() as loop:
         cor = gen.coroutine(func)
         try:
             loop.run_sync(cor, timeout=timeout)
         finally:
             loop.stop()
开发者ID:dask,项目名称:distributed,代码行数:7,代码来源:utils_test.py

示例10: inner

 def inner():
     class Foo(object):
         pass
     local_var = Foo()
     self.local_ref = weakref.ref(local_var)
     yield gen.coroutine(lambda: None)()
     raise ValueError('Some error')
开发者ID:alexdxy,项目名称:tornado,代码行数:7,代码来源:gen_test.py

示例11: _

    def _(func):
        cor = gen.coroutine(func)

        def test_func():
            IOLoop.clear_instance()
            loop = IOLoop()
            loop.make_current()

            s, workers = loop.run_sync(lambda: start_cluster(ncores,
                                                             Worker=Worker))
            args = [s] + workers

            if executor:
                e = Executor((s.ip, s.port), loop=loop, start=False)
                loop.run_sync(e._start)
                args = [e] + args
            try:
                loop.run_sync(lambda: cor(*args), timeout=timeout)
            finally:
                if executor:
                    loop.run_sync(e._shutdown)
                loop.run_sync(lambda: end_cluster(s, workers))
                loop.stop()
                loop.close(all_fds=True)

        return test_func
开发者ID:danring,项目名称:distributed,代码行数:26,代码来源:utils_test.py

示例12: tracecoroutine

def tracecoroutine(f):
    @wraps(f)
    def wrapper(*a,**kw):
        g = f(*a,**kw)
        thing = None
        try:
            if not(hasattr(g,'send')):
                note('nogen?',f)
                return
            while True:
                thing = g.send(thing)
                try: thing = yield thing
                except Exception as e:
                    note('ex down',type(e))
                    thing = g.throw(e)
        except StopIteration: pass
        except gen.Return as e: 
            # why this isn't default, no idea.
            value = e.value
            while gen.is_future(value):
                value = yield value
            raise gen.Return(value)
        except Exit:
            raise
        except:
            note.alarm('error in ',f)
            traceback.print_exc()
            return
    return gen.coroutine(wrapper)
开发者ID:cyisfor,项目名称:gnunet-webserver,代码行数:29,代码来源:coro.py

示例13: coroutine

def coroutine(f):
    """A coroutine that accepts an optional callback.

    Given a callback, the function returns None, and the callback is run
    with (result, error). Without a callback the function returns a Future.
    """
    coro = gen.coroutine(f)

    @functools.wraps(f)
    def wrapper(*args, **kwargs):
        callback = kwargs.pop('callback', None)
        if callback and not callable(callback):
            raise CallbackTypeError()
        future = coro(*args, **kwargs)
        if callback:
            def _callback(_future):
                try:
                    result = _future.result()
                    callback(result, None)
                except Exception as e:
                    callback(None, e)

            future.add_done_callback(_callback)
        else:
            return future

    return wrapper
开发者ID:sevengram,项目名称:asyncdb,代码行数:27,代码来源:tornado.py

示例14: tornado_motor_sock_method

def tornado_motor_sock_method(method):
    """Decorator for socket-like methods on TornadoMotorSocket.

    The wrapper pauses the current greenlet while I/O is in progress,
    and uses the Tornado IOLoop to schedule the greenlet for resumption
    when I/O is ready.
    """
    coro = gen.coroutine(method)

    @functools.wraps(method)
    def wrapped(self, *args, **kwargs):
        child_gr = greenlet.getcurrent()
        main = child_gr.parent
        assert main is not None, "Should be on child greenlet"

        def callback(future):
            if future.exc_info():
                child_gr.throw(*future.exc_info())
            elif future.exception():
                child_gr.throw(future.exception())
            else:
                child_gr.switch(future.result())

        # Ensure the callback runs on the main greenlet.
        self.io_loop.add_future(coro(self, *args, **kwargs), callback)

        # Pause this greenlet until the coroutine finishes,
        # then return its result or raise its exception.
        return main.switch()

    return wrapped
开发者ID:sevengram,项目名称:asyncdb,代码行数:31,代码来源:tornado.py

示例15: _parent_process

def _parent_process(child_pipe):
    """ Simulate starting an AsyncProcess and then dying.

    The child_alive pipe is held open for as long as the child is alive, and can
    be used to determine if it exited correctly. """
    def parent_process_coroutine():
        worker_ready = mp_context.Event()

        worker = AsyncProcess(target=_worker_process,
                              args=(worker_ready, child_pipe))

        yield worker.start()

        # Wait for the child process to have started.
        worker_ready.wait()

        # Exit immediately, without doing any process teardown (including atexit
        # and 'finally:' blocks) as if by SIGKILL. This should cause
        # worker_process to also exit.
        os._exit(255)

    with pristine_loop() as loop:
        try:
            loop.run_sync(gen.coroutine(parent_process_coroutine), timeout=10)
        finally:
            loop.stop()

            raise RuntimeError("this should be unreachable due to os._exit")
开发者ID:tomMoral,项目名称:distributed,代码行数:28,代码来源:test_asyncprocess.py


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