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

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

项目: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_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_async_task(self):
        @asyncio.coroutine
        def notmuch():
            return 'ok'
        t_orig = asyncio.Task(notmuch(), loop=self.loop)
        t = asyncio.async(t_orig)
        self.loop.run_until_complete(t)
        self.assertTrue(t.done())
        self.assertEqual(t.result(), 'ok')
        self.assertIs(t, t_orig)

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

        with self.assertRaises(ValueError):
            t = asyncio.async(t_orig, loop=loop)

        loop.close()

        t = asyncio.async(t_orig, loop=self.loop)
        self.assertIs(t, t_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_cancel_wait_for(self, timeout):
        loop = asyncio.new_event_loop()
        self.addCleanup(loop.close)

        @asyncio.coroutine
        def blocking_coroutine():
            fut = asyncio.Future(loop=loop)
            # Block: fut result is never set
            yield from fut

        task = loop.create_task(blocking_coroutine())

        wait = loop.create_task(asyncio.wait_for(task, timeout, loop=loop))
        loop.call_soon(wait.cancel)

        self.assertRaises(asyncio.CancelledError,
                          loop.run_until_complete, wait)

        # Python issue #23219: cancelling the wait must also cancel the task
        self.assertTrue(task.cancelled())
项目: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
项目: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)
项目:Quantrade    作者:quant-trade    | 项目源码 | 文件源码
def data_model_csv():
    path_to = join(settings.DATA_PATH, "incoming")
    filenames = multi_filenames(path_to_history=path_to, csv=True)
    cnt = len(filenames)
    batch_size = int(cnt/settings.CPUS)
    diff = cnt - (settings.CPUS * batch_size)

    def start_loop(loop, filenames):
        set_event_loop(loop)
        loop.run_until_complete(gather(*[make_initial_file(filename=filename) \
            for filename in filenames], return_exceptions=True))

    processes = []
    for cpu in range(settings.CPUS):
        if (cpu+1) == settings.CPUS:
            p = Process(target=start_loop, args=(new_event_loop(), filenames[cpu*batch_size:(cpu+1)*batch_size+diff]))
        else:
            p = Process(target=start_loop, args=(new_event_loop(), filenames[cpu*batch_size:(cpu+1)*batch_size]))
        processes.append(p)
        p.start()

    for p in processes:
        p.join()
项目:Quantrade    作者:quant-trade    | 项目源码 | 文件源码
def read_failing(filenames, path_to, loop, list_failing):

    def start_loop(loop, filenames):
        set_event_loop(loop)
        loop.run_until_complete(gather(*[gather_bad_file(filename=filename, \
            path_to=path_to, list_failing=list_failing) for filename in filenames]))

    cnt = len(filenames)
    batch_size = int(cnt/settings.CPUS)
    diff = cnt - (settings.CPUS * batch_size)

    processes = []
    for cpu in range(settings.CPUS):
        if (cpu+1) == settings.CPUS:
            p = Process(target=start_loop, args=(new_event_loop(), filenames[cpu*batch_size:(cpu+1)*batch_size+diff]))
        else:
            p = Process(target=start_loop, args=(new_event_loop(), filenames[cpu*batch_size:(cpu+1)*batch_size]))
        processes.append(p)
        p.start()

    for p in processes:
        p.join()

    return list_failing
项目: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)
项目:uvicorn    作者:encode    | 项目源码 | 文件源码
def test_send_text_data_to_server():
    async def app(message, channels):
        if message['channel'] == 'websocket.connect':
            await channels['reply'].send({'accept': True})
        elif message['channel'] == 'websocket.receive':
            data = message.get('text')
            await channels['reply'].send({'text': data})

    async def send_text(url):
        async with websockets.connect(url) as websocket:
            await websocket.send('abc')
            return await websocket.recv()

    with run_server(app) as url:
        loop = asyncio.new_event_loop()
        data = loop.run_until_complete(send_text(url))
        assert data == 'abc'
        loop.close()
项目:uvicorn    作者:encode    | 项目源码 | 文件源码
def test_send_binary_data_to_server():
    async def app(message, channels):
        if message['channel'] == 'websocket.connect':
            await channels['reply'].send({'accept': True})
        elif message['channel'] == 'websocket.receive':
            data = message.get('bytes')
            await channels['reply'].send({'bytes': data})

    async def send_text(url):
        async with websockets.connect(url) as websocket:
            await websocket.send(b'abc')
            return await websocket.recv()

    with run_server(app) as url:
        loop = asyncio.new_event_loop()
        data = loop.run_until_complete(send_text(url))
        assert data == b'abc'
        loop.close()
项目: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)
项目:dHydra    作者:Emptyset110    | 项目源码 | 文件源码
def get_quotation(self, symbol=None, symbolSet=None, dataframe=True, threadNum=3):
        if 'quotation' in self.__dict__.keys():
            del(self.quotation)
            # Cut symbolList
        symbolList = list(symbolSet)
        threads = []
        symbolListSlice = util.slice_list(num=threadNum, data_list=symbolList)
        for symbolList in symbolListSlice:
            loop = asyncio.new_event_loop()
            symbolsList = util.slice_list(step=50, data_list=symbolList)
            tasks = [self.get_quotation_task(
                symbols=symbols) for symbols in symbolsList]
            t = threading.Thread(target=util.thread_loop, args=(loop, tasks))
            threads.append(t)
        for t in threads:
            t.start()
        for t in threads:
            t.join()

        if dataframe:
            self.quotation = DataFrame.from_records(self.quotation).T
        return(self.quotation)
项目: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()
项目:msgraph-sdk-python    作者:microsoftgraph    | 项目源码 | 文件源码
def __init__(self, base_url, auth_provider, http_provider, loop=None):
        """Initialize the :class:`GraphClient` to be
            used for all Graph API interactions

        Args:
            base_url (str): The Graph base url to use for API interactions
            auth_provider(:class:`AuthProviderBase<microsoft.msgraph.auth_provider_base.AuthProviderBase>`):
                The authentication provider used by the client to auth
                with Graph services
            http_provider(:class:`HttpProviderBase<microsoft.msgraph.http_provider_base.HttpProviderBase>`):
                The HTTP provider used by the client to send all 
                requests to Graph
            loop (BaseEventLoop): Default to None, the AsyncIO loop 
                to use for all async requests
        """
        self.base_url = base_url
        self.auth_provider = auth_provider
        self.http_provider = http_provider

        if sys.version_info >= (3, 4, 0):
            import asyncio
            self._loop = loop if loop else asyncio.new_event_loop()
项目:msgraph-sdk-python    作者:microsoftgraph    | 项目源码 | 文件源码
def __init__(self, base_url, auth_provider, http_provider, loop=None):
        """Initialize the :class:`GraphClient` to be
            used for all Graph API interactions

        Args:
            base_url (str): The Graph base url to use for API interactions
            auth_provider(:class:`AuthProviderBase<msgraph.auth_provider_base.AuthProviderBase>`):
                The authentication provider used by the client to auth
                with Graph services
            http_provider(:class:`HttpProviderBase<msgraph.http_provider_base.HttpProviderBase>`):
                The HTTP provider used by the client to send all 
                requests to Graph
            loop (BaseEventLoop): Default to None, the AsyncIO loop 
                to use for all async requests
        """
        self.base_url = base_url
        self.auth_provider = auth_provider
        self.http_provider = http_provider

        if sys.version_info >= (3, 5, 0):
            import asyncio
            self._loop = loop if loop else asyncio.new_event_loop()
项目: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()
项目:nougat    作者:NougatWeb    | 项目源码 | 文件源码
def run(self, host: str="localhost", port: int=8000, debug: bool=False):
        """
        start the http server
        :param host: The listening host
        :param port: The listening port
        :param debug: whether it is in debug mod or not
        """
        if debug:
            print("Nougat is listening on http://{}:{}\n".format(host, port))
        self.debug = debug
        loop = asyncio.new_event_loop()
        loop.run_until_complete(self.start_server(host, port))
        try:
            loop.run_forever()
        except KeyboardInterrupt:
            loop.close()
项目: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]
项目:pyIntesisHome    作者:jnimmo    | 项目源码 | 文件源码
def __init__(self, username, password, loop=None):
        self._username = username
        self._password = password
        self._cmdServer = None
        self._cmdServerPort = None
        self._devices = {}
        self._connectionStatus = API_DISCONNECTED
        self._commandQueue = queue.Queue()
        self._transport = None
        self._updateCallbacks = []
        self._errorCallbacks = []
        self._errorMessage = None

        if loop:
            _LOGGER.info("Latching onto an existing event loop.")
            self._eventLoop = loop
            self._ownLoop = False
        else:
            _LOGGER.info("Creating our own event loop.")
            self._eventLoop = asyncio.new_event_loop()
            self._ownLoop = True
项目:freehp    作者:jadbin    | 项目源码 | 文件源码
def __init__(self, config):
        self.config = config
        self._loop = asyncio.new_event_loop()
        config.set('loop', self._loop)

        self._proxy_db = ProxyDb(join(config.get("data_dir"), "freehp-agent.db"))
        self._proxy_db.create_table()

        self._checker = self._load_checker(config.get("checker_cls"))
        self._checker_clients = config.getint("checker_clients")

        self._check_interval = config.getint("check_interval")
        self._block_time = config.getint("block_time")
        self._proxy_queue = ProxyQueue(config.getint("queue_size"), max_fail_times=config.getint("max_fail_times"))

        self._spider = ProxySpider(self._get_spider_config(config.get('spider_config')))

        self._agent_listen = config.get("agent_listen")

        self._futures = []
        self._wait_queue = Queue(loop=self._loop)
        self._is_running = False
项目:python-course    作者:juancarlospaco    | 项目源码 | 文件源码
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()
项目:deb-python-txaio    作者:openstack    | 项目源码 | 文件源码
def test_create_future_success_explicit_loop(framework):
    """
    process events on alternate loop= for create_future later
    """
    pytest.importorskip('asyncio')
    if txaio.using_twisted:
        pytest.skip()

    import asyncio
    alt_loop = asyncio.new_event_loop()
    txa = txaio.with_config(loop=alt_loop)

    f = txa.create_future_success('some result')

    results = []
    f.add_done_callback(lambda r: results.append(r.result()))

    # run_once() runs the txaio.config.loop so we shouldn't get any
    # results until we spin alt_loop
    assert results == []
    run_once()
    assert results == []
    with replace_loop(alt_loop):
        run_once()
    assert results == ['some result']
项目:geo-pyprint    作者:ioda-net    | 项目源码 | 文件源码
def __init__(self, payload):
        self._payload = payload
        self._loop = asyncio.new_event_loop()
        self._map_image = None
        self._map = payload['attributes']['map']
        self._projection = self._map['projection']
        self._scale = self._map['scale']
        self._center = self._map['center']
        self._dpi = self._map['dpi']

        self._init_bbox()
        self._init_map_size()
项目:python-libjuju    作者:juju    | 项目源码 | 文件源码
def test_explicit_loop_threaded(event_loop):
    async with base.CleanModel() as model:
        model_name = model.info.name
        new_loop = asyncio.new_event_loop()
        with ThreadPoolExecutor(1) as executor:
            f = executor.submit(
                new_loop.run_until_complete,
                _deploy_in_loop(new_loop, model_name, model._connector.jujudata))
            f.result()
        await model._wait_for_new('application', 'ubuntu')
        assert 'ubuntu' in model.applications
项目:dabdabrevolution    作者:harryparkdotio    | 项目源码 | 文件源码
def get_event_loop(self):
        import asyncio
        return asyncio.new_event_loop()
项目:dabdabrevolution    作者:harryparkdotio    | 项目源码 | 文件源码
def get_event_loop(self):
        import uvloop
        return uvloop.new_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))
项目:CEX.IO-Client-Python3.5    作者:cexioltd    | 项目源码 | 文件源码
def test_async(self):
        loop = asyncio.new_event_loop()
        loop.run_until_complete(self.run_all())
        loop.close()
项目:noc-orchestrator    作者:DirceuSilvaLabs    | 项目源码 | 文件源码
def initialize(self, **kwargs):
        loop = asyncio.new_event_loop()
        try:
            super(AsyncIOLoop, self).initialize(loop, close_loop=True, **kwargs)
        except Exception:
            # If initialize() does not succeed (taking ownership of the loop),
            # we have to close it.
            loop.close()
            raise
项目:noc-orchestrator    作者:DirceuSilvaLabs    | 项目源码 | 文件源码
def initialize(self, **kwargs):
        loop = asyncio.new_event_loop()
        try:
            super(AsyncIOLoop, self).initialize(loop, close_loop=True, **kwargs)
        except Exception:
            # If initialize() does not succeed (taking ownership of the loop),
            # we have to close it.
            loop.close()
            raise
项目:noc-orchestrator    作者:DirceuSilvaLabs    | 项目源码 | 文件源码
def initialize(self, **kwargs):
        loop = asyncio.new_event_loop()
        try:
            super(AsyncIOLoop, self).initialize(loop, close_loop=True, **kwargs)
        except Exception:
            # If initialize() does not succeed (taking ownership of the loop),
            # we have to close it.
            loop.close()
            raise
项目:wsstat    作者:Fitblip    | 项目源码 | 文件源码
def test_bad_handshake(self):
        event_loop = asyncio.new_event_loop()
        try:
            assert len(asyncio.Task.all_tasks(event_loop)) == 0

            # Test bad handshakes
            event_loop.run_until_complete(self.client.create_websocket_connection())

            # Make sure that the logger was called
            assert self.client.logger.log.call_count > 0
            # Ensure that there was a failed connection
            assert isinstance(self.client.sockets[self.identifier], BaseException)
        finally:
            event_loop.stop()