A few days ago I wrote a tutorial about a template for a Publisher node in Python. In the same tutorial, I used the template to write a ROS node to generate a random number.
Today, I continue the series of tutorials that ease the work of beginners in ROS, with a template for Subscriber in Python. In addition, in the article, you will find a template implementation with a ROS node that displays the data generated by the Publisher node from the previous tutorial.
Below you will find the template for a ROS Publisher node in Python. All you have to do is copy the text into a ‘. py’ file, delete the extra text and replace the text with capital letters.

Template for a ROS Publisher in Python (image source)
#The ROS Node Subscriber template #!/usr/bin/env python #remove or add the library/libraries for ROS import rospy, time, math, cv2, sys #remove or add the message type from std_msgs.msg import String, Float32, Image, LaserScan, Int32 #define function/functions to provide the required functionality def name_callback(msg): make_something_here_with msg.data rospy.loginfo("I heard %s", msg.data) if __name__=='__main__': #Add here the name of the ROS. In ROS, names are unique named. rospy.init_node('THE_NAME_OF_THE_NODE') #subscribe to a topic using rospy.Subscriber class sub=rospy.Subscriber('TOPIC_NAME', TOPIC_MESSAGE_TYPE, name_callback) rospy.spin()
I used the above template to write a ROS node that will display the random numbers sent by the node created to test the Publisher template.
#!/usr/bin/env python import rospy from std_msgs.msg import Int32 from random import randint def random_callback(msg): rospy.loginfo("I heard %s", msg.data) if __name__=='__main__': rospy.init_node('rand_subscriber') sub=rospy.Subscriber('rand_no', Int32, random_callback) rospy.spin()
To run the above node, navigate to the .py file and make it executable. The command is:
chmod u+x my_python_file.py
After the file is executable, you can run the node.
Step 1: open a new Terminal and run the command:
roscore
Step 2: open a new Terminal and run the Publisher node with the following command:
rosrun your_package your_ros_node_that_generates_random_number.py
Step 3: open a new Terminal and run the subscriber node with the following command:
rosrun your_package your_ros_node_for_subscriber.py