Running ROS2 Nodes in a Python Virtual Environment

Jegathesan Shanmugam
ROS2 Tips And Tricks
1 min readJan 4, 2023

Using Python virtual environments for ROS2 nodes can be a useful way to manage dependencies and avoid conflicts between different packages. Here are the steps to set up a Python virtual environment for a ROS2 node:
1. Source the setup file for your ROS2 distribution
2. Navigate to the desired location for the virtual environment and create a new virtual environment.
3. Activate the virtual environment
4. Make changes in the setup.cfg file
5. Build the workspace using colcon build.
6. Run the Node

# Source
source /opt/ros/foxy/setup.zsh

# Create a Virtual environment and Activate
python3 -m venv torch_test --system-site-packages --symlinks
source torch_test/bin/activate

# Install torch for testing
python3 -m pip install torch

# Add this line to setup.cfg file of your package
[build_scripts]
executable = /usr/bin/env python3

# Build
colcon build

# Run
ros2 run pkg_name node_name=

Reference:
https://github.com/colcon/colcon-core/pull/183/files#diff-fa602a8a75dc9dcc92261bac5f533c2a85e34fcceaff63b3a3a81d9acde2fc52
https://github.com/colcon/colcon-core/pull/183

--

--

Jegathesan Shanmugam
ROS2 Tips And Tricks

Talks about #robotics, #computervision, and #embeddedsystems