Creating a package (Python)

First of all, make sure you are in the src folder of your workspace before running the package creation command.

cd ~/ros2_ws/src

Also, make sure that you have sourced your ROS2 installation.

source opt/ros/eloquent/setup.bash

Now you are ready to create your package. The command structure for creating ROS 2 packages is the following.

ros2 pkg create <package_name> --build-type ament_python --dependencies <package_dependecies>

The package_name is the name of the package you want to create, and the package_dependencies are the names of other ROS packages that your package depends on. It's important to remark that this command MUST be executed in your ROS2 workspace (for this tutorials, it's ~/ros2_ws/src).

For creating a Python package, execute the following command.

ros2 pkg create my_package --build-type ament_python --dependencies rclcpy

You should get something like thisin your shell.

This will create inside our src directory a new package with some files in it. If you check the files inside your package, you will see the following:

In order to check that our package has been created successfully, we can use some ROS commands related to packages. For example, let's type:

ros2 pkg list
ros2 pkg list | grep my_package

Build your package

Return to the root of your workspace:

cd ~/ros2_ws

Now you can build your packages:

colcon build

To build only the my_package package you have created, you can run:

colcon build --packages-select my_package

Source your workspace

Finally, remember yo source your workspace after building it.

cd ~/ros2_ws
source install/setup.bash

Practice Online

Also, you can test this tutorial in ROSDS, using a ROSject which already contains all the code described in it. You can get the ROSject by clicking on the button below:

Above: Get ROSDS ROSject

The link above will take yo a page like the below one:

Now, you just need to Sign In (or Sign Up if you don't have an account yet) to ROSDS in order to launch the ROSject.