ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question

Publisher and subscriber in one node (Python)

asked 2022-03-14 12:17:06 -0500

EGam gravatar image

Hello, I new using ROS and I saw a lot of posts but I can't solve my problem.

I have a publisher (1) that sends a random number between 0 and 5 and the next node (2) needs to receive that value and multiply it by 10. After that, the same node (2) needs to send that information to another node. This is the first code

#!/usr/bin/env python
# encoding: utf-8
import rospy  
import random
from std_msgs.msg import String  
def nodo(): 
    pub = rospy.Publisher('example', String, queue_size=10)
    rate = rospy.Rate(10)
    while not rospy.is_shutdown():  
        ran = random.randint(0, 5)    
        mensaje = str(ran)

if __name__ == '__main__':  

   except rospy.ROSInterruptException:

And this is my attempt for the second code

#!/usr/bin/env python
# encoding: utf-8

import rospy
from std_msgs.msg import String
pub = rospy.Publisher("echo", String)

def callback(mensaje):
    mensaje1 = str(int(*10
    # The message has 2 parts, a header and the data. We only want to use the actual data

sub=rospy.Subscriber("chatter", String, callback)
edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2022-03-15 13:17:44 -0500

schulze18 gravatar image

Hi EGam, can you give more details about your problem? Are you able to run (rosrun) both nodes?

Based on your post, the first node seems be ok. Except for an additional "space" in the beginning of line 15: rate.sleep()

The second node seems to be missing two important parts:

  • The sctructure using if if __name__ == '__main__': in order to the python interpreter run your code
  • Even if your node just do something when a new data is published, it should have at least arospy.spin()that checks and process if any event occurs (new data received on a topic or a timer event). Check this post about rospy.spin and rospy.sleep (

To write nodes that only handle with events (like your second one), I like to follow the listener structure presented in the rospy tutorial (

I hope this will help you.

edit flag offensive delete link more

Question Tools


Asked: 2022-03-14 12:17:06 -0500

Seen: 448 times

Last updated: Mar 15 '22