Robotics StackExchange | Archived questions

How to get value from a subscribed topic in ros in python

I have the following code from the ros subscriber tutorial:

#!/usr/bin/env python
import rospy
from std_msgs.msg import String
def callback(data):
 rospy.loginfo(rospy.get_caller_id() + "I heard %s", data.data)
def listener_new():
 rospy.init_node('listener_new', anonymous=True)
 rospy.Subscriber("locations", String, callback)
 rospy.spin()
if __name__ == '__main__':
 listener_new() 

I need to know how I may store the value of data.data in callback function so that I may use it for further purposes, I tried the following code but did not work:

#!/usr/bin/env python
import rospy
from std_msgs.msg import String
def callback(data):
 rospy.loginfo(rospy.get_caller_id() + "I heard %s", data.data)
 print("I am accessing data.data," data.data) # trying to access data.data
def listener_new():
 rospy.init_node('listener_new', anonymous=True)
 rospy.Subscriber("locations", String, callback)

 rospy.spin()
if __name__ == '__main__':
 listener_new()

Asked by Tawfiq Chowdhury on 2019-04-15 13:50:51 UTC

Comments

Answers

You can:

  1. use a global variable (not recommended for anything serious)
  2. use a custom class in which you save the data you a member variable
  3. use event-driven programming in which you call other functions from within the callback and pass the data to those functions

Update

my_data = None

def callback(data):
    # you have to let python know that this is a global otherwise
    # it thinks that it's a local variable
    global my_data 
    my_data = data.data
    rospy.loginfo(rospy.get_caller_id() + "I heard %s", my_data)

Asked by jayess on 2019-04-15 14:17:21 UTC

Comments

How do I store the value of data.data in a global variable? I cannot directly do this: variable=data.data

Could you please hint or show?

Asked by Tawfiq Chowdhury on 2019-04-15 14:23:57 UTC

Did you look at the links that I posted? The first item shows how to do that. I'll update with a quick example. But, remember that you really don't want to be using globals. Using them is a really good way to make buggy, hard to fix code.

Asked by jayess on 2019-04-15 14:40:50 UTC

I have not yet, I will look at it later, yes, please show the other way, it will help. Thanks a lot.

Asked by Tawfiq Chowdhury on 2019-04-15 14:47:17 UTC

Just so you know, this is more of a Python question than a ROS one.

Asked by jayess on 2019-04-15 14:50:56 UTC

Hey,

The code you provided doesn't work, because you miss the comma after first String. Other than that it's completely fine.

print("I am accessing data.data", data.data) # trying to access data.data

Simpliest solution to store the data for later would be to use global variables. It's probably not very elegant way to do things, but should work fine in less complicated applications.

Asked by Nikodem on 2019-04-15 14:25:37 UTC

Comments