godfreap
godfreap

Reputation: 373

Must a rospy subscriber be in a function?

Most of the programs and examples I've seen initiates the rospy subscriber in a function, such as

def listener():
    rospy.Subscriber('/heylookitsanoutput',Image,imagecallback)
    rospy.spin()

But is it necessary to keep that within a function? Can it work like MQTT, where you throw the subscriber at the start of a function, with the callback executed upon seeing something post to the subscribed topic?

I can understand the need to do this since you probably need rospy.spin() to wait for the input you're looking for, but if the callback can be triggered as an interruptible event, that might be better for my scenario (updating image windows as new images come in).

Thanks!

Upvotes: 1

Views: 348

Answers (1)

tmms
tmms

Reputation: 116

You can initiate rospy subscriber also outside a function, i.e. in the if __name__ == "__main__": block. His behavior would be exactly the same, with the callback executed upon seeing something post to the subscribed topic.

I think the main point of embedding those command inside a function is possibility to import them in some other module easily and to get better code organization.

Upvotes: 1

Related Questions