Ask Your Question

How to write the publisher in Python correctly?

asked 2019-09-26 00:12:34 -0500

notSoTechnical gravatar image

updated 2019-09-26 00:13:49 -0500

Hi! I'm very confused... I failed to follow the instructions from

1 #!/usr/bin/env python
   2 # license removed for brevity
   3 import rospy
   4 from std_msgs.msg import String
   6 def publisher():
   7     pub = rospy.Publisher('chatter', String, queue_size=10)


I have a file name and it has

float32 a
float32 b
float32 c

Should I do the following? But it doesn't work. What should I do so it pulls the data from

 1 #!/usr/bin/env python
   2 # license removed for brevity
   3 import rospy
   4 from std_msgs.msg import Float32
   6 def publisher():
   7     pub = rospy.Publisher('topicName', Float32, queue_size=10)
edit retag flag offensive close merge delete



Have you gone through the official tutorials of the ROS wiki? The tutorial you link to is pretty out-of-date, it is from 2011. The official tutorials should actually cover/answer all your questions. Once you've checked those and still have issues, please post them here by editing your question...

mgruhler gravatar image mgruhler  ( 2019-09-26 01:16:04 -0500 )edit

@mgruhler Thank you!

notSoTechnical gravatar image notSoTechnical  ( 2019-09-26 11:56:15 -0500 )edit

1 Answer

Sort by ยป oldest newest most voted

answered 2019-09-26 02:03:50 -0500

drodgu gravatar image

I usually program in C++ when working with ROS. By the way, what you first define as is not a python file, it is a message file and it must be a *.msg file. Once you've written the code of your *.msg file, you must compile it in order to let ROS create the header file for that message.

To use that message, lets imagine you've called your message my_msg, so you must write in python something like this:

import rospy
from your_ros_package_name import my_msg

def publisher():
  pub = rospy.Publisher('topicName',my_msg, queue_size=10)

Try with something like this. It could be some python spelling mistake because as I've already told you I am used to work with C++ nodes.

edit flag offensive delete link more


I thought : "The std_msgs.msg import is so that we can reuse the std_msgs/String message type (a simple string container) for publishing."

notSoTechnical gravatar image notSoTechnical  ( 2019-09-26 11:55:47 -0500 )edit

If you want to use a String type msgs you can import String from std_msgs.msg. But I understood that you want to use a msg to broadcast 3 float32 numbers. This second way is better because you do not have to filter the String msg once is received.

drodgu gravatar image drodgu  ( 2019-09-30 02:04:39 -0500 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower


Asked: 2019-09-26 00:12:34 -0500

Seen: 248 times

Last updated: Sep 26 '19