Suppose you have multiple projects and all rely on a single package but each project depends on a specific version of that package. So, if you upgrade the package globally it could break all other projects/software that depend on the package's previous version. Due to this reason, you would not dare to do that, instead you would like each of the projects to have an isolated environment together with their package dependencies and the specific versions they need. This is the point where the use of virtual environments, virtualenv, comes in.
This short tutorial shows how to set and use separate Python environments.
- Make sure you have pip installed, otherwise install it
- sudo apt-get install python-pip #Python 2
- sudo apt-get install python3-pip #Python 3
- #Or upgrade pip
- pip install --upgrade pip
- #Install virtualenv
- pip install virtualenv
- #Make directory to keep all separate environments in one place
- mkdir Environments
- #Make the first virtualenv
- virtualenv project_venv1
- #Activate the virtualenv
- source project_venv1/bin/activate
- #Or
- . project_venv1/bin/activate #Try which pip or which python to see if they are inside the newly created environment
- #Install packages inside the new virtualenv, project_venv1, here we install numpy and scipy
- pip install numpy
- pip install scipy
- #Type "pip list" to see which packages were installed in this new environment
- pip list
- #Export the local dependencies in the virtualenv to a file requirements.txt
- pip freeze --local > requirements.txt
- #Check that all the dependencies have been moved to requirements.txt
- ls
- #List dependencies in the requirements.txt file
- cat requirements.txt
- #Get out of virtualenv
- deactivate #Type which python to confirm that the python listed is in the global environment
- #Delete the created virtualenv if you no longer need it
- rm -rf project_venv1/ #Note that the requirements.txt file is still availbale
- #You can specify a specific version of software you want for a particular virtual environment project. Suppose we want to use a global Python 2.7 inside the virtualenv project_venv2
- virtualenv -p /usr/bin/python2.7 project_venv2
- #Activate this new environment to use with Python 2.7
- source project_venv2/bin/activate
- #Check if the exported global Python 2.7 is currently in this new environment
- which python
- #Check which version of Python you are using inside the virtual environment, project_venv2
- python --version
- #Install the packages in the requirements.txt file to the current virtualenv, project_venv2
- pip install -r requirements.txt
- #Check if these packages are installed by typing
- pip list
- #Again, you can deactivate the virtualenv and switch to using global packages
- deactivate
Virtual environments are meant to be environments for separating packages, dependencies and the versions that you will use from project to project.