本文整理汇总了Python中pyee.EventEmitter.on方法的典型用法代码示例。如果您正苦于以下问题:Python EventEmitter.on方法的具体用法?Python EventEmitter.on怎么用?Python EventEmitter.on使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyee.EventEmitter
的用法示例。
在下文中一共展示了EventEmitter.on方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: RegistrationOnlyEmitter
# 需要导入模块: from pyee import EventEmitter [as 别名]
# 或者: from pyee.EventEmitter import on [as 别名]
class RegistrationOnlyEmitter(object):
def __init__(self):
self.emitter = EventEmitter()
def on(self, event, f):
allow_events_to_execute = True
if allow_events_to_execute:
# don't filter events, just run them all
print "Event: "+str(event)
self.emitter.on(event, f)
else:
# filter to just the registration events,
# preventing them from actually executing
if event in [
'register_intent',
'register_vocab',
'recognizer_loop:utterance'
]:
print "Event: " + str(event)
self.emitter.on(event, f)
def emit(self, event, *args, **kwargs):
event_name = event.type
self.emitter.emit(event_name, event, *args, **kwargs)
def once(self, event, f):
self.emitter.once(event, f)
def remove(self, event_name, func):
pass
示例2: InterceptEmitter
# 需要导入模块: from pyee import EventEmitter [as 别名]
# 或者: from pyee.EventEmitter import on [as 别名]
class InterceptEmitter(object):
"""
This class intercepts and allows emitting events between the
skill_tester and the skill being tested.
When a test is running emitted communication is intercepted for analysis
"""
def __init__(self):
self.emitter = EventEmitter()
self.q = None
def on(self, event, f):
# run all events
print("Event: ", event)
self.emitter.on(event, f)
def emit(self, event, *args, **kwargs):
event_name = event.type
if self.q:
self.q.put(event)
self.emitter.emit(event_name, event, *args, **kwargs)
def once(self, event, f):
self.emitter.once(event, f)
def remove(self, event_name, func):
pass
def remove_all_listeners(self, event_name):
pass
示例3: test_emit_return
# 需要导入模块: from pyee import EventEmitter [as 别名]
# 或者: from pyee.EventEmitter import on [as 别名]
def test_emit_return():
ee = EventEmitter()
# make sure emission without callback retruns False
nt.assert_false(ee.emit('data'))
# add a callback
ee.on('data')(lambda: None)
# should return true now
nt.assert_true(ee.emit('data'))
示例4: RegistrationOnlyEmitter
# 需要导入模块: from pyee import EventEmitter [as 别名]
# 或者: from pyee.EventEmitter import on [as 别名]
class RegistrationOnlyEmitter(object):
def __init__(self):
self.emitter = EventEmitter()
def on(self, event, f):
if event in ['register_intent', 'register_vocab', 'recognizer_loop:utterance']:
self.emitter.on(event, f)
def emit(self, event, *args, **kwargs):
event_name = event.message_type
self.emitter.emit(event_name, event, *args, **kwargs)
示例5: __init__
# 需要导入模块: from pyee import EventEmitter [as 别名]
# 或者: from pyee.EventEmitter import on [as 别名]
class WebsocketClient:
def __init__(self, host=None, port=None, route=None, ssl=None):
config = Configuration.get().get("websocket")
host = host or config.get("host")
port = port or config.get("port")
route = route or config.get("route")
ssl = ssl or config.get("ssl")
validate_param(host, "websocket.host")
validate_param(port, "websocket.port")
validate_param(route, "websocket.route")
self.url = WebsocketClient.build_url(host, port, route, ssl)
self.emitter = EventEmitter()
self.client = self.create_client()
self.pool = ThreadPool(10)
self.retry = 5
self.connected_event = Event()
self.started_running = False
@staticmethod
def build_url(host, port, route, ssl):
scheme = "wss" if ssl else "ws"
return scheme + "://" + host + ":" + str(port) + route
def create_client(self):
return WebSocketApp(self.url,
on_open=self.on_open, on_close=self.on_close,
on_error=self.on_error, on_message=self.on_message)
def on_open(self, ws):
LOG.info("Connected")
self.connected_event.set()
self.emitter.emit("open")
# Restore reconnect timer to 5 seconds on sucessful connect
self.retry = 5
def on_close(self, ws):
self.emitter.emit("close")
def on_error(self, ws, error):
""" On error start trying to reconnect to the websocket. """
if isinstance(error, WebSocketConnectionClosedException):
LOG.warning('Could not send message because connection has closed')
else:
LOG.exception('=== ' + repr(error) + ' ===')
try:
self.emitter.emit('error', error)
if self.client.keep_running:
self.client.close()
except Exception as e:
LOG.error('Exception closing websocket: ' + repr(e))
LOG.warning("WS Client will reconnect in %d seconds." % self.retry)
time.sleep(self.retry)
self.retry = min(self.retry * 2, 60)
try:
self.emitter.emit('reconnecting')
self.client = self.create_client()
self.run_forever()
except WebSocketException:
pass
def on_message(self, ws, message):
self.emitter.emit('message', message)
parsed_message = Message.deserialize(message)
self.pool.apply_async(
self.emitter.emit, (parsed_message.type, parsed_message))
def emit(self, message):
if not self.connected_event.wait(10):
if not self.started_running:
raise ValueError('You must execute run_forever() '
'before emitting messages')
self.connected_event.wait()
try:
if hasattr(message, 'serialize'):
self.client.send(message.serialize())
else:
self.client.send(json.dumps(message.__dict__))
except WebSocketConnectionClosedException:
LOG.warning('Could not send {} message because connection '
'has been closed'.format(message.type))
def wait_for_response(self, message, reply_type=None, timeout=None):
"""Send a message and wait for a response.
Args:
message (Message): message to send
reply_type (str): the message type of the expected reply.
Defaults to "<message.type>.response".
timeout: seconds to wait before timeout, defaults to 3
Returns:
The received message or None if the response timed out
"""
response = []
def handler(message):
#.........这里部分代码省略.........
示例6: addEventListener
# 需要导入模块: from pyee import EventEmitter [as 别名]
# 或者: from pyee.EventEmitter import on [as 别名]
def addEventListener(emitter: EventEmitter, eventName: str, handler: Callable
) -> Dict[str, Any]:
"""Add handler to the emitter and return emitter/handler."""
emitter.on(eventName, handler)
return {'emitter': emitter, 'eventName': eventName, 'handler': handler}
示例7: WebsocketClient
# 需要导入模块: from pyee import EventEmitter [as 别名]
# 或者: from pyee.EventEmitter import on [as 别名]
class WebsocketClient(object):
def __init__(self, host=config.get("Websocket", "host"), port=int(config.get("Websocket", "port")),
route=config.get("Websocket", "route"), ssl=config.getboolean("Websocket", "ssl")):
validate_param(host, "websocket.host")
validate_param(port, "websocket.port")
validate_param(route, "websocket.route")
self.build_url(host, port, route, ssl)
self.emitter = EventEmitter()
self.client = self.create_client()
self.pool = ThreadPool(10)
self.retry = 5
def build_url(self, host, port, route, ssl):
scheme = "wss" if ssl else "ws"
self.url = scheme + "://" + host + ":" + str(port) + route
def create_client(self):
return WebSocketApp(self.url,
on_open=self.on_open, on_close=self.on_close,
on_error=self.on_error, on_message=self.on_message)
def on_open(self, ws):
LOG.info("Connected")
self.emitter.emit("open")
def on_close(self, ws):
self.emitter.emit("close")
def on_error(self, ws, error):
try:
self.emitter.emit('error', error)
self.client.close()
except Exception as e:
LOG.error(repr(e))
LOG.warn("WS Client will reconnect in %d seconds." % self.retry)
time.sleep(self.retry)
self.retry = min(self.retry * 2, 60)
self.client = self.create_client()
self.run_forever()
def on_message(self, ws, message):
self.emitter.emit('message', message)
parsed_message = Message.deserialize(message)
self.pool.apply_async(
self.emitter.emit, (parsed_message.type, parsed_message))
def emit(self, message):
if (not self.client or not self.client.sock or
not self.client.sock.connected):
return
if hasattr(message, 'serialize'):
self.client.send(message.serialize())
else:
self.client.send(json.dumps(message.__dict__))
def on(self, event_name, func):
self.emitter.on(event_name, func)
def once(self, event_name, func):
self.emitter.once(event_name, func)
def remove(self, event_name, func):
self.emitter.remove_listener(event_name, func)
def run_forever(self):
self.client.run_forever()
def close(self):
self.client.close()
示例8: WebsocketClient
# 需要导入模块: from pyee import EventEmitter [as 别名]
# 或者: from pyee.EventEmitter import on [as 别名]
class WebsocketClient(object):
def __init__(self, host=None, port=None, route=None, ssl=None):
config = Configuration.get().get("websocket")
host = host or config.get("host")
port = port or config.get("port")
route = route or config.get("route")
ssl = ssl or config.get("ssl")
validate_param(host, "websocket.host")
validate_param(port, "websocket.port")
validate_param(route, "websocket.route")
self.url = WebsocketClient.build_url(host, port, route, ssl)
self.emitter = EventEmitter()
self.client = self.create_client()
self.pool = ThreadPool(10)
self.retry = 5
@staticmethod
def build_url(host, port, route, ssl):
scheme = "wss" if ssl else "ws"
return scheme + "://" + host + ":" + str(port) + route
def create_client(self):
return WebSocketApp(self.url,
on_open=self.on_open, on_close=self.on_close,
on_error=self.on_error, on_message=self.on_message)
def on_open(self, ws):
LOG.info("Connected")
self.emitter.emit("open")
# Restore reconnect timer to 5 seconds on sucessful connect
self.retry = 5
def on_close(self, ws):
self.emitter.emit("close")
def on_error(self, ws, error):
try:
self.emitter.emit('error', error)
self.client.close()
except Exception as e:
LOG.error(repr(e))
LOG.warning("WS Client will reconnect in %d seconds." % self.retry)
time.sleep(self.retry)
self.retry = min(self.retry * 2, 60)
self.client = self.create_client()
self.run_forever()
def on_message(self, ws, message):
self.emitter.emit('message', message)
parsed_message = Message.deserialize(message)
self.pool.apply_async(
self.emitter.emit, (parsed_message.type, parsed_message))
def emit(self, message):
if (not self.client or not self.client.sock or
not self.client.sock.connected):
return
if hasattr(message, 'serialize'):
self.client.send(message.serialize())
else:
self.client.send(json.dumps(message.__dict__))
def on(self, event_name, func):
self.emitter.on(event_name, func)
def once(self, event_name, func):
self.emitter.once(event_name, func)
def remove(self, event_name, func):
self.emitter.remove_listener(event_name, func)
def remove_all_listeners(self, event_name):
'''
Remove all listeners connected to event_name.
Args:
event_name: event from which to remove listeners
'''
if event_name is None:
raise ValueError
self.emitter.remove_all_listeners(event_name)
def run_forever(self):
self.client.run_forever()
def close(self):
self.client.close()