How to create a simple Python node

  1. docker-compose exec dev bash

  2. cd src

  3. ros2 pkg create my_py_pkg --build-type ament_python --dependencies rclpy

  4. Create a Python file: touch my_py_pkg/my_py_pkg/my_first_node.py

  5. Edit the file and add:

    #!/usr/bin/env python3
    import rclpy
    from rclpy.node import Node
    
    
    def main(args=None):
        rclpy.init(args=args)
        node = Node('py_test')
        node.get_logger().info('Hello ROS2')
        rclpy.spin(node)
        rclpy.shutdown()
    
    
    if __name__ == '__main__':
        main()
  6. Make the file executable: chmod +x the_python_file.py. Then you can execute by running ./the_python_file.py

  7. Add your node to src/my_py_pkg/setup.py

    entry_points={
        'console_scripts': [
            'py_node = my_py_pkg.my_first_node:main' # <-- this line
        ],
    },
  8. Go to the root of your workspace: cd /ros2_ws

  9. Build your package: colcon build --packages-select my_py_pkg --symlink-install

  10. Source again: source ~/.bashrc

  11. Run your node manually: ./install/my_py_pkg/lib/my_py_pkg/py_node

  12. Run your node through ROS2 commands (source ~/.bashrc again if necessary): ros2 run my_py_pkg py_node