A complete example of use:
'''
One listener is subscribed to a topic called 'rootTopic'.
One 'rootTopic' message gets sent.
'''
from pubsub import pub
# ------------ create a listener ------------------
def listener1(arg1, arg2=None):
print 'Function listener1 received:\n arg1="%s"\n arg2="%s"' % (arg1, arg2)
# ------------ register listener ------------------
pub.subscribe(listener1, 'rootTopic')
#------ create a function that sends a message ----
def doSomethingAndSendResult():
print 'lahdida... have result, publishing it via pubsub'
pub.sendMessage('rootTopic', arg1=123, arg2=dict(a='abc', b='def'))
# --------- define the main part of application --------
if __name__ == '__main__':
doSomethingAndSendResult()
Running the above as a script (already saved for your convenience as helloworld.py in the docs folder of the source distribution) will produce the result:
lahdida... have result, publishing it via pubsub
Function listener1 received:
arg1="123"
arg2="{'a': 'abc', 'b': 'def'}"
There are several examples that can be found in the source distribution in the examples folder. There are some “basic” examples that focus on syntax, and more advanced examples that hint at some design pattern. In most cases, there are both “console”-based and GUI (wxPython) based examples.
On Windows, the whole set of examples in the examples folder can be executed automatically as a form of regression testing. Run runall.bat from a console window once cd’d to the examples folder. Read the text in the console for instructions.
The examples described below can be browsed online.
These two examples demonstrate a simple use of pubsub with the kwargs messaging protocol (default). There are two examples that can be run from this folder:
These two examples demonstrate a simple use of pubsub with the arg1 messaging protocol. There are two examples that can be run from this folder:
protocol. Note that it imports pubsub from wxPython’s wx.lib package. Therefore you must have (a copy of) pubsub installed there for this example to work (pubsub can be installed in multiple places independently and they will all work without interfering with each other).
Note that this example is copied almost verbatim from the wxPython wiki site and is probably not a good model of how an application should be structured.
These examples demonstrate the use of the legacy (version 1) pubsub API. There are two examples that can be run from this folder:
main.py: basic console based, all in one module (so not very realistic).
wx_main.py: using pubsub within wxPython application, all in one module.
These two examples demonstrate a more advanced use of pubsub. One of the examples uses the kwargs messaging protocol, the other uses the arg1 messaging protocol. There are two examples that can be run from this folder: