Introduction to ROS using Python

The robotics landscape is currently dominated by the Robot Operating System (ROS), a framework that has become the industry standard for developing complex autonomous systems. While ROS is not a traditional operating system like Windows or Linux, it serves as a powerful middleware layer that allows different parts of a robot—such as sensors, actuators, and AI logic—to communicate seamlessly.

For developers entering this field, Python has emerged as the most popular entry point due to its readable syntax and vast library support for machine learning and computer vision. This guide provides a technical foundation for using Python to program robots within the ROS 2 ecosystem, the actively supported version now that ROS 1 reached its end of life in May 2025 [1].

Your reading tools

  • Simplify
    Any section in plain language
  • Summarize
    The key points at a glance
  • FAQ
    Quick answers to common questions
  • New
    i
    Spotted a mistake? We fix it in minutes!

Written with AI from the sources listed at the end.

Table of Contents

  1. Understanding the ROS 2 Architecture
  2. ROS 1 vs. ROS 2
  3. Setting Up Your Python Environment
  4. Building a Basic Python Publisher
  5. Data Types and Custom Interfaces
  6. Python vs. C++ in ROS 2
  7. Tools Every ROS Developer Uses
  8. Action Plan
  9. Sources

Understanding the ROS 2 Architecture

Before writing code, it is essential to understand the “Graph” architecture. A ROS system is composed of several independent nodes that communicate through a decentralized network. Unlike earlier versions that required a central “ROS Master,” ROS 2 utilizes the Data Distribution Service (DDS) [2]. This change ensures that if one node fails, the rest of the system remains functional, a critical requirement for industrial and safety-critical robotics.

Key concepts include:

  • Nodes: Individual Python scripts that perform specific tasks (e.g., a “Camera Node” or a “Motor Driver Node”).

  • Topics: Channels where nodes publish and subscribe to continuous streams of data, such as LIDAR scans.

  • Services: A request-response mechanism used for discrete actions, such as “Trigger Camera” or “Reset Odometry.”

  • Actions: Used for long-running goals that provide progress updates, such as “Move to GPS Coordinate.”

While this guide focuses on Python, some high-performance control loops may require different tools. You can learn more about alternatives in our Introduction to MATLAB in Robotics.

ROS 1 vs. ROS 2

The original ROS (now called ROS 1) was designed for academic research. While revolutionary, it lacked the robustness required for commercial products, specifically regarding real-time performance and security.

ROS 2 represents a complete ground-up rewrite. The most significant change is the move to DDS (Data Distribution Service), an industry-standard communication protocol used in aerospace and defense [1]. Unlike ROS 1, which relied on a central “Master” node that could be a single point of failure, ROS 2 is decentralized.

New developers should therefore focus on ROS 2: ROS 1 reached its official end of life (EOL) in May 2025 [1].

Table: Key differences between ROS 1 and ROS 2 architectures
FeatureROS 1ROS 2
MessagingCustom TCPROS / UDPROSDDS (Industry Standard)
ArchitectureROS Master (Single Point of Failure)Decentralized (No Master)
SecurityLacks built-in securityDDS-Security: authentication, encryption, access control
Real-TimeNot natively real-timeSupports Real-Time systems

Setting Up Your Python Environment

To program in ROS 2 with Python, you must use the rclpy (ROS Client Library for Python) package. The newest Long Term Support (LTS) release is ROS 2 Lyrical Luth (May 2026, supported until May 2031); Jazzy Jalisco (until May 2029) and Humble Hawksbill (until May 2027) are still supported too [3]. The commands below work the same way on each.

Installation and Workspace Creation

Each release targets a specific Ubuntu version (26.04 for Lyrical, 24.04 for Jazzy, 22.04 for Humble). However, it is increasingly common to use Docker containers [1] to avoid dependency conflicts.

Table: Supported ROS 2 LTS releases
ReleaseUbuntu versionSupported until
Lyrical Luth (newest)26.04May 2031
Jazzy Jalisco24.04May 2029
Humble Hawksbill22.04May 2027
  1. Create a Workspace: Your projects live in a colcon workspace. bash mkdir -p ~/ros2_ws/src cd ~/ros2_ws/src
  2. Create a Package: Develop your Python scripts within a localized package structure. bash ros2 pkg create --build-type ament_python my_robot_pkg

Building a Basic Python Publisher

The most fundamental task in ROS is publishing data to a topic. Below is the structure for a minimal Python node that broadcasts a “Hello World” message.

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


class SimplePublisher(Node):
    def __init__(self):
        super().__init__('minimal_publisher')
        self.publisher_ = self.create_publisher(String, 'topic_name', 10)
        self.timer = self.create_timer(0.5, self.timer_callback)

    def timer_callback(self):
        msg = String()
        msg.data = 'Robot Status: Active'
        self.publisher_.publish(msg)
        self.get_logger().info('Publishing: "%s"' % msg.data)


def main(args=None):
    rclpy.init(args=args)
    minimal_publisher = SimplePublisher()
    rclpy.spin(minimal_publisher)
    minimal_publisher.destroy_node()
    rclpy.shutdown()


if __name__ == '__main__':
    main()

Beginners often forget to “spin” the node. Without rclpy.spin(), your callbacks (like the timer) will never execute.

Data Types and Custom Interfaces

ROS uses strictly typed interfaces to ensure that a Python node can talk to a C++ node without errors. Common message types are found in std_msgs or sensor_msgs. For custom robotics hardware, you may need to define your own .msg files, which ROS then compiles into Python classes [4].

Using standardized messages allows you to easily integrate advanced math.

Table: Common ROS 2 Message Packages and Use Cases
Package NamePrimary Data Types
std_msgsString, Int32, Float64, Bool
sensor_msgsImage, LaserScan, PointCloud2, Imu
geometry_msgsTwist, Pose, Transform, Vector3

Python vs. C++ in ROS 2

A common debate in the community is whether to use Python or C++. According to official ROS documentation, the choice depends on the specific use case:

Table: Python (rclpy) vs. C++ (rclcpp) in ROS 2
FeaturePython (rclpy)C++ (rclcpp)
Development speedVery highMedium
Execution performanceStandardHigh (real-time capable)
Library supportML, AI, data scienceHardware drivers, math kernels
ComplexitySimpleHigher (memory management)

Python suits most prototyping, high-level decision-making and vision processing, while C++ is the usual choice for time-critical control loops.

Tools Every ROS Developer Uses

One of the primary reasons for the dominance of ROS is its ecosystem of diagnostic and visualization tools.

  1. RViz (ROS Visualization): Allows you to see what the robot “sees.” It can render 3D point clouds from lidar, show camera feeds, and display the robot’s current estimated position on a map.
  2. Gazebo: A high-fidelity physics simulator. You can test your code on a virtual robot in a virtual world before risking expensive hardware.
  3. Rqt: A plugin-based GUI that lets you visualize the communication graph of your nodes or plot data (like motor velocity) in real-time.

Action Plan

  1. Set up Ubuntu 24.04 or Docker and install ROS 2 Jazzy (or Ubuntu 26.04 with Lyrical).
  2. Initialize a Workspace using colcon and create your first ament_python package.
  3. Implement a Publisher/Subscriber pair to understand how data flows between different processes.
  4. Explore Tutorials: Follow the official ROS 2 Beginner tutorials to practice with tools like turtlesim and rqt.
  5. Interface with Hardware: Once comfortable, use a microcontroller (like an ESP32 or Arduino) to bridge Python commands to physical motors [1].

While the learning curve of ROS can be steep, the ability to leverage a global ecosystem of pre-built packages makes it an indispensable skill for any modern robotics engineer.

Sources