Basic Usage

Basic usage of PyPubSub involves subscribing listeners, sending messages, and responding to messages. The Quick Start subsection below provides examples. For details, navigate to the Basic PyPubSub Tasks subsection:

Quick Start

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 will produce the result:

Publish something via pubsub
Function listener1 received:
  arg1 = 123
  arg2 = {'a': 456, 'b': 'abc'}

Other Examples

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 PyPubSub 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 PyPubSub “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. There are two examples that can be run from this folder: basic console based, uses the and modules. wxPython GUI application with two windows (win1 and win2) that exchange data without
any reference to the other. This example looks for pubsub on your system path so default install ok.