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, which is the current, actively supported version as ROS 1 reaches its end-of-life in 2025 [1].

Table of Contents

  1. Understanding the ROS 2 Architecture
  2. Setting Up Your Python Environment
  3. Building a Basic Python Publisher
  4. Data Types and Custom Interfaces
  5. Python vs. C++ in ROS 2
  6. Summary of Key Takeaways
  7. 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 or dive deeper into the general framework in our Introduction to Robot Operating System (ROS).

ROS 2 Communication GraphDiagram showing Node A publishing to a Topic and Node B subscribing.Node ANode BTopicDDS Layer

Setting Up Your Python Environment

To program in ROS 2 with Python, you must use the rclpy (ROS Client Library for Python) package. The current Long Term Support (LTS) distribution recommended for most users is ROS 2 Humble Hawksbill, which is supported until May 2027 [3].

Installation and Workspace Creation

Most developers use Ubuntu Linux (specifically version 22.04 for Humble) as the host OS. However, it is increasingly common to use Docker containers [1] to avoid dependency conflicts.

  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()

Community discussions on Reddit’s r/ROS often highlight that beginners frequently 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. For example, if you are working with complex motion planning, you might combine your ROS Python scripts with the concepts found in our guide on Introduction to Optimal Control Theory.

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:

FeaturePython (rclpy)C++ (rclcpp)
Development SpeedVery HighMedium
Execution PerformanceStandardHigh (Real-time capable)
Library SupportML, AI, Data ScienceHardware drivers, Math kernels
ComplexitySimpleTechnical / High Memory Mgmt

Prototyping in Python is recommended for 90% of robotic tasks, including high-level decision-making and vision processing.

Summary of Key Takeaways

Main Points Covered

  • ROS 2 is Middleware: It manages communication between software components (nodes) via a decentralized DDS system.
  • Python is the Standard for Prototyping: Using the rclpy library, developers can rapidly build publishers, subscribers, and services.
  • The Power of the Graph: ROS 2 nodes communicate through Topics (streaming), Services (request/response), and Actions (goal-oriented).
  • Distribution Choice: Use ROS 2 Humble for a stable, long-term support environment.

Action Plan

  1. Set up Ubuntu 22.04 or Docker and install the ROS 2 Humble distribution.
  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.

Table: Introduction to ROS with Python Cheat Sheet
CategoryKey Detail
MiddlewareROS 2 Humble (LTS until 2027)
Core Libraryrclpy (Python Client Library)
ArchitectureDecentralized Graph via DDS
CommunicationTopics, Services, and Actions
Build Systemcolcon with ament_python packages

Sources