本文整理汇总了Python中pyee.EventEmitter类的典型用法代码示例。如果您正苦于以下问题:Python EventEmitter类的具体用法?Python EventEmitter怎么用?Python EventEmitter使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了EventEmitter类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: test_asyncio_error
def test_asyncio_error():
"""Test that event_emitters can handle errors when wrapping coroutines as
used with asyncio.
"""
loop = new_event_loop()
ee = EventEmitter(loop=loop)
should_call = Future(loop=loop)
@ee.on('event')
async def event_handler():
raise PyeeTestError()
@ee.on('error')
def handle_error(exc):
should_call.set_result(exc)
async def create_timeout(loop=loop):
await sleep(0.1, loop=loop)
if not should_call.done():
raise Exception('should_call timed out!')
return should_call.cancel()
timeout = create_timeout(loop=loop)
@should_call.add_done_callback
def _done(result):
assert isinstance(result, PyeeTestError)
ee.emit('event')
loop.run_until_complete(gather(should_call, timeout, loop=loop))
loop.close()
开发者ID:ethanaward,项目名称:pyee,代码行数:34,代码来源:test_async.py
示例2: __init__
def __init__(self, **kwargs):
EventEmitter.__init__(self)
for key, value in kwargs.iteritems():
setattr(self, key, value)
component_config = types.ComponentConfig(realm = u"sputnik")
wamp.ApplicationSessionFactory.__init__(self, config=component_config)
开发者ID:Mrkebubun,项目名称:sputnik-old,代码行数:7,代码来源:sputnik.py
示例3: __init__
def __init__(self, url, debug=False):
WebSocketClient.__init__(self, url)
EventEmitter.__init__(self)
self.debug = debug
self._session = None
self._uniq_id = 0
self._callbacks = {}
开发者ID:onepercentclub,项目名称:python-ddp,代码行数:7,代码来源:DDPClient.py
示例4: __init__
def __init__(self, address):
EventEmitter.__init__(self)
threading.Thread.__init__(self)
self.sp = serial.Serial(address, timeout=1)
self.alive = True
self.lock = threading.Lock()
开发者ID:LocoRobo,项目名称:python,代码行数:7,代码来源:serial_communication.py
示例5: PendingPacket
class PendingPacket():
def __init__(self, packet, packet_sender):
print 'Init PendingPacket'
self.ee = EventEmitter()
self._packet_sender = packet_sender
self._packet = packet
def send(self):
def packet_send():
self._packetSender.send(self._packet)
self._intervalID = helpers.set_interval(
packet_send,
constants.TIMEOUT
)
self._packet_sender.send(self._packet)
def get_sequence_number(self):
return self._packet.get_sequence_number()
def acknowledge(self):
self._intervalID.cancel()
self.ee.emit('acknowledge')
开发者ID:hoffmabc,项目名称:python-rudp,代码行数:26,代码来源:pendingpacket.py
示例6: Runner
class Runner(object):
def __init__(self, client, make_request):
self.client = client
self.make_request = make_request
self._pending = []
self.events = EventEmitter()
def _on_request_finished(self, _):
"""
Start the next waiting request if possible.
"""
if len(self.client.active) < self.client.max_clients:
self._start_request()
def _start_request(self):
"""
Start a request and add callbacks to its future.
Most notably, the completion of the requests's future will also trigger
the completion of a future we had prepared earlier.
"""
request = self.make_request(streaming_callback=lambda c: None)
future = concurrent.Future()
self.events.emit("request_ready", future, request)
self.client.fetch(request, callback=future.set_result)
self.events.emit("request_started", future)
self._pending.append(future)
future.add_done_callback(lambda f: self.events.emit("request_finished", f))
future.add_done_callback(self._pending.remove)
future.add_done_callback(self._on_request_finished)
开发者ID:nickcoutsos,项目名称:thuum,代码行数:34,代码来源:runners.py
示例7: __init__
def __init__(self, url, debug=False):
self.debug = debug
# by default socket connections don't timeout. this causes issues
# where reconnects can get stuck
# TODO: make this configurable?
socket.setdefaulttimeout(10)
WebSocketClient.__init__(self, url)
EventEmitter.__init__(self)
开发者ID:andrea689,项目名称:arduino-ciao-meteor-ddp-connector,代码行数:8,代码来源:DDPClient.py
示例8: __init__
def __init__(self, id=None, secret=None, endpoint="https://api.coinsetter.com/v1"):
EventEmitter.__init__(self)
self.username = id
self.password = secret
self.endpoint = endpoint
self.session_id = None
from urllib2 import urlopen
self.ip = json.load(urlopen('http://jsonip.com'))['ip']
开发者ID:Mrkebubun,项目名称:sputnik-old,代码行数:9,代码来源:coinsetter.py
示例9: __init__
def __init__(self, log, clock, script_path, id, app, name, popen=subprocess.Popen):
EventEmitter.__init__(self)
self.log = log
self.clock = clock
self.script_path = script_path
self.app = app
self.name = name
self.runner = None
self._name = "%s-%s-%s" % (id, app, name)
self._popen = popen
开发者ID:jrydberg,项目名称:hypervisor,代码行数:10,代码来源:runner.py
示例10: test_emit_return
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'))
开发者ID:Zearin,项目名称:pyee,代码行数:11,代码来源:tests.py
示例11: __init__
def __init__(self):
"""Constructor."""
# run the superclass constructor
EventEmitter.__init__(self)
self.type = None
self.control_elements = []
self.data_conditions = []
# sensor_id should be unique
rndnum = random.randint(0, 100000)
self.sensor_id = "sensor" + str(rndnum)
开发者ID:infant-cognition-tampere,项目名称:drop,代码行数:11,代码来源:Sensor.py
示例12: RegistrationOnlyEmitter
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)
开发者ID:BK-University,项目名称:mycroft-core,代码行数:11,代码来源:skill_tester.py
示例13: IncomingMessage
class IncomingMessage(object):
def __init__(self, im_id, size):
self.log = logging.getLogger(
'%s' % self.__class__.__name__
)
self.log.debug('New IncomingMessage Created')
self.im_id = im_id
self.size = size
self.ee = EventEmitter()
self.synced = False
self._next_sequence_number = 0
self._sync_sequence_number = None
self._packets = SortedList()
self.body = ''
self.waiting = False
def add_to_body(self, payload):
if payload in self.body:
self.log.debug('This content is already in the body.')
return
else:
self.body += payload
def reset(self):
self.log.debug('IncomingMessage Reset')
self.log.debug('Self Packets: %s', self._packets)
self._packets.clear()
self.synced = False
self._next_sequence_number = 0
self._sync_sequence_number = None
try:
self.log.debug('Downloaded (%s) | Total Size (%s)', len(self.body), self.size)
if len(self.body) >= int(self.size):
self.log.debug('Download Complete')
if len(self.body) > int(self.size):
self.log.debug('Oversized Message')
self.ee.emit('complete', {'body': self.body})
return
else:
# print self._message, self._message_size
self.log.debug('Still downloading...')
self.waiting = True
except Exception as e:
self.log.debug('Problem with resetting IncomingMessage: %s', e)
开发者ID:DevSlashNull,项目名称:OpenBazaar,代码行数:54,代码来源:receiver.py
示例14: test_emit_error
def test_emit_error():
ee = EventEmitter()
with nt.assert_raises(Exception):
ee.emit('error')
@ee.on('error')
def onError():
pass
# No longer raises and error instead return True indicating handled
nt.assert_true(ee.emit('error'))
开发者ID:Zearin,项目名称:pyee,代码行数:12,代码来源:tests.py
示例15: RegistrationOnlyEmitter
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
开发者ID:Ceda-EI,项目名称:mycroft-core,代码行数:31,代码来源:skill_tester.py
示例16: __init__
def __init__(self, clock, container, id, app, name,
image, command, config, port_pool, port):
EventEmitter.__init__(self)
self.clock = clock
self.id = id
self.app = app
self.name = name
self.image = image
self.command = command
self.config = config
self.port_pool = port_pool
self.port = port
self.state = 'init'
self._container = container
开发者ID:jrydberg,项目名称:hypervisor,代码行数:14,代码来源:proc.py
示例17: test_shorter_pattern
def test_shorter_pattern():
"""Tests correct behaviour with shorter patterns"""
ee = EventEmitter()
@ee.on('#')
def event_handler(ev):
raise ItWorkedException
with nt.assert_raises(ItWorkedException) as it_worked:
ee.emit('a/b/c')
with nt.assert_raises(ItWorkedException) as it_worked:
ee.emit('cool')
开发者ID:eagleamon,项目名称:pyee-topics,代码行数:14,代码来源:testmatching.py
示例18: test_twisted_emit
def test_twisted_emit():
"""Test that event_emitters can handle wrapping coroutines when using
twisted and ensureDeferred.
"""
ee = EventEmitter(scheduler=ensureDeferred)
should_call = Mock()
@ee.on('event')
async def event_handler():
should_call(True)
ee.emit('event')
should_call.assert_called_once()
开发者ID:ethanaward,项目名称:pyee,代码行数:15,代码来源:test_async.py
示例19: __init__
def __init__(self, url, auto_reconnect=True, auto_reconnect_timeout=0.5, debug=False):
EventEmitter.__init__(self)
self.collection_data = CollectionData()
self.ddp_client = DDPClient(url, auto_reconnect=auto_reconnect,
auto_reconnect_timeout=auto_reconnect_timeout, debug=debug)
self.ddp_client.on('connected', self.connected)
self.ddp_client.on('socket_closed', self.closed)
self.ddp_client.on('failed', self.failed)
self.ddp_client.on('added', self.added)
self.ddp_client.on('changed', self.changed)
self.ddp_client.on('removed', self.removed)
self.ddp_client.on('reconnected', self._reconnected)
self.connected = False
self.subscriptions = {}
self._login_data = None
开发者ID:feeloo007,项目名称:python-meteor,代码行数:15,代码来源:MeteorClient.py
示例20: __init__
def __init__(
self, # type: Any
addr, # type: str
port, # type: int
prot=default_protocol, # type: Protocol
out_addr=None, # type: Union[None, Tuple[str, int]]
debug_level=0 # type: int
): # type: (...) -> None
"""Initializes a peer to peer socket
Args:
addr: The address you wish to bind to (ie: "192.168.1.1")
port: The port you wish to bind to (ie: 44565)
prot: The protocol you wish to operate over, defined by a
:py:class:`py2p.base.Protocol` object
out_addr: Your outward facing address. Only needed if you're
connecting over the internet. If you use '0.0.0.0'
for the addr argument, this will automatically be
set to your LAN address.
debug_level: The verbosity you want this socket to use when
printing event data
Raises:
socket.error: The address you wanted could not be bound, or is
otherwise used
"""
object.__init__(self)
EventEmitter.__init__(self)
self.protocol = prot
self.debug_level = debug_level
self.routing_table = {} # type: Dict[bytes, BaseConnection]
# In format {ID: handler}
self.awaiting_ids = [] # type: List[BaseConnection]
# Connected, but not handshook yet
if out_addr: # Outward facing address, if you're port forwarding
self.out_addr = out_addr
elif addr == '0.0.0.0':
self.out_addr = get_lan_ip(), port
else:
self.out_addr = addr, port
info = (str(self.out_addr).encode(), prot.id.encode(), user_salt)
h = sha384(b''.join(info))
self.id = b58encode_int(int(h.hexdigest(), 16)).encode() # type: bytes
self._logger = getLogger('{}.{}.{}'.format(
self.__class__.__module__, self.__class__.__name__, self.id))
self.__handlers = [
] # type: List[Callable[[Message, BaseConnection], Union[bool, None]]]
self.__closed = False
开发者ID:gappleto97,项目名称:p2p-project,代码行数:48,代码来源:base.py
注:本文中的pyee.EventEmitter类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论