• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python trollius.set_event_loop函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: run

    def run(self, command, *args, **kwargs):
        self_ = self

        class SubprocessProtocol(asyncio.SubprocessProtocol):
            def pipe_data_received(self, fd, data):
                self_._write(fd, re.sub(r'(\r?\n)+', r'\1', data))

            def connection_lost(self, exc):
                loop.stop()  # end loop.run_forever()

        if os.name == 'nt':
            # For subprocess' pipes on Windows
            loop = asyncio.ProactorEventLoop()
            asyncio.set_event_loop(loop)
        else:
            loop = asyncio.get_event_loop()

        try:
            if kwargs.pop('shell', False):
                proc = loop.subprocess_shell(SubprocessProtocol, command)
            else:
                proc = loop.subprocess_exec(SubprocessProtocol, *command)

            def _refresh_gui():
                refresh_gui()
                loop.call_soon(_refresh_gui)

            loop.call_soon(_refresh_gui)
            transport, protocol = loop.run_until_complete(proc)
            loop.run_forever()
        except Exception, exception:
            self._write(2, str(exception))
开发者ID:wheeler-microfluidics,项目名称:pygtkhelpers,代码行数:32,代码来源:command_textview.py


示例2: run

 def run(self, driver, time_out):
     self.loop = new_event_loop()
     set_event_loop(self.loop)
     ensure_future(self.control_loop(driver, time_out))
     self.loop.run_forever()
     self.loop.close()
     return (self.distance_to_goal, self.left_velocity, self.right_velocity)
开发者ID:dljohnso,项目名称:swarm_robot,代码行数:7,代码来源:robot_controller2.py


示例3: handler

def handler(event, contest):
    logger.info("Start!")

    executor = ThreadPoolExecutor(max_workers=1000)
    main_loop = asyncio.new_event_loop()
    main_loop.set_default_executor(executor)
    asyncio.set_event_loop(main_loop)

    poll = Poll(main_loop)
    cal = poll.cal
    update_and_delete = UpdateAndDelete(main_loop, executor)

    table = event['table']
    queue_url = event['queueUrl']
    message_count = event['messageCount']

    poll.messages(sqs, queue_url, message_count)

    logger.info("Receive API count: {}".format(poll.fetch_count))
    logger.info("Fetched messages: {}".format(poll.message_count))

    update_and_delete.execute(sqs_client, db, queue_url, table, cal.stats)

    logger.info("Update API count: {}".format(update_and_delete.update_count))
    logger.info("Delete API count: {}".format(update_and_delete.delete_count))
    logger.info("Delete Message count: {}".format(
        update_and_delete.deleted_message_count))

    main_loop.close()
    executor.shutdown()

    return "Lambda job finished successfully."
开发者ID:yxd-hde,项目名称:lambda-poll-update-delete,代码行数:32,代码来源:main.py


示例4: test_default_exc_handler_coro

    def test_default_exc_handler_coro(self):
        self.loop._process_events = mock.Mock()
        self.loop.set_debug(True)
        asyncio.set_event_loop(self.loop)

        @asyncio.coroutine
        def zero_error_coro():
            yield From(asyncio.sleep(0.01, loop=self.loop))
            1 / 0

        # Test Future.__del__
        with mock.patch("trollius.base_events.logger") as log:
            fut = asyncio.async(zero_error_coro(), loop=self.loop)
            fut.add_done_callback(lambda *args: self.loop.stop())
            self.loop.run_forever()
            fut = None  # Trigger Future.__del__ or futures._TracebackLogger
            support.gc_collect()
            if PY34:
                # Future.__del__ in Python 3.4 logs error with
                # an actual exception context
                log.error.assert_called_with(
                    test_utils.MockPattern(".*exception was never retrieved"),
                    exc_info=(ZeroDivisionError, MOCK_ANY, MOCK_ANY),
                )
            else:
                # futures._TracebackLogger logs only textual traceback
                log.error.assert_called_with(
                    test_utils.MockPattern(".*exception was never retrieved.*ZeroDiv"), exc_info=False
                )
开发者ID:JioCloudCompute,项目名称:trollius,代码行数:29,代码来源:test_base_events.py


示例5: test_log_slow_callbacks

    def test_log_slow_callbacks(self, m_logger):
        def stop_loop_cb(loop):
            loop.stop()

        @asyncio.coroutine
        def stop_loop_coro(loop):
            yield From(None)
            loop.stop()

        asyncio.set_event_loop(self.loop)
        self.loop.set_debug(True)
        self.loop.slow_callback_duration = 0.0

        # slow callback
        self.loop.call_soon(stop_loop_cb, self.loop)
        self.loop.run_forever()
        fmt = m_logger.warning.call_args[0][0]
        args = m_logger.warning.call_args[0][1:]
        self.assertRegex(fmt % tuple(args), "^Executing <Handle.*stop_loop_cb.*> " "took .* seconds$")

        # slow task
        asyncio.async(stop_loop_coro(self.loop), loop=self.loop)
        self.loop.run_forever()
        fmt = m_logger.warning.call_args[0][0]
        args = m_logger.warning.call_args[0][1:]
        self.assertRegex(fmt % tuple(args), "^Executing <Task.*stop_loop_coro.*> " "took .* seconds$")
开发者ID:JioCloudCompute,项目名称:trollius,代码行数:26,代码来源:test_base_events.py


示例6: main

def main():
    asyncio.set_event_loop(None)
    if args.iocp:
        from trollius.windows_events import ProactorEventLoop
        loop = ProactorEventLoop()
    else:
        loop = asyncio.new_event_loop()
    sslctx = None
    if args.tls:
        import ssl
        # TODO: take cert/key from args as well.
        here = os.path.join(os.path.dirname(__file__), '..', 'tests')
        sslctx = asyncio.SSLContext(ssl.PROTOCOL_SSLv23)
        sslctx.options |= ssl.OP_NO_SSLv2
        sslctx.load_cert_chain(
            certfile=os.path.join(here, 'ssl_cert.pem'),
            keyfile=os.path.join(here, 'ssl_key.pem'))
    cache = Cache(loop)
    task = asyncio.streams.start_server(cache.handle_client,
                                        args.host, args.port,
                                        ssl=sslctx, loop=loop)
    svr = loop.run_until_complete(task)
    for sock in svr.sockets:
        logging.info('socket %s', sock.getsockname())
    try:
        loop.run_forever()
    finally:
        loop.close()
开发者ID:JioCloudCompute,项目名称:trollius,代码行数:28,代码来源:cachesvr.py


示例7: run

def run(driver, time_out):
    loop = new_event_loop()
    set_event_loop(loop)
    ensure_future(control_loop(driver, time_out, loop))
    loop.run_forever()
    loop.close()
    return (distance_to_goal, left_velocity, right_velocity)
开发者ID:dljohnso,项目名称:swarm_robot,代码行数:7,代码来源:robot_controller.py


示例8: set_event_loop

 def set_event_loop(self):
     self.loop = asyncio.new_event_loop()
     asyncio.set_event_loop(self.loop)
     self.events = asyncio.Queue(loop=self.loop)
     self.set_exception_handler()
     if self.loglevel is not None and self.loglevel <= logging.DEBUG:
         self.loop.set_debug(True)
     return self.loop
开发者ID:tracyone,项目名称:pyclewn_linux,代码行数:8,代码来源:vim.py


示例9: test_streamreader_constructor

    def test_streamreader_constructor(self):
        self.addCleanup(asyncio.set_event_loop, None)
        asyncio.set_event_loop(self.loop)

        # Tulip issue #184: Ensure that StreamReaderProtocol constructor
        # retrieves the current loop if the loop parameter is not set
        reader = asyncio.StreamReader()
        self.assertIs(reader._loop, self.loop)
开发者ID:JioCloudCompute,项目名称:trollius,代码行数:8,代码来源:test_streams.py


示例10: test_tb_logger_exception_unretrieved

 def test_tb_logger_exception_unretrieved(self, m_log):
     self.loop.set_debug(True)
     asyncio.set_event_loop(self.loop)
     fut = asyncio.Future(loop=self.loop)
     fut.set_exception(RuntimeError("boom"))
     del fut
     test_utils.run_briefly(self.loop)
     support.gc_collect()
     self.assertTrue(m_log.error.called)
开发者ID:balagopalraj,项目名称:clearlinux,代码行数:9,代码来源:test_futures.py


示例11: main

def main():
    if os.name == 'nt':
        loop = asyncio.ProactorEventLoop()
        asyncio.set_event_loop(loop)
    else:
        loop = asyncio.get_event_loop()
    loop.run_until_complete(start(
        'sleep 2; wc', input=[b'foo bar baz\n'*300 for i in range(100)]))
    loop.close()
开发者ID:JioCloudCompute,项目名称:trollius,代码行数:9,代码来源:subprocess_shell.py


示例12: add_task

    def add_task(self, key, task, no_cache=False):
        if not no_cache:
            task_cache = self._get_cache(key)
            if task_cache is not None:
                return TaskGetter(task_cache)
        self._tasks[key] = task
        aio.set_event_loop(self.loop)
        self.loop.call_soon_threadsafe(aio.async, self.queue.put(task))

        return TaskGetter(task)
开发者ID:PyWilhelm,项目名称:EDRIS_DS,代码行数:10,代码来源:DymolaBuilder.py


示例13: execute

    def execute(self, sqs, queue_url, ids):
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        loop.set_default_executor(self.executor)

        id_groups = group_by_10(ids)
        tasks = []
        for id_group in id_groups:
            tasks.append(self._one_request(loop, sqs, queue_url, id_group))
        loop.run_until_complete(asyncio.wait(tasks))
开发者ID:yxd-hde,项目名称:lambda-poll-update-delete,代码行数:10,代码来源:delete.py


示例14: _basetest_open_connection_no_loop_ssl

    def _basetest_open_connection_no_loop_ssl(self, open_connection_fut):
        try:
            reader, writer = self.loop.run_until_complete(open_connection_fut)
        finally:
            asyncio.set_event_loop(None)
        writer.write(b'GET / HTTP/1.0\r\n\r\n')
        f = reader.read()
        data = self.loop.run_until_complete(f)
        self.assertTrue(data.endswith(b'\r\n\r\nTest message'))

        writer.close()
开发者ID:balagopalraj,项目名称:clearlinux,代码行数:11,代码来源:test_streams.py


示例15: __init__

 def __init__(self, instances=4):
     logging.warn('init dymola builder')
     DymolaBuilder._initial_paths()
     self.dymola_instances = [start_dymola() for _ in range(instances)]
     self.loop = aio.get_event_loop()
     aio.set_event_loop(self.loop)
     self.queue = aio.Queue(maxsize=0, loop=self.loop)
     arguments = (self.queue, self.loop, self.dymola_instances)
     self.main = Thread(target=main_event_loop, args=arguments)
     self.main.start()
     logging.warn('started thread loop asyncio')
开发者ID:PyWilhelm,项目名称:EDRIS_DS,代码行数:11,代码来源:DymolaBuilder.py


示例16: run_executor

            def run_executor(executor):
                # create an event loop in the executor thread
                loop = trollius.new_event_loop()
                trollius.set_event_loop(loop)
                eventlet.spawn(run_loop, loop)

                # run the executor
                executor.start()
                executor.wait()

                # stop the event loop: run_loop() will close it
                loop.stop()
开发者ID:apporc,项目名称:oslo.messaging,代码行数:12,代码来源:test_executor.py


示例17: start

 def start(self):
     self.isStopped = False
     self.loop = asyncio.new_event_loop()
     asyncio.set_event_loop(self.loop)
     self.face = ThreadsafeFace(self.loop, '')
     k = KeyChain()
     self.face.setCommandSigningInfo(k, k.getDefaultCertificateName())
     self.face.stopWhen(lambda:self.isStopped)
     try:
         self.loop.run_until_complete(self.sendNextInsertRequest())
     finally:
         self.face.shutdown()
开发者ID:thecodemaiden,项目名称:ndn-repo-3,代码行数:12,代码来源:bms_ping.py


示例18: test_run_from_running_loop

def test_run_from_running_loop():
    @asyncio.coroutine
    def foo():
        return bnra.available_devices()

    loop = bnra.new_file_event_loop()
    original_loop = asyncio.get_event_loop()

    asyncio.set_event_loop(loop)
    print(loop.run_until_complete(foo()))
    loop.stop()
    asyncio.set_event_loop(original_loop)
开发者ID:wheeler-microfluidics,项目名称:base-node-rpc,代码行数:12,代码来源:test_async.py


示例19: get_stock_data

 def get_stock_data(self):
     threads = []
     for index in range(self.request_num):
         threads.append(self.get_stocks_by_range(index))
         log.debug("url:%s  len:%s" % (self.sina_stock_api, len(self.stock_list[index])))
     try:
         loop = asyncio.get_event_loop()
     except RuntimeError:
         loop = asyncio.new_event_loop()
         asyncio.set_event_loop(loop)
     loop.run_until_complete(asyncio.wait(threads))
     log.debug("get_stock_data_loop")
     return self.format_response_data()
开发者ID:johnsonhongyi,项目名称:pyQuant,代码行数:13,代码来源:sina_data.py


示例20: setup_eventloop

 def setup_eventloop(self):
     """
     Sets up a new eventloop as the current one according to the OS.
     """
     if os.name == 'nt':
         self.eventloop = asyncio.ProactorEventLoop()
         if sys.version_info <= (3, 0):
             # FIXME: There appears to be a bug in the 2.7 version of trollius, wherein the selector retrieves an
             # object of value 0 and attempts to look for it in the weakref set, which raises an exception.
             # This hack sidesteps this issue, but does not solve it. If a proper fix is found, apply it!
             self.eventloop._selector._stopped_serving = set()
     else:
         self.eventloop = asyncio.new_event_loop()
     asyncio.set_event_loop(self.eventloop)
开发者ID:eaufavor,项目名称:pyshark-ssl,代码行数:14,代码来源:capture.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python trollius.sleep函数代码示例发布时间:2022-05-27
下一篇:
Python trollius.get_event_loop函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap