UP | HOME

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

  1. With this method, you install pip packages directly into a ROS 2 workspace
  2. Whenever that workspace is sourced (either directly or as an underlay), the python packages installed will be used by all ROS 2 nodes.
  3. Packages installed via this manner will override any packages installed on the system.

Steps

  1. Create a new ROS workspace and ament_python package

    mkdir -p ws/src
    cd ws/src
    ros2 pkg create --build-type ament_python py_venv
    cd ..
    
  2. Build and source the workspace:

    colcon build
    source install/setup.bash
    
  3. Rather than calling pip directly, use the following invocation: PYTHONUSERBASE=$(ros2 pkg prefix py_venv) pip3 install --user --break-system-packages <OTHER ARGS HERE>
  4. The above command will override system packages, which could cause some ROS 2 packages to break. You may need to:
    1. Use the --no-deps flags 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 from pip.
    2. 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.0 by default, but ROS packages require numpy < 2

Virtual Environment

  1. With this method a virtual environment is created and sourced separately.
  2. Individual packages must opt-in to use the virtual environment in their setup.cfg
  3. The virtual environment must be activated in addition to sourcing the workspace

Steps

  1. Any python package that uses virtual environments must have the following adding to the setup.cfg

    [build_scripts]
    executable = /usr/bin/env python3
    
  2. Create the virtual environment: python3 -m venv myvenv
  3. If the virtual environment is in a ROS 2 workspace: touch myvenv/COLCON_IGNORE
  4. Activate the virtual environment: source myvenv/bin/activate
  5. The packages that have had their setup.cfg modified will now use the virtual environment
  6. You will need to activate the virtual environment every time you want to use it, in addition to sourcing the ros2 workspace

Author: Matthew Elwin.