ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

A ROS subscriber runs continuously and gets all messages that are published on a topic until it is shut down. The callback is called once for each message.

In your case it looks like your program runs long enough to receive three messages before it stops, but I suspect that sometimes you will get 1, 2 or maybe 4 messages depending on timing and other CPU usage.

If you want to receive a single message on a topic, you need to create subscriber, wait for callback to be called once, and then unsubscribe; rospy has a function that does this for you: rospy.wait_for_message

I haven't tested it, but this should work:

#!/usr/bin/env python
from __future__ import print_function
import rospy
from sensor_msgs.msg import LaserScan

rospy.init_node("subscribe_once")
message = rospy.wait_for_message("/scan", LaserScan)
print(message)