Use the virtual environments with Python

Jérôme Dx - Oct 23 '23 - - Dev Community

If you work on several Python projects, you will quickly need to have different versions of your packages, depending on the current project.

Virtual environments are designed for this, they allow to isolate the libraries between your projects. There are different libraries you can use, I will show you Venv and Pipenv.

Venv

Venv is the built-in module for creating virtual environments in Python 3.

First let’s create a simple script, that needs two packages :

import requests
import numpy

if __name__ == "__main__":

    # Use the requests library
    request = requests.get("https://httpbin.org/get")
    print("Response : ")
    print(request.text)

    # Use the numpy library
    print("Numpy version : " + numpy.__version__)
Enter fullscreen mode Exit fullscreen mode

Create a file "requirements.txt" :

requests>=2.25.1
numpy>=1.19.5
Enter fullscreen mode Exit fullscreen mode

Then you can use this commands (don’t forget to add "venv" in your .gitignore file) :

# Create the venv
python -m venv venv

# Activate the venv
source venv/bin/activate

# Install the requirements
pip install -r requirements.txt

# Deactivate the venv
deactivate
Enter fullscreen mode Exit fullscreen mode

Pipenv

Pipenv is a higher-level tool that combines package management and virtual environment management, using Pipfile.

First, install Pipenv :

brew install pipenv
Enter fullscreen mode Exit fullscreen mode

Create a file "Pipfile", made for the script we are working on :
(you can also generate it with the "pipenv install" command)

[[source]]
url = "https://pypi.org/simple"
verify_ssl = true
name = "pypi"

[packages]
requests = ">=2.25.1"
numpy = ">=1.19.5"

[dev-packages]
Enter fullscreen mode Exit fullscreen mode

Then you can use this commands :

# Inititiate the Pipfile (or install all packages)
pipenv install

# You can install packages (or edit Pipfile directly)
pipenv install requests
pipenv install numpy

# Activate/Deactivate the venv
pipenv shell  # and Ctrl + D to quit

# Alternatively, run a command inside the virtualenv
pipenv run python

# Uninstall the venv
pipenv --rm
Enter fullscreen mode Exit fullscreen mode

Both are good solutions for virtual environments, venv is built-in and lighter to write, also pipenv is faster and allows more possibilities, so choose the good one for the good context.

You can also be interested by Pyenv, a complementary tool made to manage different versions of Python on your computer.

. . . . . . . . . . . . . . . . . . . .
Terabox Video Player