Basic usage of pubsub involves subscribing listeners, sending messages, and responding to messages. The Quick Start subsection below provides examples. For details, navigate to the Basic Pubsub Tasks subsection:
Simplest 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:'
print ' arg1 =', arg1
print ' arg2 =', arg2
# ------------ register listener ------------------
pub.subscribe(listener1, 'rootTopic')
#---------------- send a message ------------------
print 'Publish something via pubsub'
anObj = dict(a=456, b='abc')
pub.sendMessage('rootTopic', arg1=123, arg2=anObj)
Running the above as a script (available in the docs/usage folder of the source distribution as helloworld.py) will produce the result:
Publish something via pubsub
Function listener1 received:
arg1 = 123
arg2 = {'a': 456, 'b': 'abc'}
There are several examples that can be found in the source distribution in the examples folder. Some focus on the basics, others on more advanced aspects of pubsub usage. Some examples are GUI-based and may require other packages (such as wxPython).
The examples/basic_kwargs folder contains examples of basic usage of pubsub “out of the box”, i.e. using the default (“kwargs”) messaging protocol. The README.txt file in examples/basic_kwargs explains:
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:
Use of the arg1 messaging protocol is documented in the Advanced section.