Template for a ROS Publisher in Python

I do not like to memorize definitions, methods, procedures, etc., but I like to find solutions to help me reach my final goal.

In ROS, the structure of a simple node is repeated almost every time. To write the Publisher nodes as easily as possible, I’ve made a template that you can modify as you needed.

The template below represents a ROS Publisher node written in Python. All you have to do is to copy the template into a ‘. py’ file, delete the extra text and replace the text in capital letters.

Template for a ROS Publisher in Python

Template for a ROS Publisher in Python (image source)

I used the above template to make a ROS node that generates a random number between 0 and 5000.

To run the above node, navigate to the .py file and make it executable. The command is:

After the file is executable, you can run the node.

Step 1: open a new Terminal and run the command:

Step 2: open a new Terminal and run the node with the following command:

5 comments » Write a comment

  1. Hi from Canada and THANK YOU for this tutorial!

    Regarding your example Python script to generate a random number,
    if I open a new terminal and run it using Python it works great:
    “gary@gary-VirtualBox:~$ python template-for-a-ros-publisher-example01.py
    [INFO] [1517249692.759530]: The number generated is lower than 2500: 599
    [INFO] [1517249692.761242]: The number generated is lower than 2500: 1966
    [INFO] [1517249692.761691]: The number generated is higher than 2500: 3456”

    But after making it executable: chmod u+x template-for-a-ros-publisher-example01.py
    I open a new terminal and use rosrun but receive the following error:
    “gary@gary-VirtualBox:~$ rosrun template-for-a-ros-publisher-example01.py
    Usage: rosrun [–prefix cmd] [–debug] PACKAGE EXECUTABLE [ARGS]
    rosrun will locate PACKAGE and try to find
    an executable named EXECUTABLE in the PACKAGE tree.
    If it finds it, it will run it with ARGS.”

    What am I doing wrong? My new ROS environment works fine using turtlesim:
    “gary@gary-VirtualBox:~$ rosrun turtlesim turtle_teleop_key
    Reading from keyboard
    Use arrow keys to move the turtle.”

    Thanks so much, Gary

  2. Hey, Thank very much from the tutorial

    My question is how I would be able to export value from ROS node ( in my case from cmd_vel) to Arduino with your template?
    I know how to write a subscribe thing on Arduino but not sure about the publisher.

    Thanks again

  3. Hello, could u plz help me, I have six node, the first node should publis several random graph to other nodes, and after that other nodes extract some info and send this info to each other. Every thing is fine when The first node publish just one graph but when it publishes several graphs the problem happens. Some node does not have chance to receive all the graphs publish from first node ? I tried rospy.sleep(15) but the problem did not solve

Leave a Reply