ROS Resources: Documentation | Support | Discussion Forum | Service Status | Q&A answers.ros.org

Convert Topic Message to Dictionary in Python Callback

I would like to save a topic message into a file in a Python callback. I can use a csv.DictWriter if I first convert the message into a dictionary. Is there a better way of converting a message into a dictionary rather than iterating over msg._fields_and_field_types? I cannot use vars() since the message does not have a dict attribute. Is it safe to rely on _fields_and_field_types in future ROS distributions? Thanks!

def _callback(self, msg):
    msg_dict = {field: getattr(msg, field) for field in msg._fields_and_field_types if hasattr(msg, field)}
    self.csv_dict_writer.writerow(msg_dict)

Thanks for your question. However we ask that you please ask questions on http://answers.ros.org following our support guidelines: http://wiki.ros.org/Support

ROS Discourse is for news and general interest discussions. ROS Answers provides a Q&A site which can be filtered by tags to make sure the relevant people can find and/or answer the question, and not overload everyone with hundreds of posts.