출처

Running ROS2 Nodes in a Python Virtual Environment

Running ROS2 Nodes in a Python Virtual Environment

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

#만약 가상환경 만드는 모듈이 설치가 안되었을 경우
sudo apt install python3.xx-venv

# Create a Virtual environment and Activate
python3.xx -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=

  1. Edit PYTHONPATH

symlink-install (colcon build)

위의 내용대로면 package마다 적용이 가능하다 다만 —symlink-install 옵션을 사용할 때 문제가 된다.

이는 PYTHONPATH를 설정해주면 된다.

이 때, 빌드 후

export PYTHONPATH=/{path/to/your/virtualenv}/lib/python3.x/site-packages:$PYTHONPATH