Table of Contents

go back to main page

Virtual Environments in Python

Installation example

First, open a terminal and check if pip is installed by typing :

pip -V

If the command does exist, it will give the version number of pip, if the pip command is not installed you can get it by typing :

sudo apt install python-pip

or:

sudo apt install python3-pip

The virtual environment is installed at user level (no sudo required) with pip:

pip install --user virtualenv

If after a while virtualenv command is not working (No module named 'virtualenv.main') you can try changing version; e.g. :

pip install --user virtualenv==20.0.23

To get larger access to virtualenv commands, you can it in the $PATH variable by adding these 2 lines at the end of the .bashrc file :

# add virtualenv command path :
PATH=$HOME/.local/bin:$PATH

Then you can create the virtualenvs everywhere in your computer, but it may be wise to put them in a folder (e.g. “MyVenvs”) :

cd
mkdir MyEnvs
cd MyEnvs

Then we can create and activate our first virtualenv called venv-opencv-27 to, for example, make some image processing with numpy and OpenCv in Python 2.7 :

virtualenv -p /usr/bin/python2.7 venv-opencv-27
source venv-opencv-27/bin/activate

If everything went well, you should see the name of the virtualenv (venv-opencv-27) into parenthesis at the beginning of the prompt. We can now install the packages we need in the virtualenv and check installation went fine by typing the version of numpy and OpenCV ::

pip install numpy
pip install opencv-contrib-python
pip install Pillow
python -c "import numpy as np;print np.__version__"
python -c "import cv2;print cv2.__version__

Then your can work on your project folder. The project folder folder can be everywhere on your computer. As long as you have (venv-opencv-27) at the beginning of the prompt you are in the virtualenv. To quit the virtualenv, just type :

deactivate

To open back the virtual, you just need to activate it again :

source $HOME/MyEnvs/venv-opencv-27/bin/activate

Manual Install with setup.py

Open the virtualenv (ex) :

source $HOME/MyEnvs/venv-opencv-27/bin/activate

and check that the default python running is the one of the virtualenv :

which python

should give the path of the python interpreter in the virtualenv, in our example it will be :

/home/newubu/MyEnvs/venv-opencv-27/bin/python

Then you can use, the classical command for manual install of a python package :

python setup.py build
python setup.py install

Manual import of virtualenv packages

In some cases, for example when using virtualenvs in Coppeliasim python scripts, the virtualenv modules must be manually added to the import path; Example with pyproj

import sys
# replace /path/to/myenv with appropriate path to virtual environment
sys.path.append('/path/to/myenv/lib/pythonX.X/site-packages')