Creating a workspace and a package
The first step is to create a workspace and a package within that workspace. This is covered well in the official documentation, so we won't repeat those steps here:Adding code to the package
After creating the workspace and package, add the Python code for your ROS node(s) to the package. The recommended file organization is to place these programs three levels deep:- Within your workspace, in srcsubdirectory for the workspace.
- Within that srcsubdirectory, a package source subdirectory with the same name as your package.
- Within that package source subdirectory, another subdirectory with the same name as your package.
ros_ws
, my Project 1
package is called project1
, and my program is called circle.py
.
So I created a directory called
ros_ws/src/project1/project1
circle.py
source code in that directory:
ros_ws/src/project1/project1/circle.py
Creating an entry point
Next, you should declare your program as an “entry point” for the package, so thatros2 run
can locate and execute the program. This is
done by modifying the package's setup.py
, adding an element to the
entry_points
list, which is empty by default.
In my example, the entry_points
block looks like this:
entry_points={
'console_scripts': [
'circle = project1.circle:main',
],
}
circle
should exist, and when that
command is run, it should execute the function called main
in the
circle
module inside the project1
Python package. If you have
more than one program, you can add multiple entries to this list.
Building the package
After adding your program to the package, you should build the package. This step uses the package configuration to assemble all of the parts of the complete package in a place where theros2
runtime system
can locate them. (For programs written in compiled languages like C++,
this step is also where the compilation process happens.)
To build after the package setup is complete, run this command in your
workspace directory:
colcon build
source install/setup.bash
ros2 pkg list
ros2 run
. For
example, I can use the command
ros2 run project1 circle
colcon build
step should
be repeated to ensure that the latest versions are available to ROS.
This page from the official documentation has a few more details about
building packages: