Robotics StackExchange | Archived questions

init_node need locating after Publisher?

I create one simple to send msgs to other nodes, but others cannot get msgs, even if they have been connected. The code shows as following.

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

def talker():
    rospy.init_node('talker')
    pub = rospy.Publisher('chatter', String, queue_size=10)    
    hello_str = "hello world %s" % rospy.get_time()
    pub.publish(hello_str)
    rospy.loginfo(hello_str)

if __name__ == '__main__':
    talker()

But when I move the init_node after rospy.publisher, it works well. And like this.

#!/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')
    hello_str = "hello world %s" % rospy.get_time()
    pub.publish(hello_str)
    rospy.loginfo(hello_str)

if __name__ == '__main__':
    talker()

Asked by suoxd123 on 2018-06-12 05:05:46 UTC

Comments

Answers

Don't move init_node as you suggest. The problem with your first code snippet is that you publish one single message and then exit. This means your publisher is destroyed immediately and no other nodes gets the chance of subscribing before it is too late.

Put the publish line inside a loop as the tutorials show.

Asked by knxa on 2018-06-12 14:25:21 UTC

Comments