Managing Isolated Python Dependencies with venv
For developers working on multiple Python projects requiring conflicting library versions, venv provides a solution for dependency isolation. This standard library module allows the creation of self-contained environments, each with its own independent set of installed packages, preventing conflicts between projects.
Creating a Virtual Environment
First, navigate to your project directory using a terminal. The following command creates a new environment:
python -m venv environment_name
For instance, executing this with in a project folder named project_a:
python -m venv project_a_env
A new directory named project_a_env will appear. This folder contains a complete, isolated Python installation and a dedciated package management directory (site-packages).
Activating the Environment
Activation methods differ between operating systems.
Windows Run the activation script from the command line:
project_a_env\Scripts\activate
macOS / Linux
Use the source command to activate:
source project_a_env/bin/activate
Upon successful activasion, the terminal prompt will be prefixed with the environment name, e.g., (project_a_env). Any subsequent pip install commands will install packages only into this isolated environment.
Deactivating the Environment
To leave the virtual environment and return to the system's global Python context, execute:
deactivate
The environment prefix will disappear from the prompt, confirming the deactivation.