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
-
Create workspace:
mkdir -p ~/ros2_ws/src
cd ~/ros2_ws -
Create package:
ros2 pkg create --build-type ament_python my_python_pkg -
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() -
Update setup.py and package.xml.
-
Build:
colcon build -
Source:
source install/setup.bash -
Run:
ros2 run my_python_pkg minimal_node
Self‑Assignment
- Create your own custom ROS 2 Python package.
- Add two nodes communicating via a topic.
- Add parameters to your node.
- Document your package folder structure.
- Try running nodes with remapping.
MCQs
- ROS 2 Python packages use which build type?
a) ament_cmake
b) catkin
c) ament_python
d) bazel - The command to build a workspace is:
a) ros2 build
b) colcon build
c) build_ros2
d) rosbuild - Which file defines dependencies?
a) setup.cfg
b) node.py
c) package.xml
d) build.xml - Which function starts the ROS 2 client library?
a) rclpy.run()
b) rclpy.start()
c) rclpy.init()
d) rclpy.begin() - A ROS 2 node is:
a) A sensor
b) A running executable
c) A folder
d) A virtual machine