Using Pip With ROS 2
Overview
This guide explains two methods for installing pip packages directly into a ROS colcon workspace.
One method uses pip and the ROS 2 workspace method directly, while the other uses virtual environments.
Direct Into A Workspace
- With this method, you install pip packages directly into a ROS 2 workspace
- Whenever that workspace is sourced (either directly or as an underlay), the python packages installed will be used by all ROS 2 nodes.
- Packages installed via this manner will override any packages installed on the system.
Steps
Create a new ROS workspace and
ament_pythonpackagemkdir -p ws/src cd ws/src ros2 pkg create --build-type ament_python py_venv cd ..
Build and source the workspace:
colcon build source install/setup.bash- Rather than calling
pipdirectly, use the following invocation:PYTHONUSERBASE=$(ros2 pkg prefix py_venv) pip3 install --user --break-system-packages <OTHER ARGS HERE> - The above command will override system packages, which could cause some ROS 2 packages to break. You may need to:
- Use the
--no-depsflags and add needed dependencies manually: this is a good way to go if you want to ensure most packages are from the system (e.g., ROS 2 compatible) and only unavailable ones are frompip. - Specifically uninstall packages that conflict with
PYTHONUSERBASE=$(ros2 pkg prefix pyvenv) pip3 uninstall --break-system-packages <UNINSTALL>- The goal is to find package versions that work with both ROS 2 and whatever package you are installing.
- For example, many pip packages use
numpy > 2.0by default, but ROS packages requirenumpy < 2
- Use the
Virtual Environment
- With this method a virtual environment is created and sourced separately.
- Individual packages must opt-in to use the virtual environment in their
setup.cfg - The virtual environment must be activated in addition to sourcing the workspace
Steps
Any python package that uses virtual environments must have the following adding to the
setup.cfg[build_scripts] executable = /usr/bin/env python3
- Create the virtual environment:
python3 -m venv myvenv - If the virtual environment is in a ROS 2 workspace:
touch myvenv/COLCON_IGNORE - Activate the virtual environment:
source myvenv/bin/activate - The packages that have had their
setup.cfgmodified will now use the virtual environment - You will need to activate the virtual environment every time you want to use it, in addition to sourcing the
ros2 workspace