0
$\begingroup$

Rosanswers logo

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?


Originally posted by ksato-dev on ROS Answers with karma: 83 on 2021-01-05

Post score: 3

$\endgroup$

3 Answers 3

0
$\begingroup$

Rosanswers logo

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/master/ros2node


Originally posted by duck-development with karma: 1999 on 2021-01-05

This answer was NOT ACCEPTED on the original site

Post score: 1


Original comments

Comment by gvdhoorn on 2021-01-05:\

But subprocess is the cleaner way

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

Comment by duck-development on 2021-01-09:
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.

$\endgroup$
0
$\begingroup$

Rosanswers logo

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/api/node.html

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.


Originally posted by tfoote with karma: 58457 on 2021-01-05

This answer was NOT ACCEPTED on the original site

Post score: 3

$\endgroup$
0
$\begingroup$

Rosanswers logo

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

Originally posted by ksato-dev with karma: 83 on 2021-01-06

This answer was NOT ACCEPTED on the original site

Post score: 5

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.