Python Virtual Environments

By

Learn how to use Python virtual environments to isolate module versions per project, creating one with python -m venv and activating it with source activate.

~~~

A virtual environment gives each Python project its own private set of installed packages, isolated from the rest of the system. You create one with python -m venv, activate it, and from then on pip installs into the project, not globally.

It’s common to have multiple Python applications running on your system.

When applications require the same module, at some point you will reach a tricky situation where an app needs a version of a module, and another app a different version of that same module.

To solve this, you use virtual environments.

We’ll use venv, which is built into Python. Other tools work similarly, like pipenv.

Create and activate the environment

Create a virtual environment using

python -m venv .venv

in the folder where you want to start the project, or where you already have an existing project.

This creates a .venv folder containing a copy of the Python interpreter and its own pip.

Then run

source .venv/bin/activate

Use source .venv/bin/activate.fish on the Fish shell. On Windows, run .venv\Scripts\activate instead.

Executing the program will activate the Python virtual environment. Depending on your configuration you might also see your terminal prompt change.

Mine changed from

➜ folder

to

(.venv) ➜ folder

Now running pip will use this virtual environment instead of the global environment.

Installing packages

With the environment active, install packages as usual:

pip install requests

The package lands inside .venv, invisible to other projects. You can verify which Python you’re using with which python: it should point inside the .venv folder.

To let others recreate the same environment, freeze the installed packages into a file:

pip freeze > requirements.txt

Anyone cloning the project creates their own environment and runs pip install -r requirements.txt to get the exact same versions.

When you’re done working, run deactivate to go back to the global environment.

Two things to remember. First, add .venv to your .gitignore. The folder can be huge, and it’s machine-specific: it can always be recreated from requirements.txt.

Second, the classic mistake: opening a new terminal, forgetting to activate, and running pip install. The package goes into the global environment, and your app inside the virtual environment keeps failing with ModuleNotFoundError. If a package you just installed seems missing, check your prompt for the (.venv) prefix and activate the environment first.

Tagged: Python · All topics
~~~

Related posts about python: