Carlton Banks Carlton Banks - 1 year ago 184
Python Question

Writing a ros node with both a publisher and subscriber?

I am currently trying to make a ROS node in Python which has both a subscriber and a publisher.

I've seen examples where a message is published within the callback, but I want it to "constantly" publish messages, and perform callbacks when it is the case.

Here is how I do it now:

#!/usr/bin/env python

import rospy
from std_msgs.msg import Empty
from std_msgs.msg import String
import numpy as np

pub = rospy.Publisher('/status', String, queue_size=1000)

def callback(data):
print "Message received"

def listener():

rospy.init_node('control', anonymous=True)

rospy.Subscriber('control_c', Empty, callback)

if __name__ == '__main__':
print "Running"

So where should I publish?

Answer Source

Simply replace rospy.spin() with the following loop:

while not rospy.is_shutdown():
    # do whatever you want here
    rospy.sleep(1)  # sleep for one second

Of course you can adjust the sleep duration to whatever value you want (or even remove it entirely).

According to this reference subscribers in rospy are running in a separate thread, so you don't need to call spin actively.

Note that in roscpp (i.e. when using C++) this is handled differently. There you have to call ros::spinOnce() in the while loop.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download