-
Notifications
You must be signed in to change notification settings - Fork 14
PythonPubSub
Anson Strauch edited this page Jan 23, 2026
·
1 revision
This example is a reimplementation of example 2 in Python.
This example combines both features (subscriber and publisher into one file). Let's start with publishing.
gn = GravityNode()
while gn.init("PyPub") != gravity.SUCCESS:
SpdLog.warn("failed to init, retrying...")
time.sleep(1)
gn.registerDataProduct("PythonGDP", gravity.TCP)
gn.subscribe("PythonGDP", mySub) # Note that this is here to subscribe only. Not useful for publishing
counterPB = BasicCounterDataProductPB()
gdp = GravityDataProduct("PythonGDP")
for i in range (1, 50):
counterPB.count = i
gdp.data=counterPB
gn.publish(gdp)
time.sleep(1)
gn.waitForExit()To set up the subscriber, you must define a class the same way you would in C++. Then, call the subscribe method with an instantiation of that class.
class MySubscriber(GravitySubscriber):
# We're only using GravitySubscriber here, but this is generally the way we
# initialize Gravity Python components to ensure that __init__ is called
# on each parent.
def __init__(self):
GravitySubscriber.__init__(self)
def subscriptionFilled(self, dataProducts):
counterPB = BasicCounterDataProductPB()
for gdp in dataProducts:
gdp.populateMessage(counterPB)
SpdLog.warn("received counter with value = "+str(counterPB.count))
mySub = MySubscriber()
gn = GravityNode()
while gn.init("PyPub") != gravity.SUCCESS:
SpdLog.warn("failed to init, retrying...")
time.sleep(1)
gn.registerDataProduct("PythonGDP", gravity.TCP) # Not useful for subscribing.
gn.subscribe("PythonGDP", mySub)Once you understand the regular C++ version, this is pretty straightforward.
Again it's pretty similar to the C++ version. One difference is that the _init_() method is explicitly defined, which ensures parent constructors are called. Another is constants, such as GravityReturnCodes and protocols.