Ask Your Question
0

init_node need locating after Publisher?

asked 2018-06-12 05:05:46 -0500

suoxd123 gravatar image

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()
edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2018-06-12 14:25:21 -0500

knxa gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2018-06-12 05:05:46 -0500

Seen: 215 times

Last updated: Jun 12 '18