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
- SimplifyAny section in plain language
- SummarizeThe key points at a glance
- FAQQuick answers to common questions
- NewSpotted a mistake? We fix it in minutes!
Written with AI from the sources listed at the end.
Table of Contents
- Understanding the ROS 2 Architecture
- ROS 1 vs. ROS 2
- Setting Up Your Python Environment
- Building a Basic Python Publisher
- Data Types and Custom Interfaces
- Python vs. C++ in ROS 2
- Tools Every ROS Developer Uses
- Action Plan
- 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 2 replaces the centralized ROS Master with a decentralized Data Distribution Service (DDS). This ensures that the failure of a single node does not cause the entire system to crash, making it more suitable for industrial applications.
Topics are used for continuous data streaming where multiple nodes can publish or subscribe, while Services follow a request-response pattern intended for discrete, one-off actions like triggering a sensor.
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].
| Feature | ROS 1 | ROS 2 |
|---|---|---|
| Messaging | Custom TCPROS / UDPROS | DDS (Industry Standard) |
| Architecture | ROS Master (Single Point of Failure) | Decentralized (No Master) |
| Security | Lacks built-in security | DDS-Security: authentication, encryption, access control |
| Real-Time | Not natively real-time | Supports Real-Time systems |
ROS 2 utilizes the Data Distribution Service (DDS) protocol, which provides industrial-grade security and real-time performance. Unlike ROS 1, it removes the central ‘Master’ node, creating a decentralized system that is more robust for production environments.
No, it is highly recommended to focus exclusively on ROS 2. ROS 1 reached its official End of Life (EOL) in May 2025, meaning it will no longer receive updates or official support for new developments.
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.
| Release | Ubuntu version | Supported until |
|---|---|---|
| Lyrical Luth (newest) | 26.04 | May 2031 |
| Jazzy Jalisco | 24.04 | May 2029 |
| Humble Hawksbill | 22.04 | May 2027 |
- Create a Workspace: Your projects live in a
colconworkspace.bash mkdir -p ~/ros2_ws/src cd ~/ros2_ws/src - Create a Package: Develop your Python scripts within a localized package structure.
bash ros2 pkg create --build-type ament_python my_robot_pkg
Ubuntu 22.04 is the official host operating system for ROS 2 Humble. Developers can also use Docker containers to run ROS 2 environments without conflicting with their local system dependencies.
The rclpy package is the ROS Client Library for Python. It provides the essential APIs that allow Python scripts to interact with the ROS 2 ecosystem, including creating nodes and managing communication.
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.
The spin function keeps the node alive and active. Without it, the script would finish executing immediately and your callback functions, such as timers for publishing data, would never be triggered.
That number represents the queue size for the publisher. It limits the amount of outgoing messages stored in memory if the system cannot send them as fast as they are being generated.
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.
| Package Name | Primary Data Types |
|---|---|
| std_msgs | String, Int32, Float64, Bool |
| sensor_msgs | Image, LaserScan, PointCloud2, Imu |
| geometry_msgs | Twist, Pose, Transform, Vector3 |
Yes, ROS 2 uses strictly typed, language-independent interfaces. As long as both nodes use the same message definition (like std_msgs), they can communicate seamlessly regardless of the programming language used.
For custom hardware, you can define your own .msg files. ROS 2 will then compile these definitions into Python classes that you can import and use just like standard messages.
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:
| Feature | Python (rclpy) | C++ (rclcpp) |
|---|---|---|
| Development speed | Very high | Medium |
| Execution performance | Standard | High (real-time capable) |
| Library support | ML, AI, data science | Hardware drivers, math kernels |
| Complexity | Simple | Higher (memory management) |
Python suits most prototyping, high-level decision-making and vision processing, while C++ is the usual choice for time-critical control loops.
C++ (rclcpp) is preferred for high-performance tasks such as real-time control loops or hardware drivers. Python is usually better for high-level logic, AI integration, and rapid prototyping.
For most tasks, yes: Python is fast enough for prototyping, vision processing and decision-making, where hard real-time execution is not the main constraint; time-critical control loops are usually written in C++.
Tools Every ROS Developer Uses
One of the primary reasons for the dominance of ROS is its ecosystem of diagnostic and visualization tools.
- 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.
- Gazebo: A high-fidelity physics simulator. You can test your code on a virtual robot in a virtual world before risking expensive hardware.
- Rqt: A plugin-based GUI that lets you visualize the communication graph of your nodes or plot data (like motor velocity) in real-time.
RViz is a 3D visualization tool that allows developers to see the robot’s internal state. It renders complex data like lidar point clouds, camera feeds, and mapping transformations, making it essential for debugging sensor data and navigation.
Yes, you can use Gazebo, a high-fidelity physics simulator. Gazebo allows you to create virtual robots in realistic environments, enabling you to test and refine your code safely and for free before deploying it to actual hardware.
Action Plan
- Set up Ubuntu 24.04 or Docker and install ROS 2 Jazzy (or Ubuntu 26.04 with Lyrical).
- Initialize a Workspace using
colconand create your firstament_pythonpackage. - Implement a Publisher/Subscriber pair to understand how data flows between different processes.
- Explore Tutorials: Follow the official ROS 2 Beginner tutorials to practice with tools like
turtlesimandrqt. - 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.
ROS 2 Humble is a Long Term Support (LTS) distribution supported until May 2027; for new projects, the newer LTS releases Jazzy (until May 2029) and Lyrical (until May 2031) are better choices.
After mastering publishers and subscribers in a simulated environment, you can use microcontrollers like an Arduino or ESP32 to bridge your Python commands to physical components like motors and sensors.