Python virtual environments

Python virtual environments are useful for managing dependencies between different projects. Below are some tips and tricks for virtualenv (venv) and Conda which are two of the most widely used virtual environments.

Outline

Conda

Installation:

Install Anaconda or Miniconda (lightweight version) by following the official guide.

Setup a new environment

conda create --name <env_name> python=<version_number>
    # <version_number>: 2.x or 3.x
conda activate <env_name> # Activate env
conda deactivate # Deactivate env

Export an environment:

conda env export -f environment.yml --no-build

--no-build flag is required when exporting conda environment to different machine/OS.

virtualenv

Installation:

# Install as an apt package
sudo apt install virtualenv

or

# Install (locally) as a python package
pip install --user virtualenv

Setup a new environment:

virtualenv -p /usr/bin/python* <env_name> # Create env
    # python*: python / python2 / python3
source <env_name>/bin/activate # Activate env
deactivate # Deactivate env

Using with Jupyter notebook:

virtualenv -p <env_name>/bin/activate # Activate env
pip install ipykernel
python -m ipykernel install --user --name <env_name> \
    --disp-name "env_name_to_appear_in_jupyter"