Getting Started with ROS2 and Python

2025-04-01

Introduction

ROS2 (Robot Operating System 2) is an essential framework for developing robotic applications. In this post, we'll go through the steps to create a simple ROS2 node using Python.

Prerequisites

Before we begin, make sure you have the following installed:

You can install ROS2 by following the official ROS2 installation guide.

Creating a ROS2 Package

Let's start by creating a new ROS2 package:

cd ~/ros2_ws/src
ros2 pkg create --build-type ament_python my_python_pkg

This is how you write python

import rclpy
from rclpy.node import Node

class SimpleNode(Node):
    def __init__(self):
        super().__init__('simple_nodesimple_nodesimple_nodesimple_nodesimple_nodesimple_nodesimple_nodesimple_node')
        self.get_logger().info("Hello, ROS2!")

def main(args=None):
    rclpy.init(args=args)
    node = SimpleNode()
    rclpy.spin(node)
    node.destroy_node()
    rclpy.shutdown()

if __name__ == '__main__':
    main()

This is how you do in c++

#include "rclcpp/rclcpp.hpp"

class SimpleNode : public rclcpp::Node {
  public:
    SimpleNode() : Node("simple_node") {
        RCLCPP_INFO(this->get_logger(), "Hello, ROS2 from C++!");
    }
};

int main(int argc, char** argv) {
    rclcpp::init(argc, argv);
    auto node = std::make_shared<SimpleNode>();
    rclcpp::spin(node);
    rclcpp::shutdown();
    return 0;
}

this is the image

image