Python Virtual Env

Python Virtual Environments

Python applications will often use packages and modules that don’t come as part of the standard library. Applications will sometimes need a specific version of a library.

This means it may not be possible for one Python installation to meet the requirements of every application. If application A needs version 1.0 of a particular module but application B needs version 2.0, then the requirements are in conflict.

The solution for this problem is to create a virtual environment, a self-contained directory tree that contains a Python installation for a particular version of Python, plus a number of additional packages.


1. Creating a Virtual Environment

The module used to create and manage virtual environments is called venv.

To create a virtual environment, decide upon a directory where you want to place it, open your terminal, and run the venv module as a script with the directory path:

python -m venv tutorial-env

This will create the tutorial-env directory if it doesn’t exist, and also create directories inside it containing a copy of the Python interpreter and various standard library files.


2. Activating a Virtual Environment

Once you’ve created a virtual environment, you may activate it.

On Windows, run:

tutorial-env\Scripts\activate.bat

On Unix or MacOS, run:

source tutorial-env/bin/activate

Activating the virtual environment will change your shell’s prompt to show what virtual environment you’re using, and modify the environment so that running python will get you that particular version and installation.


3. Deactivating

When you are done working in the virtual environment, you can deactivate it and return to your global Python environment by simply typing:

deactivate

Best Practice: Always use a virtual environment when working on Python projects. It prevents your global package list from becoming cluttered and prevents version conflicts between different projects!