I am new at using ROS and I want to use an int that is received by a topic and use it in another python file. The listener.py receives the correct int but when i use it in another file it won't update and just print None. I don't know what I'm doing wrong.
listener.py
#!/usr/bin/env python
import rospy
from std_msgs.msg import Int32
class listenerPy:
def __init__(self):
self.received_integer = None
def callback(self, data):
self.received_integer = data.data
print(self.received_integer)
def listener(self):
rospy.init_node('listener', anonymous=True)
rospy.Subscriber('chatter', Int32, self.callback)
rospy.spin()
if __name__ == '__main__':
try:
listener = listenerPy() # Instantiate the listenerPy class
listener.listener() # Call the listener method on the instance
except rospy.ROSInterruptException:
pass
other file
#!/usr/bin/env python
from listener import listenerPy
from time import sleep
def main():
local_var = listenerPy()
while True:
value = local_var.received_integer
print(value)
sleep(1)
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
pass
If you want to run both files standalone, you need some sort of shared memory. However, in your example, you need to actually start the listener in your other file.
def main():
local_var = listenerPy()
local_var.listener()
while True:
value = local_var.received_integer
print(value)
sleep(1)
However, you call rospy.spin()
in your ros node, which will block. So you should remove that call from your node.