Ask Your Question
0

while loop only executes subscriber callback()

asked 2018-12-09 14:50:28 -0600

Elona gravatar image

Hi,

the key code parts:

def callback(data):
    global value
    value = data.data

def listener():
    #init.node and creating a subscriber for a topic are performed

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? However, after rospy.spin() the callback() function is executed constantly, but the print statement is not repeated.

Thanks.

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2018-12-09 15:03:18 -0600

gvdhoorn gravatar image

updated 2018-12-09 15:17:35 -0600

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.
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-12-09 14:50:28 -0600

Seen: 356 times

Last updated: Dec 09 '18