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

Python trollius.get_event_loop函数代码示例

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

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



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

示例1: _send_servo_commands

    def _send_servo_commands(self):
        servo_started_up = False

        while True:
            if ((not servo_started_up)
                and self.mech_driver
                and self.mech_driver.servo):
                servo_started_up = True
                # Reset all servos on startup, as they may have had an pending
                # error due to power glitch or something similar.
                self.logger.info('Rebooting servos on startup')
                yield From(self.mech_driver.servo.reboot())

            if not self.servo_send_now.is_set():
                # Make sure we wake up periodically
                asyncio.get_event_loop().call_later(
                    SERVO_SEND_INTERVAL, self.servo_send_now.set)
            yield From(self.servo_send_now.wait())
            self.servo_send_now.clear()

            new_pkt = self.net_packet
            old_pkt = self.servo_packet
            if new_pkt is not None:
                yield From(self._send_servo_commands_once(
                        new_pkt, old_pkt))
            self.servo_packet = new_pkt

            # send any status updates
            self.status_send_now.set()
开发者ID:mjbots,项目名称:mjmech,代码行数:29,代码来源:vserver.py


示例2: __init__

	def __init__(self, cameras=[], port=9004, users_file="users.json", recognition_db="recognition.db"):

		Server.__init__(self, port=port, usessl=False)

		self.recognition_db = recognition_db

		self.last_user_uuid = ""
		self.last_len_persons_detected = -1
		self.last_len_users = -1

		self.camera_clients = []
		self.recognizer = Recognizer(users_file)

		self.cameras = cameras
		self.start()

		self.method_handlers = {}
		self.method_handlers["list_users"] = self.list_users
		self.method_handlers["select_camera"] = self.select_camera
		self.method_handlers["list_users_with_level"] = self.list_users_with_level
		self.method_handlers["add_association"] = self.add_association

		self.users_recognized = []

		asyncio.get_event_loop().create_task(self.poll())
开发者ID:tripzero,项目名称:snetcam,代码行数:25,代码来源:recognitionserver2.py


示例3: __init__

	def __init__(self, name, processes=1, maxQueueSize=100, args=None):
		try:
			self.pool = []
			self.resultQueue = DeQueue(maxQueueSize)
			self.dataQueue = DeQueue(maxQueueSize)
			self.debugQueue = Queue()
			self.name = name
			self.variables = {}

			print ("processes for {} = {}".format(name, processes))

			for i in range(processes):
				if args:
					p = Process(target=self.process, args=args)
				else:
					p = Process(target=self.process)
				self.pool.append(p)
				p.start()

			asyncio.get_event_loop().create_task(self.poll())

		except:
			exc_type, exc_value, exc_traceback = sys.exc_info()
			traceback.print_tb(exc_traceback, limit=1, file=sys.stdout)
			traceback.print_exception(exc_type, exc_value, exc_traceback,
            	          limit=2, file=sys.stdout)
开发者ID:tripzero,项目名称:snetcam,代码行数:26,代码来源:imageresource.py


示例4: __init__

	def __init__(self, pollRate = MINS(10), port=9001, sslcert = "server.crt", sslkey= "server.key", privateKeyFile = 'dhserver.key', clientsFile = "clients.json"):
		Server.__init__(self, True, port, sslcert, sslkey, privateKeyFile = privateKeyFile, clientsFile = clientsFile)
		self.pollRate = pollRate
		self.port = port

		self.numclients = len(self.clients)
		
		asyncio.get_event_loop().create_task(self.poll())
开发者ID:tripzero,项目名称:snetcam,代码行数:8,代码来源:wsresource.py


示例5: test_send_error

 def test_send_error(self):
     """An error in sending must be reported through the future."""
     # Create a stream with a packet size that is bigger than the likely
     # MTU. It should cause an error.
     stream = UdpStream(
         spead2.ThreadPool(), "localhost", 8888,
         spead2.send.StreamConfig(max_packet_size=100000), buffer_size=0)
     future = stream.async_send_heap(self.heap)
     trollius.get_event_loop().run_until_complete(self._test_send_error(future))
开发者ID:shaoguangleo,项目名称:spead2,代码行数:9,代码来源:test_send_trollius.py


示例6: test_async_flush_fail

 def test_async_flush_fail(self):
     """Test async_flush in the case that the last heap sent failed.
     This is arranged by filling up the queue slots first.
     """
     for i in range(5):
         trollius.async(self.stream.async_send_heap(self.heap))
     # The above only queues up the async sends on the event loop. The rest of the
     # test needs to be run from inside the event loop
     trollius.get_event_loop().run_until_complete(self._test_async_flush())
开发者ID:shaoguangleo,项目名称:spead2,代码行数:9,代码来源:test_send_trollius.py


示例7: session_made

 def session_made(self, conn):
     """
     called when we established a session to the router
     we can look up names/b32 but can't send messages to others yet
     :param conn: our i2cp connection that we are using
     """
     self.conn = conn
     self._log.info('session made we are {}'.format(conn.dest))
     asyncio.get_event_loop().call_later(self._delay, self._send)
开发者ID:majestrate,项目名称:python-i2cp,代码行数:9,代码来源:__main__.py


示例8: main

def main():
    logging.basicConfig(level=logging.WARN, stream=sys.stdout)

    parser = optparse.OptionParser(description=__doc__)

    MechDriver.add_options(parser)

    options, args = parser.parse_args()

    task = Task(start(options))
    asyncio.get_event_loop().run_until_complete(task)
开发者ID:HermanHGF,项目名称:legtool,代码行数:11,代码来源:gait_driver.py


示例9: onJoin

	def onJoin(self, details):
		print("Session Joined.")
		#Setting variables
		self.lastServoValue = 417 #Assumes it starts in the middle
		self.servoMin = 315  # Min pulse length out of 4096
		self.servoMax = 520  # Max pulse length out of 4096
		self.servoMiddle = 417 # middle servo value
		self.servoChannel = 3        
		print "What is happening????"
		self.motorMiddle = 1500
		self.motorChannel = 2
		self.subscribe(self.joyMonitor, 'aero.near.joystream')
		print "joystream ok"
		#subscribe to methods to prevent register conflicts
		self.subscribe(self.honkCommand, 'aero.near.honkHorn')
		print "honk ok"
		self.subscribe(self.emergencyStop, 'aero.near.emergStop')
		print "emergstop ok"
		self.subscribe(self.manualOverride, 'aero.near.override')
		print "About to make the loop"
		self.gps_data = {'latitude': 0,'longitude': 0,'heading': 0,'speed': 0}
		
 		self.loop = asyncio.get_event_loop()
#		self.loop.stop()
#		future = asyncio.Future()
#		print "the future exists"
#		asyncio.async(self.gpsUpdate())
#		self.loop.run_until_complete(future)
#		self.loop = asyncio.new_event_loop()
# 		tasks = [
# 			asyncio.async(self.honk()),
# #			asyncio.async(self.lidarRead())]
# #			asyncio.async(self.gpsUpdate())]
# #			asyncio.async(self.internet_on())]
# 		print tasks
# 		swag.system('cls' if swag.name == 'nt' else 'clear')
# 		try:
		self.loop = asyncio.get_event_loop()
		tasks = [
			asyncio.async(self.netDisconnect())]
		print tasks
		try:
			done, pending = yield self.loop.run_until_complete(asyncio.wait(tasks))
		except Exception as e:
			print e
		print tasks
		#print "running"
		self.loop.close()
# 			done, pending = yield self.loop.run_until_complete(asyncio.wait(tasks))
# 		except Exception as e:
			# print e
		# print tasks
		print "running"
开发者ID:ThomasBassa,项目名称:near-netcar,代码行数:53,代码来源:pi-master+(testing).py


示例10: _connect_dual_stack

    def _connect_dual_stack(self, primary_address, secondary_address):
        '''Connect using happy eyeballs.'''
        self._primary_connection = self._connection_factory(primary_address)
        self._secondary_connection = self._connection_factory(secondary_address)

        @trollius.coroutine
        def connect_primary():
            yield From(self._primary_connection.connect())
            raise Return(self._primary_connection)

        @trollius.coroutine
        def connect_secondary():
            yield From(self._secondary_connection.connect())
            raise Return(self._secondary_connection)

        primary_fut = connect_primary()
        secondary_fut = connect_secondary()

        failed = False

        for fut in trollius.as_completed((primary_fut, secondary_fut)):
            if not self._active_connection:
                try:
                    self._active_connection = yield From(fut)
                except NetworkError:
                    if not failed:
                        _logger.debug('Original dual stack exception', exc_info=True)
                        failed = True
                    else:
                        raise
                else:
                    _logger.debug('Got first of dual stack.')

            else:
                @trollius.coroutine
                def cleanup():
                    try:
                        conn = yield From(fut)
                    except NetworkError:
                        pass
                    else:
                        conn.close()
                    _logger.debug('Closed abandoned connection.')

                trollius.get_event_loop().create_task(cleanup())

        if self._active_connection.address == secondary_address:
            preferred_addr = secondary_address
        else:
            preferred_addr = primary_address

        self._happy_eyeballs_table.set_preferred(preferred_addr, primary_address, secondary_address)
开发者ID:Willianvdv,项目名称:wpull,代码行数:52,代码来源:connection.py


示例11: _start_tls

    def _start_tls(self):
        '''Start SSL protocol on the socket.'''
        socket_ = self._writer.get_extra_info('socket')

        try:
            trollius.get_event_loop().remove_reader(socket_.fileno())
        except ValueError as error:
            raise trollius.ConnectionAbortedError() from error

        self._writer.write(b'HTTP/1.1 200 Connection established\r\n\r\n')
        yield From(self._writer.drain())

        try:
            trollius.get_event_loop().remove_writer(socket_.fileno())
        except ValueError as error:
            raise trollius.ConnectionAbortedError() from error

        ssl_socket = ssl.wrap_socket(
            socket_, server_side=True,
            certfile=self._cert_filename,
            keyfile=self._key_filename,
            do_handshake_on_connect=False
        )

        # FIXME: this isn't how to START TLS
        for dummy in range(1200):
            try:
                ssl_socket.do_handshake()
                break
            except ssl.SSLError as error:
                if error.errno in (ssl.SSL_ERROR_WANT_READ, ssl.SSL_ERROR_WANT_WRITE):
                    _logger.debug('Do handshake %s', error)
                    yield From(trollius.sleep(0.05))
                else:
                    raise
        else:
            _logger.error(_('Unable to handshake.'))
            ssl_socket.close()
            self._reject_request('Could not start TLS')
            raise trollius.ConnectionAbortedError('Could not start TLS')

        loop = trollius.get_event_loop()
        reader = trollius.StreamReader(loop=loop)
        protocol = trollius.StreamReaderProtocol(reader, loop=loop)
        transport, dummy = yield From(loop.create_connection(
            lambda: protocol, sock=ssl_socket))
        writer = trollius.StreamWriter(transport, protocol, reader, loop)

        self._reader = reader
        self._writer = writer
开发者ID:Willianvdv,项目名称:wpull,代码行数:50,代码来源:server.py


示例12: __init__

    def __init__(self, config_file):
        super(Tourbillon, self).__init__()

        self._aio_run_event = asyncio.Event()
        self._thr_run_event = threading.Event()
        self._loop = asyncio.get_event_loop()
        self._tasks = []
        self._pluginconfig = {}

        with open(config_file, 'r') as f:
            self._config = json.load(f)

        formatter = logging.Formatter(fmt=self._config['log_format'])
        handler = logging.handlers.WatchedFileHandler(
            self._config['log_file'])
        handler.setFormatter(formatter)
        handler.setLevel(getattr(logging, self._config['log_level']))
        logging.getLogger().addHandler(handler)
        logging.getLogger().setLevel(
            getattr(logging, self._config['log_level']))

        logger.info('Use config file: %s', config_file)

        self._load_plugins_config(os.path.abspath(
                                  os.path.dirname(config_file)))

        self._influxdb = InfluxDBClient(**self._config['database'])
        self._databases = [i['name']
                           for i in self._influxdb.get_list_database()]
        print(self._databases)
开发者ID:orfeu65,项目名称:tourbillon-agent,代码行数:30,代码来源:agent.py


示例13: test_queue_overload

    def test_queue_overload(self):

        http = HTTPConnectionPool('httpbin.org', maxsize=3, block=True, timeout=3)

        testLoop = asyncio.get_event_loop()
        testLoop.set_debug(True)
        global test_queue_overload_count
        test_queue_overload_count = 0

        @asyncio.coroutine
        def get_page():
            global test_queue_overload_count
            try:
                resp = yield From(http.request('GET', '/delay/1', pool_timeout=3))
                pg = yield From(resp.data)
                self.assertTrue(b'Connection' in pg, pg)
            except EmptyPoolError:
                pass
            except Exception as e:
                raise
            else:
                test_queue_overload_count += 1

        pageGetters = [get_page(), get_page(), get_page(), get_page(), get_page()]
        testLoop.run_until_complete(asyncio.wait(pageGetters, return_when=asyncio.ALL_COMPLETED))
        self.assertGreater(test_queue_overload_count, 4, 'not all page_getters ran')
开发者ID:andrewleech,项目名称:yieldfromUrllib3_trollius,代码行数:26,代码来源:test_pool_overload.py


示例14: __init__

 def __init__(self, log, max_pool=10, max_tasks=5):
     self.log = log
     self.max_pool = max_pool  # Overall limit.
     self.max_tasks = max_tasks  # Per-key limit.
     self.loop = asyncio.get_event_loop()
     self.connections = {}  # {(host, port, ssl): [Connection, ...], ...}
     self.queue = []  # [Connection, ...]
开发者ID:JioCloudCompute,项目名称:trollius,代码行数:7,代码来源:crawl.py


示例15: main

def main():
    global SERVER

    try:
        loop = trollius.get_event_loop()
        coro = trollius.start_server(
            handle_client,
            host=None,
            port=pagure.APP.config['EVENTSOURCE_PORT'],
            loop=loop)
        SERVER = loop.run_until_complete(coro)
        log.info('Serving server at {}'.format(SERVER.sockets[0].getsockname()))
        if pagure.APP.config.get('EV_STATS_PORT'):
            stats_coro = trollius.start_server(
                stats,
                host=None,
                port=pagure.APP.config.get('EV_STATS_PORT'),
                loop=loop)
            stats_server = loop.run_until_complete(stats_coro)
            log.info('Serving stats  at {}'.format(
                stats_server.sockets[0].getsockname()))
        loop.run_forever()
    except KeyboardInterrupt:
        pass
    except trollius.ConnectionResetError:
        pass

    # Close the server
    SERVER.close()
    if pagure.APP.config.get('EV_STATS_PORT'):
        stats_server.close()
    log.info("End Connection")
    loop.run_until_complete(server.wait_closed())
    loop.close()
    log.info("End")
开发者ID:tenstormavi,项目名称:pagure,代码行数:35,代码来源:pagure-stream-server.py


示例16: connect_read_pipe

def connect_read_pipe(file):
    loop = asyncio.get_event_loop()
    stream_reader = asyncio.StreamReader(loop=loop)
    def factory():
        return asyncio.StreamReaderProtocol(stream_reader)
    transport, _ = yield From(loop.connect_read_pipe(factory, file))
    raise Return(stream_reader, transport)
开发者ID:JioCloudCompute,项目名称:trollius,代码行数:7,代码来源:child_process.py


示例17: __init__

 def __init__(self, *args, **kwargs):
     self._loop = kwargs.pop('loop', None)
     super(Wrapped, self).__init__(*args, **kwargs)
     if self._loop is None:
         self._loop = trollius.get_event_loop()
     self._active = 0
     self._last_queued_future = None
开发者ID:ska-sa,项目名称:spead2,代码行数:7,代码来源:trollius.py


示例18: ThriftAsyncServerFactory

def ThriftAsyncServerFactory(
    processor, interface=None, port=0, loop=None, nthreads=None, sock=None,
    backlog=100
):
    if loop is None:
        loop = asyncio.get_event_loop()

    if not isinstance(processor, TProcessor):
        try:
            processor = processor._processor_type(processor, loop=loop)
        except AttributeError:
            raise TypeError(
                "Unsupported processor type: {}".format(type(processor)),
            )

    if nthreads:
        from concurrent.futures import ThreadPoolExecutor
        loop.set_default_executor(
            ThreadPoolExecutor(max_workers=nthreads),
        )
    event_handler = TServerEventHandler()
    pfactory = ThriftServerProtocolFactory(processor, event_handler, loop)
    server = yield From(loop.create_server(
        pfactory,
        interface,
        port,
        sock=sock,
        backlog=backlog,
    ))

    if server.sockets:
        for socket in server.sockets:
            event_handler.preServe(socket.getsockname())

    raise Return(server)
开发者ID:ConfusedReality,项目名称:pkg_serialization_fbthrift,代码行数:35,代码来源:TTrolliusServer.py


示例19: analyze_body

def analyze_body(sdf, address=("127.0.0.1", 11346)):
    """
    Single body analyzer. Opens a new connection, analyzes the
    body, and returns the result. If you already have a manager
    running doing other things, create an instance of `BodyAnalyzer`
    instead.

    :param sdf: SDF object consisting of BodyPart
                instances.
    :type sdf: SDF
    :param address: Tuple of the hostname and port where the analyzer resides. Note
                    that the default is one up from the default Gazebo port,
                    since it is meant to be used with the `run-analyzer.sh` tool.
    :type address: (str, int)
    :return:
    :rtype: (bool, (float, float, float))
    """
    response_obj = [None]

    @trollius.coroutine
    def internal_analyze():
        analyzer = yield From(BodyAnalyzer.create(address))
        response_obj[0] = yield From(analyzer.analyze_sdf(sdf))

    loop = trollius.get_event_loop()
    loop.run_until_complete(internal_analyze())
    return response_obj[0]
开发者ID:ElteHupkes,项目名称:revolve,代码行数:27,代码来源:analyze.py


示例20: produce_record

    def produce_record(self, stream, key, data):
        record = Record(key, data, stream)
        stream = self.runner.streams[stream]

        loop = trollius.get_event_loop()
        for subscriber in stream.subscribers:
            loop.call_soon(subscriber.process_record, self, record)
开发者ID:ADI-Labs,项目名称:concord-local,代码行数:7,代码来源:concord_local.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python trollius.set_event_loop函数代码示例发布时间:2022-05-27
下一篇:
Python utils.get_total函数代码示例发布时间: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