How a ROS node written in Python could subscribe to multiple topics and publish to multiple topics?

All examples I found were for a single topic. Is this an event-driven model so subscription to multiple "events" is allowed or it is more like a loop, so it can listen only to one "source" at a time?


You can follow the example code here and simply add a second subscription like so:

import rospy
from std_msgs.msg import String

def callback1(data):
    rospy.loginfo("Callback1 heard %s",data.data)

def callback2(data):
    rospy.loginfo("Callback2 heard %s",data.data) 

def listener():
    rospy.Subscriber("chatter1", String, callback1)
    rospy.Subscriber("chatter2", String, callback2)
    # spin() simply keeps python from exiting until this node is stopped

ROS Python nodes are inherently multi-threaded. When you get each callback, it will be in a separate thread. So this is an event-driven model.

Note that this behavior is different than the default behavior for ROS C nodes which are inherently single threaded unless you specifically make them multi-threaded.

  • $\begingroup$ Thanks @Ben for confirming that Python nodes are event-driven (multiple threads) and providing an example code. This is exactly the confirmation I was looking for. Thanks! $\endgroup$ – Zoltan Fedor Feb 22 '15 at 16:30

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.