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
if __name__ == "__main__":
    listener()
    while not rospy.is_shutdown():
        print('inside main')
        rospy.spin()

My problem is that the print statement 'inside main' is executed only once and I don't understand why, shouldn't it be looping for as long as the rospy is up and running?

No, it shouldn't.

rospy.spin() is a blocking call: you're program will not advance to the next line as long as rospy.spin() is executing -- which will be forever by design. That is, until you make rospy.is_shutdown() true (by using ctrl+c for instance).

So your while is entered, the print(..) statement is executed once and then rospy.spin() takes over and never returns.

if __name__ == "__main__":
    listener()
    while not rospy.is_shutdown():
        print('inside main')
        rospy.spin()

My problem is that the print statement 'inside main' is executed only once and I don't understand why, shouldn't it be looping for as long as the rospy is up and running?

No, it shouldn't.

rospy.spin() is a blocking call: you're program will not advance to the next line as long as rospy.spin() is executing -- which will be forever by design. That is, until you make rospy.is_shutdown() true (by using ctrl+c for instance).

So your while is entered, the print(..) statement is executed once and then rospy.spin() takes over and never returns.


Edit: some things to note:

  • rospy.spin() doesn't really do anything: it just sits there, waiting. It's not needed in rospy for handling events.
  • if you're going to use something else instead of rospy.spin(), make sure to properly throttle your while-loop, or it will start using 100% cpu even while doing nothing.
  • you seem to be implementing a synchronous sampling system (global value; value = data.data): you may want to consider handling incoming msgs directy in the callback and keep everything event-based, or take a look at message_filters/Cache.