Skip to content

Using Python Virtual Environments #1094

@jandaa

Description

@jandaa

Bug report

I'm trying to use a python virtual environment in my colcon workspace to separate system level and node level dependencies. I'm following the instructions given in this tutorial in the ros2 documentation (Specifically installing via a virtual environment). However, when I check what python interpreter is being used inside the node, it returns the system level one instead of the virtual environment. This can be further verified by installing a package in the virtual environment that is not present in the system environment and try importing it from inside the node.

I have tried doing a clean build with and without sourcing the virtual environment in the build shell. I have also tried using virtualenv as in the tutorial and also python -m venv. I also call my virtual environment "venv" as in the tutorial.

Required Info:

  • Operating System: Ubuntu 20.04
  • Installation type: Binaries
  • Version or commit hash: Foxy Fitzroy
  • DDS implementation: (Default) Cyclone DDS
  • Client library (if applicable): N/A

Steps to reproduce issue

  1. Follow the steps in the tutorial
  2. Create a ros2 python package with cd src && ros2 pkg create venv --build-type ament_python
  3. Create a python node called venv.py under src/venv/venv with the following code
import rclpy
from rclpy.node import Node
import sys

class ExampleNode(Node):
    def __init__(self):
        super().__init__('sensors')
        self.get_logger().info("ExampleNode started")
        self.get_logger().info(f"python path: {sys.executable}")

def main(args=None):
    rclpy.init(args=args)
    node = ExampleNode()
    rclpy.spin(node)
    rclpy.shutdown()

if __name__ == '__main__':
    main()
  1. Add the node to setup.py with
entry_points={
      'console_scripts': [
          'venv = venv.venv:main'
      ],
  },
  1. Build using
source ./venv/bin/activate
source /opt/ros/foxy/setup.bash
colcon build
source install/setup.sh
  1. Run using ros2 run venv venv

Expected behavior

The returned python path should show ${workspaceFolder}/venv/bin/python and any packages installed in the virtual environment should be accessible inside the node.

Actual behavior

Returns the system base python /usr/bin/python3 and breaks when trying to import a package that is installed in the virtual environment but not at system level.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions