本文整理汇总了Python中pubsub.pub.subscribe函数的典型用法代码示例。如果您正苦于以下问题:Python subscribe函数的具体用法?Python subscribe怎么用?Python subscribe使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了subscribe函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: init
def init(serv):
serv.loadConfig(populate=False)
# Minecraft part of the Hub
wsFactory = serv.factories["WorldServerFactory"] = WorldServerFactory(serv)
# Populate configuration.
serv.populateConfig()
# Load up the database.
serv.loadDatabase()
# Start up everything.
# Until Endpoint has reconnection abilities, this is unused
#TCP4ClientEndpoint(reactor, serv.settings["world"]["main"]["hub-ip"],
# serv.settings["world"]["main"]["hub-port"]).connect(serv.factories["WorldServerFactory"]).addCallback(serv.factories["WorldServerFactory"])
def afterLoadedPreloadedWorlds():
reactor.connectTCP(wsFactory.settings["main"]["hub-ip"], wsFactory.settings["main"]["hub-port"], wsFactory)
def afterLoadedSelfID():
serv.factories["WorldServerFactory"].loadPreloadedWorlds().addCallback(noArgs(afterLoadedPreloadedWorlds))
def afterDBAPIReady():
# Get our ID
wsFactory.loadID().addCallback(noArgs(afterLoadedSelfID))
pub.subscribe(afterDBAPIReady, "cloudbox.common.service.databaseAPIReady")
reactor.run()
示例2: __init__
def __init__(self):
"""Constructor"""
screenwidth = root.winfo_screenwidth()
screenheight = root.winfo_screenheight()
Tk.Toplevel.__init__(self)
self.overrideredirect(True)
self.geometry("{0}x{1}+0+0".format(screenwidth, screenheight))
canvasFrame = Tk.Frame(self, width = screenwidth, height = (screenheight - 100))
instructionFrame = Tk.Frame(self, width = screenwidth, height = 50)
self.canvas = Tk.Canvas(canvasFrame, width = screenwidth, height = (screenheight - 100))
# create the button
calibrateButton = Tk.Button(instructionFrame, text="Start Calibration", command=self.ovalChange)
exitButton = Tk.Button(instructionFrame, text="Quit", command=self.quitCal)
canvasFrame.grid()
instructionFrame.grid(row = 1)
self.canvas.grid()
calibrateButton.grid(column = 0)
exitButton.grid(column = 1, row = 0)
pub.subscribe(self.listener, "userFrameClosed")
示例3: __init__
def __init__(self, rect):
super(TrackButtonBar, self).__init__()
self.selected_index = 0
self.tiles_to_show = 0
self.rect = rect
self.dirty = True
pub.subscribe(self.on_key_up, "input.key-up")
示例4: __init__
def __init__(self):
self.poller = select.poll()
pub.subscribe(tracelogger, pub.ALL_TOPICS)
pub.sendMessage('lifecycle', msg='Starting up')
# Register modules
handlers.insteon.InsteonHandler(self, dev='/dev/ttyS0')
handlers.tcpsocket.TCPHandler(self, port=2062)
Arduino(self,dev='/dev/ttyACM0')
holdme = Light(self)
holdme2 = ZabbixPush(self)
testdev = X10('fishtank', 'L4', False)
#self.add_io_handler(sys.stdin.fileno(), stdinhandler)
# load configs?
# main loop
pub.sendMessage('lifecycle', msg='Starting main loop')
while (True):
try:
active=self.poller.poll()
for (fd, event) in active:
# Call the FD event handler
for i in self.FDs:
if i.fileno() == fd:
self.FDs[i](i, event)
break
except KeyboardInterrupt:
break
pub.sendMessage('lifecycle', msg='Quiting')
示例5: __init__
def __init__(self):
pub.subscribe(self.queue_file, 'new_file')
pub.subscribe(self.stop, 'wants_to_close')
self.thread = None
self.running = False
self.queue = queue.Queue()
示例6: test_pubsub
def test_pubsub(self):
# Subscribe so we can catch the status update as it comes out.
nodeuuid = str(uuid.uuid4())
self.configuration.set_node_uuid(nodeuuid)
job_id = str(uuid.uuid4())
pub.subscribe(self.on_job_status_update, self.configuration.get_job_status_pub_topic(job_id))
# Now send off a job update. This should exit via the pub/sub system, but be dropped
# on the incoming side.
self.configuration.send_job_status(job_id, state='TEST')
status = self.wait()
self.assertEquals(status.job_id, job_id, "Job ID was not as expected.")
self.assertEquals(status.state, 'TEST', "Job status was not as expected.")
# Now, manually send a status and force it to go via the pub/sub system and
# back out again.
job_id = str(uuid.uuid4())
pub.subscribe(self.on_job_status_update, self.configuration.get_job_status_pub_topic(job_id))
message = paasmaker.common.configuration.JobStatusMessage(job_id, 'ROUNDTRIP', 'BOGUS')
message.unittest_override = True
self.backend.send_job_status(message)
status = self.wait()
self.assertEquals(status.job_id, job_id, "Job ID was not as expected.")
self.assertEquals(status.state, 'ROUNDTRIP', "Job status was not as expected.")
self.assertEquals(status.source, 'BOGUS', 'Source was correct.')
示例7: testDeadListener
def testDeadListener():
# create a listener for listeners that have died
class DeathListener(IgnoreNotificationsMixin):
listenerStr = ''
def notifyDeadListener(self, pubListener, topicObj):
assert topicObj.getName() == 'sadTopic'
#import pdb; pdb.set_trace()
#print 'hi again'
DeathListener.listenerStr = pubListener.name()
dl = DeathListener()
pub.addNotificationHandler( dl )
pub.setNotificationFlags(deadListener=True)
# define a topic, subscribe to it, and kill its listener:
class TempListener:
def __call__(self, **kwargs):
pass
def __del__(self):
# print 'being deleted'
pass
#def tempListener(): pass
tempListener = TempListener()
expectLisrStr, _ = getListenerID(tempListener)
pub.subscribe(tempListener, 'sadTopic')
del tempListener
# verify:
gc.collect() # for pypy: the gc doesn't work the same as cpython's
assert DeathListener.listenerStr.startswith(expectLisrStr), \
'"%s" !~ "%s"' % (DeathListener.listenerStr, expectLisrStr)
pub.addNotificationHandler(None)
pub.clearNotificationHandlers()
示例8: __init__
def __init__(self, parent, global_store, vsrc_name, *args, **kwargs):
# If the device doesn't exist, give up.
try:
vsrc = global_store.devices[vsrc_name].device
except (KeyError, AttributeError):
self.Destroy()
return
Dialog.__init__(self, parent, title='Voltage source settings', *args, **kwargs)
self.vsrc_name = vsrc_name
# Dialog.
dialog_box = wx.BoxSizer(wx.VERTICAL)
## Settings panel.
self.panel = VoltageSourceSettingsPanel(self, global_store, vsrc)
dialog_box.Add(self.panel)
self.SetSizerAndFit(dialog_box)
# Subscriptions.
pub.subscribe(self.msg_device, 'device.added')
pub.subscribe(self.msg_device, 'device.removed')
示例9: test_track_event_seveal_subscriptions
def test_track_event_seveal_subscriptions(self):
c = peachbox.scheduler.ConditionalEvent('c5')
e1 = peachbox.scheduler.Event('finished')
status = e1.status()
status['payload'] = {'latest_kafka_offset':123}
e2 = peachbox.scheduler.Event('timer')
status2 = e2.status()
status2['payload'] = {'timestamp':123456}
c.subscribe(e1)
c.subscribe(e2)
def receiver(param):
self.assertEqual(123, param['payload']['latest_kafka_offset'])
self.assertEqual(123456, param['payload']['timestamp'])
pub.subscribe(receiver, c.name())
def publish_in_process(event):
self.s.publish(event)
p1 = multiprocessing.Process(target=self.s.publish, args=(e1,))
p2 = multiprocessing.Process(target=self.s.publish, args=(e2,))
p1.start()
p2.start()
p1.join()
p2.join()
# Check if the counters are reset
subscriptions = c.get_subscriptions()
self.assertEqual({'finished':1, 'timer':1}, subscriptions)
示例10: __init__
def __init__(self, parent):
super(OverviewWidget, self).__init__(parent)
self.label = QtGui.QLabel("Asymmetry")
self.parent = parent
self.active = False
self.left_front = OverviewView(self, "Left Front", 0)
self.left_hind = OverviewView(self, "Left Hind", 1)
self.right_front = OverviewView(self, "Right Front", 2)
self.right_hind = OverviewView(self, "Right Hind", 3)
self.overview_list = [self.left_front,
self.left_hind,
self.right_front,
self.right_hind]
self.asymmetry_layout = QtGui.QGridLayout()
self.asymmetry_layout.addWidget(self.left_front, 1, 0)
self.asymmetry_layout.addWidget(self.left_hind, 2, 0)
self.asymmetry_layout.addWidget(self.right_front, 1, 1)
self.asymmetry_layout.addWidget(self.right_hind, 2, 1)
self.main_layout = QtGui.QVBoxLayout()
self.main_layout.addLayout(self.asymmetry_layout)
self.main_layout.addStretch(1)
self.setLayout(self.main_layout)
pub.subscribe(self.active_widget, "active_widget")
示例11: testNotifyByPrint
def testNotifyByPrint():
capture = captureStdout()
def listener1(arg1):
pass
pub.subscribe(listener1, 'baz')
pub.sendMessage('baz', arg1=123)
pub.unsubscribe(listener1, 'baz')
def doa():
def listener2():
pass
pub.subscribe(listener2, 'bar')
doa() # listener2 should be gc'd
gc.collect() # for pypy: the gc doesn't work the same as cpython's
topicMgr.delTopic('baz')
expect = """\
PUBSUB: New topic "baz" created
PUBSUB: Subscribed listener "listener1" to topic "baz"
PUBSUB: Start sending message of topic "baz"
PUBSUB: Sending message of topic "baz" to listener listener1
PUBSUB: Done sending message of topic "baz"
PUBSUB: Unsubscribed listener "listener1" from topic "baz"
PUBSUB: New topic "bar" created
PUBSUB: Subscribed listener "listener2" to topic "bar"
PUBSUB: Listener "listener2" of Topic "bar" has died
PUBSUB: Topic "baz" destroyed
"""
captured = capture.getvalue()
#print captured
#print repr(expect)
assert captured == expect, \
'\n'.join( unified_diff(expect.splitlines(), captured.splitlines(), n=0) )
示例12: __init__
def __init__(self, parent, title):
wx.Frame.__init__(self, parent, -1)
self.CreateStatusBar(1)
pub.subscribe(self.change_statusbar, "change.statusbar")
tempheading = ((" ",10), (" ",15), (" ",10))
self.panel_login = panel_login(self, -1)
self.panes = {}
self.panes['base'] = self.panel_base = panel_base(self, -1) # top horizontal ctrls
self.panes['rereg_list'] = self.panel_rereg_list = panel_rereg_list(self, -1)
self.panes['edit_booking'] = self.edit_booking = edit_booking(self, -1)
self.panes['edit_courses'] = self.panel_courses = panel_courses_picker(self, -1)
self.panes['student_details'] = self.panel_student_details = cSiswaDetails(self, -1)
self.panes['add_edit_course'] = self.panel_add_edit_course = panel_add_edit_course(self, -1)
self.panes['course_bookings'] = self.panel_course_bookings = panel_course_bookings(self,-1)
self.panes['edit_rereg_status'] = self.panel_edit_rereg_status = panel_edit_rereg_status(self, -1)
self.panes['edit_booking_status'] = self.panel_edit_booking_status = panel_edit_booking_status(self, -1)
self.panes['edit_guardian_data'] = self.PanelGuardianData = panel_edit_guardian(self, 1)
self.panes['edit_booking_student_details'] = self.edit_booking_student_details = edit_booking_student_details(self, -1)
self.panes['course_fees'] = self.panel_course_fees = course_fees(self, -1)
self.panes['edit_schools'] = self.edit_school = edit_school(self, -1)
self.panes['edit_address'] = self.panel_edit_address = panel_edit_address(self, -1)
self.Bind(wx.EVT_CLOSE, self.OnClose, self)
self.__set_properties()
self.__do_layout()
self.__do_main()
示例13: __init__
def __init__(self):
self.config = config.read('config.json')
if not 'twitch_id' in self.config:
raise config.ConfigurationError(
'Setting twitch_id incorrectly configured in config.json')
self.wx = wx.App()
self.plugins = plugins.PluginManager()
self.plugins.load('plugins/')
twitch_id = self.config['twitch_id']
login = self.config['services']['chat']['login']
bot_id = login['id']
bot_oauth = login['oauth']
chat.connect(bot_id, bot_oauth, twitch_id)
reactor.interleave(wx.CallAfter)
pub.subscribe(self.quit, 'command.quit')
self.icon = gui.Icon(self.plugins.plugins())
self.menu = gui.Menu(self.plugins.plugins())
self.wx.MainLoop()
示例14: job_subscribe
def job_subscribe(self, job_id):
"""
This event handler subscribes to the supplied job, and also
the matching job tree. Future updates to this job and any jobs
in the tree are automatically sent along to the client.
The client is sent two messages: job.subscribed, with the entire
job tree in flat format, and job.tree, which is the entire job
tree in pretty format.
"""
if not self.configuration.is_pacemaker():
# We don't relay job information if we're not a pacemaker.
self.emit('error', 'This node is not a pacemaker.')
return
# Start listening to job status's after the first subscribe request.
if not self.job_listening:
pub.subscribe(self.on_job_status, 'job.status')
self.job_listening = True
def got_pretty_tree(tree):
# Send back the pretty tree to the client.
self.emit('job.tree', job_id, tree)
def got_flat_tree_subscribe(job_ids):
for job_id in job_ids:
self.job_subscribed[job_id] = True
self.emit('job.subscribed', list(job_ids))
# Subscribe to everything in the tree.
self.configuration.job_manager.get_pretty_tree(job_id, got_pretty_tree)
self.configuration.job_manager.get_flat_tree(job_id, got_flat_tree_subscribe)
示例15: __init__
def __init__(self, configFile, completed_callback):
self.config = configFile
super(audioUploader, self).__init__()
self.dialog = wx_ui.audioDialog(services=self.get_available_services())
self.file = None
self.recorded = False
self.recording = None
self.playing = None
widgetUtils.connect_event(self.dialog.play, widgetUtils.BUTTON_PRESSED, self.on_play)
widgetUtils.connect_event(self.dialog.pause, widgetUtils.BUTTON_PRESSED, self.on_pause)
widgetUtils.connect_event(self.dialog.record, widgetUtils.BUTTON_PRESSED, self.on_record)
widgetUtils.connect_event(self.dialog.attach_exists, widgetUtils.BUTTON_PRESSED, self.on_attach_exists)
widgetUtils.connect_event(self.dialog.discard, widgetUtils.BUTTON_PRESSED, self.on_discard)
if self.dialog.get_response() == widgetUtils.OK:
self.postprocess()
log.debug("Uploading file %s to %s..." % (self.file, self.dialog.get("services")))
self.uploaderDialog = wx_transfer_dialogs.UploadDialog(self.file)
output.speak(_(u"Attaching..."))
if self.dialog.get("services") == "SNDUp":
base_url = "http://sndup.net/post.php"
if len(self.config["sound"]["sndup_api_key"]) > 0:
url = base_url + '?apikey=' + self.config['sound']['sndup_api_key']
else:
url = base_url
self.uploaderFunction = transfer.Upload(field='file', url=url, filename=self.file, completed_callback=completed_callback)
elif self.dialog.get("services") == "TwUp":
url = "http://api.twup.me/post.json"
self.uploaderFunction = transfer.Upload(field='file', url=url, filename=self.file, completed_callback=completed_callback)
pub.subscribe(self.uploaderDialog.update, "uploading")
self.uploaderDialog.get_response()
self.uploaderFunction.perform_threaded()