Rosanswers logo

I was looking at the beginner's Publisher node boilerplate code from the wiki and I was wondering:

How does ROS knows which node is the publisher of a message?

#!/usr/bin/env python
# license removed for brevity
import rospy
from std_msgs.msg import String

def talker():
    pub = rospy.Publisher('chatter', String, queue_size=10)
    rospy.init_node('talker', anonymous=True)
    rate = rospy.Rate(10) # 10hz
    while not rospy.is_shutdown():
        hello_str = "hello world %s" % rospy.get_time()

if __name__ == '__main__':
    except rospy.ROSInterruptException:

I see the creation of a chatter Topic and talker node, so, how does pub.publish knows which topic is publishing and if pub.publish doesn't need to know, how does rosmaster knows?

Originally posted by John999991 on ROS Answers with karma: 37 on 2020-02-26

Post score: 0

Original comments

Comment by Wilco Bonestroo on 2020-02-26:
What exactly do you want to know?

Your first question "how does ROS knows which node is the publisher" is about the client library. In this case this is rospy. Here the node is registered and also the publisher with the topic is registered. Eventually the master handles setting up the communication with nodes that have subscriptions on this topic.

Your second question "how does pub.publish know to which topic it is publishing" is more straightforward. When the publisher is created, the topic is given as an argument and publisher object is stored in the variable pub. When you call pub.publish later on, the object still knows what its topic is.

Comment by John999991 on 2020-02-26:
Dear Bonestroo,

If I was to create 2 nodes in the same py script:

 rospy.init_node('talker1', anonymous=True)
 rospy.init_node('talker2', anonymous=True)

with all other the same, which one would be the node publishing data?

Comment by Wilco Bonestroo on 2020-02-27:
Hi, Now I see your question. There can be only one node per python process. According to the documentation "You can only have one node in a rospy process, so you can only call rospy.init_node() once."


1 Answer 1


Rosanswers logo

Because you use rospy.init_node() before sending the actual message, this will communicate with the roscore of the node's existence. The publisher must have an initialized node before being able to to publish. Try removing the "rospy.init_node('talker', anonymous=True)" and it will fail to publish.

Originally posted by bob-ROS with karma: 525 on 2020-02-26

This answer was ACCEPTED on the original site

Post score: 1

Original comments

Comment by John999991 on 2020-02-26:
So, I cannot initialize 2 nodes from the same .py file?

Comment by bob-ROS on 2020-02-26:
It is not intended to have multiple nodes in one rospy program https://wiki.ros.org/rospy/Overview/Initialization%20and%20Shutdown#Initializing_your_ROS_Node


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.