Context
I’m running ROS 2 Jazzy on Ubuntu 24.04, and I need to use some Python 3.12 external libraries.
What I tried
In this GitHub issue they talked about this problem. From my understanding ROS2 is not meant to be used with virtual envs.
As suggested here, i tried the following
# 1) Create and activate venv
python3.12 -m venv ~/my_venv
source ~/myvenv/bin/activate
# 2) Install external packages
pip install foo bar
# 3) Source ros2 env
source /opt/ros/jazzy/setup.bash
# 4) Build with colcon
colcon build
Despite activating the virtual environment, colcon still invokes /usr/bin/python3 and it searches packages inside /opt/ros/jazzy/lib/python3.12/site-packages, while ignoring packages installed in ~/my_venv.
Looks like it's because colcon has been installed with apt, so it will always use the default interpreter.
What I would do
Since it's not defined a "best practice" to handle external python packages with ROS2, I'd highlight the solutions suggested by amjad-haider (also stated here):
python3 -m venv ~/my_venv
export PYTHONPATH="~/my_venv/lib/python3.12/site-packages:$PYTHONPATH"
source ~/my_venv/bin/activate
colcon build
tl;dr It adds the site-packages path from your virtual environment to the PYTHONPATH variable, so that colcon also searches there to find your custom packages.
Question
Could this be considered the best practice for handling external Python packages with ROS 2? Are there any potential issues I'm overlooking?