Python virtual Environments

TL;DR

Essentially this allows you to create an isolated environment for each python application you create. Meaning each application can use difference libraries or even different version of the same library without interfering with each other.

What is VENV

A python virtual environment or VENV is a lightweight self-contained directory tree that contains a Python installation for a particular version of python, plus a number of additional packages.

Each python application you create can use its own virtual environment. This resolves the problem of conflicting requirements between applications.

The venv module is used to create the virtual environment.

How to install venv

pip install virtualenv
Enter fullscreen mode Exit fullscreen mode

Create a virtual environment

python -m venv /path/to/new/virtual/environment
Enter fullscreen mode Exit fullscreen mode

Use a virtual environment

For Linux or Mac OS your new venv can be activated by using this command:

source /path/to/new/virtual/environment/bin/activate
Enter fullscreen mode Exit fullscreen mode

For windows:

\path\to\new\virtual\environment\Scripts\activate.bat
Enter fullscreen mode Exit fullscreen mode

Once activated you should be able to install libraries via pip like you normally would but it will now be installed into you virtual environment

Exiting your virtual environment

Just like with activation venv provides a handy deactivate script. For Linux or Mac OS your new venv can be deactivated by using this command:

deactivate
Enter fullscreen mode Exit fullscreen mode

or if that does not work:

source /path/to/new/virtual/environment/bin/deactivate
Enter fullscreen mode Exit fullscreen mode

For windows:

\path\to\new\virtual\environment\Scripts\deactivate.bat
Enter fullscreen mode

Why should you use a virtual environment

When you run Python and its libraries from the system, you are restricted to a specific Python version chosen by your operating system. This approach can lead to version conflicts among the libraries when running multiple Python applications on the same installation. Additionally, modifying the system Python may disrupt other OS features that rely on it. Using a virtual environment isolates each application thus solving this problem.


Discover more from Coursity

Subscribe to get the latest posts sent to your email.

Leave a Comment

Your email address will not be published. Required fields are marked *

Discover more from Coursity

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top