Skip to content

Python

Introduction to Python Virtual Environments: venv and conda

Python virtual environments are essential for managing dependencies in Python projects. They allow you to create isolated environments for different projects, each with its own set of libraries and specific versions. This helps avoid conflicts, especially when working on multiple projects that require different library versions or dependencies.

Two popular tools for creating virtual environments are venv (built-in to Python) and conda (a package and environment manager from Anaconda).

Before getting started, remember to load the appropriate python module:

$ module purge
$ module load python3.12-anaconda/2024.06-1

venv - The Built-in Python Virtual Environment

Venv is a tool included with Python that allows you to create lightweight virtual environments.

Create a virtual environment in your project folder:

$ python -m venv myenv

Here, myenv is the name of the environment folder. You can replace it with any name.

Activate the virtual environment:

$ source myenv/bin/activate

Install packages as needed with pip, e.g.,:

$ pip install requests

Deactivate the environment when done:

$ deactivate

The venv tool is straightforward and efficient for basic Python projects. It’s lightweight, and it’s included by default with Python installations.


conda - An Environment and Package Manager

Conda is a powerful environment manager provided by the Anaconda distribution.

Create a conda environment with a specified Python version (optional):

$ conda create -n myenv python=3.8

Activate the environment:

$ conda activate myenv

Install packages using conda or pip, e.g.:

$ conda install numpy

Deactivate the environment:

$ conda deactivate