Rosanswers logo

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?

Originally posted by zrahman on ROS Answers with karma: 25 on 2023-03-02

Post score: 0


1 Answer 1


Rosanswers logo


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.

Originally posted by bluegiraffe-sc with karma: 221 on 2023-03-03

This answer was ACCEPTED on the original site

Post score: 2


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.