ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question
0

ROS with python virtual environment

asked 2023-03-02 14:06:28 -0600

zrahman gravatar image

I installed ROS noetic on my ubuntu machine using apt command. It uses root python installation (python3.8) like /usr/bin/python3. All ROS related python modules like rospkg, rospy, cv_bridge have been installed for this interpretor. Now, as I work on other big projects, I need to install many python modules and even different python versions. So, I use conda or python venv environment for that. How can I run those projects in ROS since it uses the root installation interpretor? If I activate a virtual env, the ROS node does not run and shows error like

ModuleNotFoundError: No module named "rospkg"

What is the best way to handle different python environments along with ROS?

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-03-03 07:42:23 -0600

bluegiraffe-sc gravatar image

Hi!

To run the nodes in a virtual environment of your choice, you should change the shebang (i.e. the very first line in your script which should look something like #!/usr/bin/env python) of your scripts so to point to the Python interpreter of the virtual environment.

As an example, if your virtual environment name is venv the first line in the script should be #!/path/to/venv/bin/python3. This is of course not so portable, as you are hardcoding the path in each and every script. A more flexible solution I have recently started to use is to set the virtual environment from the launch file with

 <arg name="venv" value="/path/to/venv/bin/python3" />
 <node> pkg="pkg" type="node.py" name="node" launch-prefix = "$(arg venv)" />

so if you migrate the venv, you just have to adapt the path to the interpreter in one place (i.e. the launch file).

As for the

ModuleNotFoundError: No module named "rospkg"

you should be able to solve by simply activating your virtual environment and installing rospkg into it with pip install rospkg.

edit flag offensive delete link more

Question Tools

2 followers

Stats

Asked: 2023-03-02 14:06:28 -0600

Seen: 4,906 times

Last updated: Mar 03 '23