Skip to content
Semillero
ARES

ROS 2

ROS 2 with Python

By Juan Felipe Martínez Bedoya

This tutorial explains how to create ROS 2 packages, nodes and launch files with Python.

Packages

Structure

A ROS 2 Python package has this structure:

  • package.xml: package information, such as its dependencies.
  • setup.py: instructions to build and install the package.
  • setup.cfg: where executables are installed.
  • <packageName>/: a folder with the same name as the package, holding the .py files.
  • launch/: launch files.

Creating a package

Load the ROS 2 environment (replace humble with your distribution):

source /opt/ros/humble/setup.bash

Create the workspace and its src folder, where packages live:

mkdir -p ~/ros2_ws/src
cd ~/ros2_ws/src

Inside src, create the package:

ros2 pkg create --build-type ament_python <packageName> --dependencies rclpy
  • --build-type ament_python says it is a Python package.
  • --dependencies lists the packages it depends on, separated by spaces. With Python you almost always use rclpy.

Build from the workspace root to check everything is fine:

cd ~/ros2_ws
colcon build --packages-select <packageName>
source install/setup.bash

To confirm the package exists:

ros2 pkg list | grep <packageName>

setup.py

entry_points declares the executables the package generates, in the form <executableName> = <packageName>.<file>:main:

entry_points={
    'console_scripts': [
        'simple_node = my_package.simple:main',
    ],
},

In this example, ros2 run my_package simple_node runs the main function in my_package/simple.py.

For colcon to install launch files, add them to data_files (and add import os and from glob import glob at the top of setup.py):

data_files=[
    ('share/ament_index/resource_index/packages', ['resource/' + package_name]),
    ('share/' + package_name, ['package.xml']),
    (os.path.join('share', package_name), glob('launch/*.launch.py')),
],

Launch files then end up in ~/ros2_ws/install/<packageName>/share/<packageName>/.

Launch files

A launch file starts one or more nodes with their configuration, so you do not have to run them one by one:

from launch import LaunchDescription
from launch_ros.actions import Node

def generate_launch_description():
    return LaunchDescription([
        Node(
            package='turtlebot3_teleop',
            executable='teleop_keyboard',
            output='screen',
        ),
    ])

generate_launch_description returns a LaunchDescription with the nodes to start. Each Node gives the package, the executable and where its output goes (screen shows it in the terminal).

A minimal program

import rclpy

def main(args=None):
    rclpy.init(args=args)      # start communication with ROS 2
    print("Hello world!")
    rclpy.shutdown()           # close communication

if __name__ == '__main__':
    main()

A node

import rclpy
from rclpy.node import Node

class MyNode(Node):
    def __init__(self):
        # Node name (no spaces)
        super().__init__('my_node')
        # Call timer_callback every 0.2 s
        self.create_timer(0.2, self.timer_callback)

    def timer_callback(self):
        self.get_logger().info("Hello world from a node!")

def main(args=None):
    rclpy.init(args=args)
    node = MyNode()
    rclpy.spin(node)    # keep the node alive until Ctrl+C
    rclpy.shutdown()

if __name__ == '__main__':
    main()

Publishing messages

This node publishes a string on the /greeting topic every half second:

import rclpy
from rclpy.node import Node
from std_msgs.msg import String

class Publisher(Node):
    def __init__(self):
        super().__init__('publisher')
        self.pub = self.create_publisher(String, 'greeting', 10)
        self.create_timer(0.5, self.publish_greeting)

    def publish_greeting(self):
        msg = String()
        msg.data = 'Hello from ARES!'
        self.pub.publish(msg)

def main(args=None):
    rclpy.init(args=args)
    rclpy.spin(Publisher())
    rclpy.shutdown()

Add std_msgs to the package dependencies. In another terminal you can watch the messages with ros2 topic echo /greeting.

Translated from Spanish.