Writing Python Subscriber in ROS2
There are three ways to to write a Python publisher in ROS2, namely:
- Old-school approach
- Object-oriented (member-function) approach
- Local function (lambda) approach
Below is an example of each approach to write a Python node listening to “Hello World” stream. The code is taken from here: https://github.com/ros2/examples/tree/foxy/rclpy/topics/minimal_subscriber/examples_rclpy_minimal_subscriber
Old-school approach:
import rclpy
from std_msgs.msg import String
g_node = None
def chatter_callback(msg):
global g_node
g_node.get_logger().info(
'I heard: "%s"' % msg.data)
def main(args=None):
global g_node
rclpy.init(args=args)
g_node = rclpy.create_node('minimal_subscriber')
subscription = g_node.create_subscription(String, 'topic', chatter_callback, 10)
subscription # prevent unused variable warning
while rclpy.ok():
rclpy.spin_once(g_node)
# Destroy the node explicitly
# (optional - otherwise it will be done automatically
# when the garbage collector destroys the node object)
g_node.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main()
Object-oriented (member-function) approach:
import rclpy
from rclpy.node import Node
from std_msgs.msg import String
class MinimalSubscriber(Node):
def __init__(self):
super().__init__('minimal_subscriber')
self.subscription = self.create_subscription(
String,
'topic',
self.listener_callback,
10)
self.subscription # prevent unused variable warning
def listener_callback(self, msg):
self.get_logger().info('I heard: "%s"' % msg.data)
def main(args=None):
rclpy.init(args=args)
minimal_subscriber = MinimalSubscriber()
rclpy.spin(minimal_subscriber)
# Destroy the node explicitly
# (optional - otherwise it will be done automatically
# when the garbage collector destroys the node object)
minimal_subscriber.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main()
Local function (lambda) approach:
import rclpy
from std_msgs.msg import String
def main(args=None):
rclpy.init(args=args)
node = rclpy.create_node('minimal_subscriber')
subscription = node.create_subscription(
String, 'topic', lambda msg: node.get_logger().info('I heard: "%s"' % msg.data), 10)
subscription # prevent unused variable warning
rclpy.spin(node)
# Destroy the node explicitly
# (optional - otherwise it will be done automatically
# when the garbage collector destroys the node object)
node.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main()
