Python asyncio 模块,set_event_loop() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用asyncio.set_event_loop()

项目:dabdabrevolution    作者:harryparkdotio    | 项目源码 | 文件源码
def run(self, handler):
        import asyncio
        from aiohttp.wsgi import WSGIServerHttpProtocol
        self.loop = self.get_event_loop()
        asyncio.set_event_loop(self.loop)

        protocol_factory = lambda: WSGIServerHttpProtocol(
            handler,
            readpayload=True,
            debug=(not self.quiet))
        self.loop.run_until_complete(self.loop.create_server(protocol_factory,
                                                             self.host,
                                                             self.port))

        if 'BOTTLE_CHILD' in os.environ:
            import signal
            signal.signal(signal.SIGINT, lambda s, f: self.loop.stop())

        try:
            self.loop.run_forever()
        except KeyboardInterrupt:
            self.loop.stop()
项目:MusicPlayer    作者:HuberTRoy    | 项目源码 | 文件源码
def start():
    app = QApplication(sys.argv)

    # ?Qt??????asyncio??????
    # QEventLoop??Qt???????
    # ??asyncio????????
    eventLoop = QEventLoop(app)
    asyncio.set_event_loop(eventLoop)
    main = Window()

    main.show()
    # ??????????
    # ????????????????
    # ??????show???????
    # ????????????????
    main.playWidgets.currentMusic.resize(main.navigation.width(), 64)

    with eventLoop:
        eventLoop.run_forever()

    sys.exit(0)
项目:Main    作者:N-BodyPhysicsSimulator    | 项目源码 | 文件源码
def handle(self, generator):
        self.clients = []

        async def server(client, _):
            self.clients.append(client)

            for state in generator:
                await client.send(json.dumps(state.to_dict()))

        asyncio.set_event_loop(
            asyncio.new_event_loop()
        )

        asyncio.get_event_loop().run_until_complete(
            websockets.serve(server, self.args.get('ws_host'), self.args.get('ws_port'))
        )

        asyncio.get_event_loop().run_forever()
项目:annotated-py-asyncio    作者:hhstore    | 项目源码 | 文件源码
def main():
    asyncio.set_event_loop(None)
    if args.iocp:
        from asyncio.windows_events import ProactorEventLoop
        loop = ProactorEventLoop()
    else:
        loop = asyncio.new_event_loop()
    sslctx = None
    if args.tls:
        sslctx = test_utils.dummy_ssl_context()
    cache = CacheClient(args.host, args.port, sslctx=sslctx, loop=loop)
    try:
        loop.run_until_complete(
            asyncio.gather(
                *[testing(i, cache, loop) for i in range(args.ntasks)],
                loop=loop))
    finally:
        loop.close()
项目:annotated-py-asyncio    作者:hhstore    | 项目源码 | 文件源码
def test_create_task(self):
        class MyTask(asyncio.Task):
            pass

        @asyncio.coroutine
        def test():
            pass

        class EventLoop(base_events.BaseEventLoop):
            def create_task(self, coro):
                return MyTask(coro, loop=loop)

        loop = EventLoop()
        self.set_event_loop(loop)

        coro = test()
        task = asyncio.async(coro, loop=loop)
        self.assertIsInstance(task, MyTask)

        # make warnings quiet
        task._log_destroy_pending = False
        coro.close()
项目:annotated-py-asyncio    作者:hhstore    | 项目源码 | 文件源码
def test_task_class(self):
        @asyncio.coroutine
        def notmuch():
            return 'ok'
        t = asyncio.Task(notmuch(), loop=self.loop)
        self.loop.run_until_complete(t)
        self.assertTrue(t.done())
        self.assertEqual(t.result(), 'ok')
        self.assertIs(t._loop, self.loop)

        loop = asyncio.new_event_loop()
        self.set_event_loop(loop)
        t = asyncio.Task(notmuch(), loop=loop)
        self.assertIs(t._loop, loop)
        loop.run_until_complete(t)
        loop.close()
项目:annotated-py-asyncio    作者:hhstore    | 项目源码 | 文件源码
def test_async_coroutine(self):
        @asyncio.coroutine
        def notmuch():
            return 'ok'
        t = asyncio.async(notmuch(), loop=self.loop)
        self.loop.run_until_complete(t)
        self.assertTrue(t.done())
        self.assertEqual(t.result(), 'ok')
        self.assertIs(t._loop, self.loop)

        loop = asyncio.new_event_loop()
        self.set_event_loop(loop)
        t = asyncio.async(notmuch(), loop=loop)
        self.assertIs(t._loop, loop)
        loop.run_until_complete(t)
        loop.close()
项目:annotated-py-asyncio    作者:hhstore    | 项目源码 | 文件源码
def test_async_future(self):
        f_orig = asyncio.Future(loop=self.loop)
        f_orig.set_result('ko')

        f = asyncio.async(f_orig)
        self.loop.run_until_complete(f)
        self.assertTrue(f.done())
        self.assertEqual(f.result(), 'ko')
        self.assertIs(f, f_orig)

        loop = asyncio.new_event_loop()
        self.set_event_loop(loop)

        with self.assertRaises(ValueError):
            f = asyncio.async(f_orig, loop=loop)

        loop.close()

        f = asyncio.async(f_orig, loop=self.loop)
        self.assertIs(f, f_orig)
项目:annotated-py-asyncio    作者:hhstore    | 项目源码 | 文件源码
def test_cancel_current_task(self):
        loop = asyncio.new_event_loop()
        self.set_event_loop(loop)

        @asyncio.coroutine
        def task():
            t.cancel()
            self.assertTrue(t._must_cancel)  # White-box test.
            # The sleep should be cancelled immediately.
            yield from asyncio.sleep(100, loop=loop)
            return 12

        t = asyncio.Task(task(), loop=loop)
        self.assertRaises(
            asyncio.CancelledError, loop.run_until_complete, t)
        self.assertTrue(t.done())
        self.assertFalse(t._must_cancel)  # White-box test.
        self.assertFalse(t.cancel())
项目:annotated-py-asyncio    作者:hhstore    | 项目源码 | 文件源码
def test_constructor_loop_selection(self):
        @asyncio.coroutine
        def coro():
            return 'abc'
        gen1 = coro()
        gen2 = coro()
        fut = asyncio.gather(gen1, gen2)
        self.assertIs(fut._loop, self.one_loop)
        self.one_loop.run_until_complete(fut)

        self.set_event_loop(self.other_loop, cleanup=False)
        gen3 = coro()
        gen4 = coro()
        fut2 = asyncio.gather(gen3, gen4, loop=self.other_loop)
        self.assertIs(fut2._loop, self.other_loop)
        self.other_loop.run_until_complete(fut2)
项目:aschedule    作者:eightnoteight    | 项目源码 | 文件源码
def test_every_param_loop(self):
        asyncio.set_event_loop(None)
        # scheduled executions 1, 3, 5, 7, 9
        schedule = self.schedule_manager.every(self.get_coroutine,
                                               timedelta(seconds=2),
                                               datetime.now() + timedelta(seconds=1),
                                               loop=self.loop)
        # will be cancelled at
        cancel_in_seconds = 10

        async def cancel_schedule():
            await asyncio.sleep(cancel_in_seconds, loop=self.loop)
            self.schedule_manager.cancel(schedule, running_jobs=True)

        try:
            self.loop.run_until_complete(
                asyncio.gather(cancel_schedule(), schedule.future, loop=self.loop))
        except asyncio.CancelledError:
            pass

        # making sure that all running jobs and the schedule are cancelled
        self.loop.run_until_complete(asyncio.sleep(10, loop=self.loop))
        self.assertEqual(5, self.count)
        asyncio.set_event_loop(self.loop)
项目:aschedule    作者:eightnoteight    | 项目源码 | 文件源码
def test_once_at_param_loop(self):
        asyncio.set_event_loop(None)
        start = self.loop.time()
        times = []
        cancel_in_seconds = 10
        async def record_times():
            times.append(round(self.loop.time() - start))

        async def cancel_schedule():
            await asyncio.sleep(cancel_in_seconds, loop=self.loop)
            # should report an error that the given schedule doesn't belong to this schedule manager
            # as the schedule is completed before this arises
            with self.assertRaises(aschedule.AScheduleException):
                self.schedule_manager.cancel(schedule, running_jobs=True)

        schedule = self.schedule_manager.once_at(record_times,
                                                 datetime.now() + timedelta(seconds=5),
                                                 loop=self.loop)
        self.loop.run_until_complete(
            asyncio.gather(cancel_schedule(), schedule.future, loop=self.loop))

        # making sure that all running jobs and the schedule are cancelled
        self.loop.run_until_complete(asyncio.sleep(10, loop=self.loop))
        self.assertEqual([5], times)
        asyncio.set_event_loop(self.loop)
项目:warriorframework    作者:warriorframework    | 项目源码 | 文件源码
def run(self, handler):
        import asyncio
        from aiohttp.wsgi import WSGIServerHttpProtocol
        self.loop = asyncio.new_event_loop()
        asyncio.set_event_loop(self.loop)

        protocol_factory = lambda: WSGIServerHttpProtocol(
            handler,
            readpayload=True,
            debug=(not self.quiet))
        self.loop.run_until_complete(self.loop.create_server(protocol_factory,
                                                             self.host,
                                                             self.port))

        if 'BOTTLE_CHILD' in os.environ:
            import signal
            signal.signal(signal.SIGINT, lambda s, f: self.loop.stop())

        try:
            self.loop.run_forever()
        except KeyboardInterrupt:
            self.loop.stop()
项目:aiossdb    作者:Microndgt    | 项目源码 | 文件源码
def __init__(self, address, *, password=None, parser=None, encoding=None, minsize, maxsize,
                 connection_cls=None, timeout=None, loop=None):
        assert isinstance(minsize, int) and minsize >= 0, ("minsize must be int >=0", minsize, type(minsize))
        assert isinstance(maxsize, int) and maxsize >= minsize, (
            "maxsize must be int >= minsize", maxsize, type(maxsize), minsize)
        if loop is None:
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)
        self._address = address
        self._password = password
        self._parser_class = parser
        self._timeout = timeout
        self._loop = loop
        self._used = set()
        self._connection_cls = connection_cls
        self._pool = collections.deque(maxlen=maxsize)
        self._minsize = minsize
        self._maxsize = maxsize
        self._encoding = encoding
        # ??release?????????????????????????????
        self._cond = asyncio.Condition(lock=asyncio.Lock(loop=loop), loop=loop)
        self._waiter = None
        self._closing = False
        self._closed = False
项目:Auspex    作者:BBN-Q    | 项目源码 | 文件源码
def run(self):
            self._loop = zmq.asyncio.ZMQEventLoop()
            asyncio.set_event_loop(self._loop)
            self.context = zmq.asyncio.Context()
            self.status_sock = self.context.socket(zmq.ROUTER)
            self.data_sock = self.context.socket(zmq.PUB)
            self.status_sock.bind("tcp://*:%s" % self.status_port)
            self.data_sock.bind("tcp://*:%s" % self.data_port)
            self.poller = zmq.asyncio.Poller()
            self.poller.register(self.status_sock, zmq.POLLIN)

            self._loop.create_task(self.poll_sockets())
            try:
                self._loop.run_forever()
            finally:
                self.status_sock.close()
                self.data_sock.close()
                self.context.destroy()
项目:plone.server    作者:plone    | 项目源码 | 文件源码
def setUp(cls):
        """With a Plone Site."""
        loop = cls.aioapp.loop or asyncio.get_event_loop()
        cls.handler = cls.aioapp.make_handler(debug=DEBUG, keep_alive_on=False)
        cls.srv = loop.run_until_complete(loop.create_server(
            cls.handler,
            '127.0.0.1',
            TESTING_PORT))
        print("Started Testing server on port {port}".format(
            port=TESTING_PORT))

        import threading

        def loop_in_thread(loop):
            asyncio.set_event_loop(loop)
            loop.run_forever()

        cls.t = threading.Thread(target=loop_in_thread, args=(loop,))
        cls.t.start()
        cls.requester = PloneRequester('http://localhost:' + str(TESTING_PORT))
        cls.time = time.time()
项目:m2mb    作者:thperret    | 项目源码 | 文件源码
def setUp(self):
        self._old_loop = asyncio.get_event_loop()
        self.loop = asyncio.new_event_loop()
        asyncio.set_event_loop(self.loop)
        #  logging.basicConfig(level=logging.DEBUG)
        #  self.loop.set_debug(True)

        self.parsed_url = urlparse(self.GOOD_WEBHOOK_URL)
        dummy_mattermost_api_app = web.Application()
        dummy_mattermost_api_app.router.add_post(
            "/hooks/{webhook_id}",
            partial(handle_incoming_webhook,
                    webhook_urls=[self.parsed_url.path])
        )
        dummy_mattermost_api_factory = self.loop.create_server(
            dummy_mattermost_api_app.make_handler(),
            *self.parsed_url.netloc.split(":")
        )
        self.dummy_mattermost_api_server = self.loop.run_until_complete(dummy_mattermost_api_factory)
项目:pytwitcher    作者:adongy    | 项目源码 | 文件源码
def __init__(self, loop: asyncio.BaseEventLoop = None, **config):
        if loop is None:
            try:
                loop = asyncio.get_event_loop()
            except RuntimeError:
                loop = asyncio.new_event_loop()
                asyncio.set_event_loop(loop)

        # TOOD: say in the docs that we take ownership of the loop, we close it
        # ourselves in run()
        self.loop = loop
        self.config = dict(self.DEFAULTS, **config)

        self.encoding = self.config['encoding']
        self.registry = registry.Registry(self.config)
        self.queue = asyncio.Queue(loop=self.loop)

        asyncio.ensure_future(self._process_queue(), loop=self.loop)
项目:NebulaSolarDash    作者:toddlerya    | 项目源码 | 文件源码
def run(self, handler):
        import asyncio
        from aiohttp.wsgi import WSGIServerHttpProtocol
        self.loop = asyncio.new_event_loop()
        asyncio.set_event_loop(self.loop)

        protocol_factory = lambda: WSGIServerHttpProtocol(
            handler,
            readpayload=True,
            debug=(not self.quiet))
        self.loop.run_until_complete(self.loop.create_server(protocol_factory,
                                                             self.host,
                                                             self.port))

        if 'BOTTLE_CHILD' in os.environ:
            import signal
            signal.signal(signal.SIGINT, lambda s, f: self.loop.stop())

        try:
            self.loop.run_forever()
        except KeyboardInterrupt:
            self.loop.stop()
项目:SinaL2    作者:Emptyset110    | 项目源码 | 文件源码
def token_sender(self):
        while not self.stopped:
            self.logger.info("???????55??????????")
            start = datetime.now()
            tasks = list()
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)

            for symbol in self.websockets.keys():
                ws = self.websockets[symbol]["ws"]
                if ws.open:
                    tasks.append(
                        ws.send("*" + self.websockets[symbol]["token"]))

            if len(tasks) > 0:
                loop.run_until_complete(asyncio.wait(tasks))
                loop.close()
            self.logger.info(
                "????????. ???%s" %
                (datetime.now() - start).total_seconds()
            )
            time.sleep(55)

    # ????????token
项目:SinaL2    作者:Emptyset110    | 项目源码 | 文件源码
def token_renewer(self):
        while not self.stopped:
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)
            tasks = list()
            for symbol in self.websockets.keys():
                ws = self.websockets[symbol]["ws"]
                if ws.open:
                    if (
                        datetime.now() - self.websockets[symbol]["renewed"]
                    ).total_seconds() > 180:
                        tasks.append(self.renew_token(symbol))

            if len(tasks) > 0:
                loop.run_until_complete(asyncio.wait(tasks))
                loop.close()
            time.sleep(1)
项目:bottle_beginner    作者:denzow    | 项目源码 | 文件源码
def run(self, handler):
        import asyncio
        from aiohttp.wsgi import WSGIServerHttpProtocol
        self.loop = self.get_event_loop()
        asyncio.set_event_loop(self.loop)

        protocol_factory = lambda: WSGIServerHttpProtocol(
            handler,
            readpayload=True,
            debug=(not self.quiet))
        self.loop.run_until_complete(self.loop.create_server(protocol_factory,
                                                             self.host,
                                                             self.port))

        if 'BOTTLE_CHILD' in os.environ:
            import signal
            signal.signal(signal.SIGINT, lambda s, f: self.loop.stop())

        try:
            self.loop.run_forever()
        except KeyboardInterrupt:
            self.loop.stop()
项目:MCSManager-fsmodule    作者:Suwings    | 项目源码 | 文件源码
def run(self, handler):
        import asyncio
        from aiohttp.wsgi import WSGIServerHttpProtocol
        self.loop = self.get_event_loop()
        asyncio.set_event_loop(self.loop)

        protocol_factory = lambda: WSGIServerHttpProtocol(
            handler,
            readpayload=True,
            debug=(not self.quiet))
        self.loop.run_until_complete(self.loop.create_server(protocol_factory,
                                                             self.host,
                                                             self.port))

        if 'BOTTLE_CHILD' in os.environ:
            import signal
            signal.signal(signal.SIGINT, lambda s, f: self.loop.stop())

        try:
            self.loop.run_forever()
        except KeyboardInterrupt:
            self.loop.stop()
项目:paraproxio    作者:intagger    | 项目源码 | 文件源码
def _run(self, *args, **kwargs):
        try:
            with self._state_changed:
                if self._state != STARTING:
                    return

            # Create custom executor.
            executor = concurrent.futures.ThreadPoolExecutor()

            # Create an event loop.
            loop = self._loop = asyncio.new_event_loop()  # type: BaseEventLoop
            loop.set_default_executor(executor)
            asyncio.set_event_loop(None)

            # Schedule 'set started' on loop.
            loop.call_later(1, self._set_started)
            self.run(loop, *args, **kwargs)
        finally:
            with self._state_changed:
                self._state = STOPPED
                self._state_changed.notify_all()
项目:paraproxio    作者:intagger    | 项目源码 | 文件源码
def setUp(self):
        self.loop = asyncio.new_event_loop()
        asyncio.set_event_loop(None)

        # Start a web server.
        self.web_server = TestWebServer()
        self.web_server.start()

        # Start a proxy server.
        self.proxy_server = TestParaproxioServer()
        self.proxy_server.start(
            args=['--host', PROXY_SERVER_HOST,
                  '--port', str(PROXY_SERVER_PORT),
                  '--parallels', self.parallels,
                  '--debug',
                  '--clean-all'])
项目:dHydra    作者:Emptyset110    | 项目源码 | 文件源码
def token_sender(self):
        while not self.stopped:
            self.logger.debug("???????55??????????")
            start = datetime.now()
            tasks = list()
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)

            for symbol in self.websockets.keys():
                ws = self.websockets[symbol]["ws"]
                if ws.open:
                    tasks.append(
                        ws.send("*" + self.websockets[symbol]["token"]))

            if len(tasks) > 0:
                loop.run_until_complete(asyncio.wait(tasks))
                loop.close()
            self.logger.debug(
                "????????. ???%s" %
                (datetime.now() - start).total_seconds()
            )
            time.sleep(55)

    # ????????token
项目:dHydra    作者:Emptyset110    | 项目源码 | 文件源码
def token_renewer(self):
        while not self.stopped:
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)
            tasks = list()
            for symbol in self.websockets.keys():
                ws = self.websockets[symbol]["ws"]
                if ws.open:
                    if (
                        datetime.now() - self.websockets[symbol]["renewed"]
                    ).total_seconds() > 180:
                        tasks.append(self.renew_token(symbol))

            if len(tasks) > 0:
                loop.run_until_complete(asyncio.wait(tasks))
                loop.close()
            time.sleep(1)
项目:krpc-library    作者:krpc    | 项目源码 | 文件源码
def run(self, loop):
        self.fp = None
        asyncio.set_event_loop(loop)
        self.loop = asyncio.get_event_loop()
        print("Pynet running")
        # Create a task to handle incoming requests then wait for
        # all tasks to complete.
        self.loop.set_exception_handler(self.exception_handler)

        # Start the request handler
        self.loop.create_task(self.request_handler())

        pending = asyncio.Task.all_tasks()
        try:
            self.loop.run_until_complete(asyncio.gather(*pending))
        except RuntimeError:
            print("Pynet Loop stopped, disconnected")

        self.disconnect()

    # Main thread
项目:dHydra    作者:Michael0711    | 项目源码 | 文件源码
def websocket_creator(self):
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        # ???????????
        symbol_list = self.symbols
        # Cut symbol_list
        weight = (len(self.query) +
                  1) if ('transaction' in self.query) else len(self.query)
        step = int(64 / weight)
        symbol_list_slice = [symbol_list[i: i + step]
                             for i in range(0, len(symbol_list), step)]

        tasks = list()
        for symbol_list in symbol_list_slice:
            qlist = ''
            for symbol in symbol_list:
                qlist = self.generate_qlist(qlist=qlist, symbol=symbol)
            qlist = qlist.lower()
            tasks.append(self.create_ws(qlist, symbol_list=symbol_list))

        loop.run_until_complete(asyncio.wait(tasks))
        loop.close()

    # ??????????
项目:dHydra    作者:Michael0711    | 项目源码 | 文件源码
def token_sender(self):
        while True:
            self.logger.info("???????55??????????")
            start = datetime.now()
            tasks = list()
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)

            for symbol in self.websockets.keys():
                ws = self.websockets[symbol]["ws"]
                if ws.open:
                    tasks.append(
                        ws.send("*" + self.websockets[symbol]["token"]))

            if len(tasks) > 0:
                loop.run_until_complete(asyncio.wait(tasks))
                loop.close()
            self.logger.info(
                "????????. ???%s" %
                (datetime.now() - start).total_seconds()
            )
            time.sleep(55)

    # ????????token
项目:dHydra    作者:Michael0711    | 项目源码 | 文件源码
def token_renewer(self):
        while True:
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)
            tasks = list()
            for symbol in self.websockets.keys():
                ws = self.websockets[symbol]["ws"]
                if ws.open:
                    if (
                        datetime.now() - self.websockets[symbol]["renewed"]
                    ).total_seconds() > 180:
                        tasks.append(self.renew_token(symbol))

            if len(tasks) > 0:
                loop.run_until_complete(asyncio.wait(tasks))
                loop.close()
            time.sleep(1)
项目:dHydra    作者:Michael0711    | 项目源码 | 文件源码
def websocket_creator(self):
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        # ???????????
        symbolList = self.symbols
        # Cut symbolList
        weight = (len(self.query)+1) if ('deal' in self.query) else len(self.query)
        step = int(64/weight)
        symbolListSlice = [symbolList[ i : i + step] for i in range(0, len(symbolList), step)]

        tasks = list()
        for symbolList in symbolListSlice:
            qlist = ''
            for symbol in symbolList:
                qlist = self.generate_qlist(qlist=qlist,symbol=symbol)
            qlist = qlist.lower()
            tasks.append( self.create_ws(qlist,symbolList = symbolList) )

        loop.run_until_complete( asyncio.wait(tasks) )
        loop.close()

    # ??????????
项目:dHydra    作者:Michael0711    | 项目源码 | 文件源码
def token_sender(self):
        while True:
            self.logger.info("???????55??????????")
            start = datetime.now()
            tasks = list()
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)

            for symbol in self.websockets.keys():
                ws = self.websockets[ symbol ]["ws"]
                if ws.open:
                    tasks.append( ws.send("*"+self.websockets[symbol]["token"]) )

            if len(tasks)>0:
                loop.run_until_complete( asyncio.wait(tasks) )
                loop.close()
            self.logger.info("????????. ???%s" % (datetime.now()-start).total_seconds() )
            time.sleep(55)

    # ????????token
项目:dHydra    作者:Michael0711    | 项目源码 | 文件源码
def token_renewer(self):
        while True:
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)
            tasks = list()
            for symbol in self.websockets.keys():
                ws = self.websockets[ symbol ]["ws"]
                if ws.open:
                    if (datetime.now()-self.websockets[ symbol ]["renewed"]).total_seconds()>180:
                        tasks.append( self.renew_token( symbol ) )

            if len(tasks)>0:
                loop.run_until_complete( asyncio.wait(tasks) )
                loop.close()
            time.sleep(1)
            # gc.collect()
项目:autoinjection    作者:ChengWiLL    | 项目源码 | 文件源码
def run(self, handler):
        import asyncio
        from aiohttp.wsgi import WSGIServerHttpProtocol
        self.loop = asyncio.new_event_loop()
        asyncio.set_event_loop(self.loop)

        protocol_factory = lambda: WSGIServerHttpProtocol(
            handler,
            readpayload=True,
            debug=(not self.quiet))
        self.loop.run_until_complete(self.loop.create_server(protocol_factory,
                                                             self.host,
                                                             self.port))

        if 'BOTTLE_CHILD' in os.environ:
            import signal
            signal.signal(signal.SIGINT, lambda s, f: self.loop.stop())

        try:
            self.loop.run_forever()
        except KeyboardInterrupt:
            self.loop.stop()
项目:cozmo-python-sdk    作者:anki    | 项目源码 | 文件源码
def _connect_async(f, conn_factory=conn.CozmoConnection, connector=None):
    # use the default loop, if one is available for the current thread,
    # if not create  a new loop and make it the default.
    #
    # the expectation is that if the user wants explicit control over which
    # loop the code is executed on, they'll just use connect_on_loop directly.
    loop = None
    try:
        loop = asyncio.get_event_loop()
    except:
        pass

    if loop is None:
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)

    coz_conn = connect_on_loop(loop, conn_factory, connector)
    try:
        loop.run_until_complete(f(coz_conn))
    except KeyboardInterrupt:
        logger.info('Exit requested by user')
    finally:
        loop.run_until_complete(coz_conn.shutdown())
        loop.stop()
        loop.run_forever()
项目:Knjiznica    作者:TilenNoc    | 项目源码 | 文件源码
def run(self, handler):
        import asyncio
        from aiohttp.wsgi import WSGIServerHttpProtocol
        self.loop = self.get_event_loop()
        asyncio.set_event_loop(self.loop)

        protocol_factory = lambda: WSGIServerHttpProtocol(
            handler,
            readpayload=True,
            debug=(not self.quiet))
        self.loop.run_until_complete(self.loop.create_server(protocol_factory,
                                                             self.host,
                                                             self.port))

        if 'BOTTLE_CHILD' in os.environ:
            import signal
            signal.signal(signal.SIGINT, lambda s, f: self.loop.stop())

        try:
            self.loop.run_forever()
        except KeyboardInterrupt:
            self.loop.stop()
项目:nougat    作者:NougatWeb    | 项目源码 | 文件源码
def __request(self, method, url, cookies=None, *args, **kwargs):

        async def __local_request(app, method, url, *args, **kwargs):

            server_loop = await app.start_server(HOST, PORT)
            self.port = server_loop.sockets[0].getsockname()[1]
            url = 'http://{host}:{port}{uri}'.format(host=HOST, port=self.port, uri=url)

            async with aiohttp.ClientSession(loop=self.loop, cookies=cookies) as session:
                async with getattr(session, method)(url, *args, **kwargs) as response:
                    response.text = await response.text()
                    server_loop.close()
                    await server_loop.wait_closed()
                    return response

        asyncio.set_event_loop(self.loop)
        ret = self.loop.run_until_complete(__local_request(self.app, method, url, *args, **kwargs))

        # cancel all task
        tasks = asyncio.Task.all_tasks()
        for task in tasks:
            task.cancel()
        self.loop.run_until_complete(self.stop_server())

        return ret
项目:sanic    作者:channelcat    | 项目源码 | 文件源码
def test_keep_alive_timeout_reuse():
    """If the server keep-alive timeout and client keep-alive timeout are
     both longer than the delay, the client _and_ server will successfully
     reuse the existing connection."""
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    client = ReuseableSanicTestClient(keep_alive_timeout_app_reuse, loop)
    headers = {
        'Connection': 'keep-alive'
    }
    request, response = client.get('/1', headers=headers)
    assert response.status == 200
    assert response.text == 'OK'
    loop.run_until_complete(aio_sleep(1))
    request, response = client.get('/1', end_server=True)
    assert response.status == 200
    assert response.text == 'OK'
项目:sanic    作者:channelcat    | 项目源码 | 文件源码
def test_keep_alive_client_timeout():
    """If the server keep-alive timeout is longer than the client
    keep-alive timeout, client will try to create a new connection here."""
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    client = ReuseableSanicTestClient(keep_alive_app_client_timeout,
                                      loop)
    headers = {
        'Connection': 'keep-alive'
    }
    request, response = client.get('/1', headers=headers,
                                   request_keepalive=1)
    assert response.status == 200
    assert response.text == 'OK'
    loop.run_until_complete(aio_sleep(2))
    exception = None
    try:
        request, response = client.get('/1', end_server=True,
                                       request_keepalive=1)
    except ValueError as e:
        exception = e
    assert exception is not None
    assert isinstance(exception, ValueError)
    assert "got a new connection" in exception.args[0]
项目:windflow    作者:hartym    | 项目源码 | 文件源码
def get_event_loop(debug=False):
    if not debug:
        import uvloop
        asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
        asyncio.set_event_loop(uvloop.new_event_loop())
    return asyncio.get_event_loop()
项目:windflow    作者:hartym    | 项目源码 | 文件源码
def get_event_loop(self, debug=False):
        if not debug:
            asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
            asyncio.set_event_loop(uvloop.new_event_loop())
        AsyncIOMainLoop().install()
        return asyncio.get_event_loop()
项目:Farm-server    作者:MakersLab    | 项目源码 | 文件源码
def makeRequest(command, printers, fileName=None, toolTemperature=None, bedTemperature=None):
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    future = asyncio.ensure_future(run(command, printers, fileName, toolTemperature=toolTemperature, bedTemperature=bedTemperature))
    return (loop.run_until_complete(future))
项目:oshino    作者:CodersOfTheNight    | 项目源码 | 文件源码
def create_loop():
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    return loop
项目:zanph    作者:zanph    | 项目源码 | 文件源码
def setUp(self):
        if asyncio is None:
            raise SkipTest()
        self.loop = zaio.ZMQEventLoop()
        asyncio.set_event_loop(self.loop)
        super(TestAsyncIOSocket, self).setUp()
项目:zanph    作者:zanph    | 项目源码 | 文件源码
def setUp(self):
        if asyncio is None:
            raise SkipTest()
        self.loop = zaio.ZMQEventLoop()
        asyncio.set_event_loop(self.loop)
        super().setUp()
项目:zanph    作者:zanph    | 项目源码 | 文件源码
def install():
    """Install and return the global ZMQEventLoop

    registers the loop with asyncio.set_event_loop
    """
    global _loop
    if _loop is None:
        _loop = ZMQEventLoop()
        asyncio.set_event_loop(_loop)
    return _loop
项目:hdx-data-freshness    作者:OCHA-DAP    | 项目源码 | 文件源码
def retrieve(urls):
    start_time = time.time()
    loop = uvloop.new_event_loop()
    asyncio.set_event_loop(loop)
    future = asyncio.ensure_future(check_urls(urls, loop))
    results = loop.run_until_complete(future)
    logger.info('Execution time: %s seconds' % (time.time() - start_time))
    return results
项目:mooq    作者:jeremyarr    | 项目源码 | 文件源码
def GIVEN_RabbitMQBrokerStarted(cls,host,port):
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        loop.set_debug(True)

        cls.broker = mooq.RabbitMQBroker(host=host,port=port)

        try:
            loop.run_until_complete(cls.broker.run())
        finally:
            loop.close()
项目:highfive    作者:abau171    | 项目源码 | 文件源码
def worker_main(job_handler, host, port):
    """
    Starts an asyncio event loop to connect to the master and run jobs.
    """

    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(None)
    loop.run_until_complete(handle_jobs(job_handler, host, port, loop=loop))
    loop.close()