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

Recursively get message field names in ROS2

asked 2021-09-16 03:44:48 -0600

KenYN gravatar image

updated 2021-09-16 03:45:23 -0600

We have the handy rosidl_runtime_py.message_to_csv() method for converting a message to CSV, but is there a similar function that will recursively get the field names so I can print out a CSV header as well?

edit retag flag offensive close merge delete

2 Answers

Sort by ยป oldest newest most voted

answered 2021-09-16 22:35:16 -0600

KenYN gravatar image

Solved it!

def recursive_items(ordered_dict):
    for key, value in ordered_dict.items():
        if type(value) is collections.OrderedDict:
            yield from recursive_items(value)
            yield (key, value)

def print_headers(record):
    print(','.join([key for key, _ in recursive_items(rosidl_runtime_py.message_to_ordereddict(record))]))

I'd missed the API rosidl_runtime_py.message_to_ordereddict() which gives me the message with names and values in a nested OrderedDict, so I iterate over that to pull out the keys from the leaf nodes.

edit flag offensive delete link more

answered 2021-09-16 04:05:50 -0600

Ranjit Kathiriya gravatar image

updated 2021-09-16 04:06:06 -0600

Just have a look at this question: #q379915, I hope you will get your solution. Instead, you also can use the Pandas library for printing header in a recursive manner.

edit flag offensive delete link more


That's the wrong way round - I want to go from Bag to CSV, not CSV to Bag.

KenYN gravatar image KenYN  ( 2021-09-16 18:35:53 -0600 )edit

Ohh! I am sorry, but It should be easy you just have collected data in the last and in the end you can store it to CSV. I preferred to use pandas because it is faster the normal way of code.

def write_csv():
    df2 = pd.DataFrame()
    for name, df in data.items():
        df2 = df2.append(df)
Ranjit Kathiriya gravatar image Ranjit Kathiriya  ( 2021-09-17 01:38:48 -0600 )edit

Question Tools



Asked: 2021-09-16 03:44:48 -0600

Seen: 327 times

Last updated: Sep 16 '21