How to create a simple Python node
-
docker-compose exec dev bash
-
cd src
-
ros2 pkg create my_py_pkg --build-type ament_python --dependencies rclpy
-
Create a Python file:
touch my_py_pkg/my_py_pkg/my_first_node.py
-
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()
-
Make the file executable:
chmod +x the_python_file.py
. Then you can execute by running./the_python_file.py
-
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 ], },
-
Go to the root of your workspace:
cd /ros2_ws
-
Build your package:
colcon build --packages-select my_py_pkg --symlink-install
-
Source again:
source ~/.bashrc
-
Run your node manually:
./install/my_py_pkg/lib/my_py_pkg/py_node
-
Run your node through ROS2 commands (source
~/.bashrc
again if necessary):ros2 run my_py_pkg py_node