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

How to show topics using python in ROS2

asked 2021-01-05 00:19:05 -0500

Hi, everyone.

Like the title, I want to show topics using python in ROS2.

First I thought use a ros2 topic list command through a subprocess module of python, but If possible I want to use a official ros2cli package of python.

Please, could anyone tell me how to use a ros2cli package?

edit retag flag offensive close merge delete

3 Answers

Sort by ยป oldest newest most voted
5

answered 2021-01-06 01:01:50 -0500

updated 2021-01-06 01:13:47 -0500

Thank you everyone for telling me good information, I implemented a sample code below using get_topic_names_and_types.

### `sample_to_show_topic_list.py` ###
import rclpy
from rclpy.node import Node

def get_topic_list():
    node_dummy = Node("_ros2cli_dummy_to_show_topic_list")
    topic_list = node_dummy.get_topic_names_and_types()
    node_dummy.destroy_node()
    return topic_list


rclpy.init()
topic_list = get_topic_list()
for info in topic_list:
    print(info[0])
rclpy.shutdown()

Execute this code, and get following output in the terminal.

$ ros2 topic pub --rate 1 hoge std_msgs/msg/String "{data: "hoge"}"  # publish a string
$ python3 sample_to_show_topic_list.py  # show topic list

/hoge
/parameter_events
/rosout
edit flag offensive delete link more
3

answered 2021-01-05 14:10:42 -0500

tfoote gravatar image

You can use the python client library and ask for the topics for each node: using get_publisher_names_and_types_by_node iterating through each node on the system which is available via get_node_names

Both are documented in the rclpy Node API: http://docs.ros2.org/latest/api/rclpy...

We don't appear to have the straight API for asking for the list from all nodes on the system, which I think would be a nice enhancement PR if someone would wish to do that.

edit flag offensive delete link more
1

answered 2021-01-05 02:42:24 -0500

duck-development gravatar image

You can look how the ros2cli is make it. But subprocess is the cleaner way. Through the ros2cli you can extend the ros2 cmd list. But it is not used for the other way around

See here https://github.com/ros2/ros2cli/tree/...

edit flag offensive delete link more

Comments

1

But subprocess is the cleaner way

personal, but I would never consider using subprocess to be cleaner than anything else.

gvdhoorn gravatar image gvdhoorn  ( 2021-01-05 03:11:45 -0500 )edit

i mean it by the philosophy of unix, use a set small tools to complete a complex task.
and not reinvent the wheel. but if the node api has this call it is also ok.

duck-development gravatar image duck-development  ( 2021-01-09 14:27:17 -0500 )edit

Question Tools

1 follower

Stats

Asked: 2021-01-05 00:19:05 -0500

Seen: 2,843 times

Last updated: Jan 06 '21