Skip to main content

2.3 Building ROS 2 packages with Python

Creating ROS 2 Packages in Python

Overview

This module covers how to create ROS 2 Python packages, structure nodes, and use topics, services, and actions.

Workflow Diagram

flowchart TD
A[Create Workspace] --> B[Create ROS 2 Package]
B --> C[Write Python Nodes]
C --> D[Setup setup.py & package.xml]
D --> E[Build Workspace]
E --> F[Source Overlay]
F --> G[Run Nodes]

Steps to Create a ROS 2 Python Package

  1. Create workspace:

    mkdir -p ~/ros2_ws/src
    cd ~/ros2_ws
  2. Create package:

    ros2 pkg create --build-type ament_python my_python_pkg
  3. Write node:

    import rclpy
    from rclpy.node import Node

    class MinimalNode(Node):
    def __init__(self):
    super().__init__('minimal_node')
    self.get_logger().info("Node Started")

    def main():
    rclpy.init()
    node = MinimalNode()
    rclpy.spin(node)
    node.destroy_node()
    rclpy.shutdown()

    if __name__ == "__main__":
    main()
  4. Update setup.py and package.xml.

  5. Build:

    colcon build
  6. Source:

    source install/setup.bash
  7. Run:

    ros2 run my_python_pkg minimal_node

Self‑Assignment

  1. Create your own custom ROS 2 Python package.
  2. Add two nodes communicating via a topic.
  3. Add parameters to your node.
  4. Document your package folder structure.
  5. Try running nodes with remapping.

MCQs

  1. ROS 2 Python packages use which build type? a) ament_cmake
    b) catkin
    c) ament_python
    d) bazel
  2. The command to build a workspace is: a) ros2 build
    b) colcon build
    c) build_ros2
    d) rosbuild
  3. Which file defines dependencies? a) setup.cfg
    b) node.py
    c) package.xml
    d) build.xml
  4. Which function starts the ROS 2 client library? a) rclpy.run()
    b) rclpy.start()
    c) rclpy.init()
    d) rclpy.begin()
  5. A ROS 2 node is: a) A sensor
    b) A running executable
    c) A folder
    d) A virtual machine