Install and enable virtualenv using Python 3

May 22, 2021 MrAnyx 2 min de lecture

Prerequisite

  • Python 3
  • Pip :
    • Windows : By default, pip is installed when you install python.
    • Linux : sudo apt-get install python-3-pip

Utilisation

  1. Install the package virtualenv.
# Windows
pip install virtualenv

# Linux
python -m pip install virtualenv
  1. Navigate to the project planned for a virtual environment.
  2. Create the virtual environment.
# Windows / Linux
python -m virtualenv venv

venv being the name of the configuration folder.

  1. Activate the virtual environment.
# Windows
venv/Scripts/activate

# Linux
. venv/Scripts/activate

From this moment, all the packages will be in the virtual environment.

  1. Install the necessary packages.
# Windows
pip install package_name

# Linux
python -m pip install package_name
  1. If you have an installation error, upgrade pip in the virtual environment.
python -m pip install --upgrade pip
  1. 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.

  1. 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

  1. Retrieve the desired project.
  2. Activate the virtual environment.
# Windows
venv/Scripts/activate

# Linux
. venv/Scripts/activate
  1. Use the project normally afterwards.

Recovering the project from a normal environment

  1. Retrieve the desired project.
  2. 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
  1. 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


Cette œuvre est mise à disposition selon les termes de la licence Licence Creative Commons