ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | Q&A
Ask Your Question

ROS Subscribe to multiple topics with single function

asked 2022-10-11 06:26:58 -0500

FurkanEdizkan gravatar image

updated 2022-10-11 06:28:47 -0500

Thanks for feedback and help in advance,

I want to give input of topic names, initial data and data_type as dictionary to a function, and that function will subscribe to each topic and save data to dictionary. This is what I have done so far.

Example input

ros_topics = {"rosTopic1": {"data": None,
                            "type": "msg_type1"},
              "rosTopic2": {"data": None,
                            "type": "msg_type2"},
              "rosTopic3": {"data": None,
                            "type": "msg_type3"}}

I can subscribe to multiple topics and show their output message, however I couldn't save them into dictionary.

My function so far

def subscribe_topics(self):
    for key in self.ros_topics.keys():

def common_callback(self, msg):
    # Want to store to ros_topics[key]["data"], however I couldn't transfer **key**

Stackoverflow Question Link

  • Python 3.8
  • ROS Noetic
  • Ubuntu 20.04
edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2022-10-11 07:42:51 -0500

ravijoshi gravatar image

You need to use callback_args parameter of the Subscriber class.

In your case, you can set the key as shown below:


And then change the callback signature to accommodate key as shown below:

def common_callback(self, msg, args):
    key = args

I have not tested the above code. In case of an error, please inform and change the callback_args to a tuple.

For more information, please check this answer.

edit flag offensive delete link more


This question scratches the same itch:

ljaniec gravatar image ljaniec  ( 2022-10-11 08:46:26 -0500 )edit

Yes, it perfectly works. Thank you

FurkanEdizkan gravatar image FurkanEdizkan  ( 2022-10-12 02:34:25 -0500 )edit

I can open an other question for this topic but since we are here, is this usage a good way to use ros subscriber?

FurkanEdizkan gravatar image FurkanEdizkan  ( 2022-10-12 02:35:11 -0500 )edit

@FurkanEdizkan I am glad it worked. Yes, it is all right to use callback_args. If you face any problems with it, feel free to open a new question, as you said.

ravijoshi gravatar image ravijoshi  ( 2022-10-12 05:55:09 -0500 )edit

Thank you for answer

FurkanEdizkan gravatar image FurkanEdizkan  ( 2022-10-12 06:01:53 -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: 2022-10-11 06:26:58 -0500

Seen: 713 times

Last updated: Oct 11 '22