Install and enable virtualenv using Python 3
Prerequisite
- Python 3
- Pip :
- Windows : By default, pip is installed when you install python.
- Linux :
sudo apt-get install python-3-pip
Utilisation
- Install the package
virtualenv
.
# Windows
pip install virtualenv
# Linux
python -m pip install virtualenv
- Navigate to the project planned for a virtual environment.
- Create the virtual environment.
# Windows / Linux
python -m virtualenv venv
venv
being the name of the configuration folder.
- Activate the virtual environment.
# Windows
venv/Scripts/activate
# Linux
. venv/Scripts/activate
From this moment, all the packages will be in the virtual environment.
- Install the necessary packages.
# Windows
pip install package_name
# Linux
python -m pip install package_name
- If you have an installation error,
upgrade
pip in the virtual environment.
python -m pip install --upgrade pip
- Check that the package is installed correctly.
# Windows
pip list
# Linux
python -m pip list
You should see the packages you installed displayed.
It is normal that the packages that you installed outside of the virtual environment do not appear in the list of the virtual environment.
- You can use your project normally.
Exporting the project
Create the requirements.txt
file.
# Windows
pip freeze > requirements.txt
# Linux
python -m pip freeze > requirements.txt
This file will contain all the packages necessary for this project as well as the versions.
Retrieving the project from a virtual environment
- Retrieve the desired project.
- Activate the virtual environment.
# Windows
venv/Scripts/activate
# Linux
. venv/Scripts/activate
- Use the project normally afterwards.
Recovering the project from a normal environment
- Retrieve the desired project.
- Install the
virtualenv
package.
# Windows
pip install virtualenv
# Linux
python -m pip install virtualenv
You won't need to create the virtual environment, unless the environment configuration folder exists via a
.gitignore
.In this case, issue the following command.
# Windows / Linux python -m virtualenv venv
- Activate the virtual environment.
# Windows
venv/Script/activate
# Linux
. venv/Script/activate
If, in step 2, you needed to create the virtual environment, you will need to install the necessary packages.
# Windows pip install -r requirements.txt # Linux python -m pip install -r requirements.txt
You can then use the project normally.
Exit the virtual environment
To exit the virtual environment, execute the command.
deactivate
Cover photo by Lucas Benjamin