Virtual environments let you manage dependencies for various pieces of software without having to install conflicting dependencies system-wide. This makes developing against different versions of the same library easier, and makes for a cleaner system install as well.

Anaconda/Miniconda

Creating an environment

Miniconda and Anaconda are the same Python distribution, and differ in what the base install contains. Miniconda is just the framework for conda, while Anaconda distributions come with a variety of Python modules ready to install. This section will use the Miniconda installer.

To use the Miniconda installer, first download the installer from the conda.io website. Execute it with:

# You could also download Python 2, if you were for some reason possessed
# with the desire to embrace a technology that expired January 1, 2020
# (https://pythonclock.org/).
sudo ./Miniconda3-latest-Linux-x86_64.sh

To create an environment, use the conda command:

conda create --name myenv python=3.7

From an environment file

To create an environment from a YAML file specification in conda_env.yml:

conda env create --file conda_env.yml

Updating and maintaining an environment

To install a new package, use conda install:

conda install -y numpy

To save the environment state, use conda list:

conda list --export > requirements.txt

Activating an environment

Go to the directory where you created the environment, and use conda activate:

conda activate myenv

Exiting an environment

Exit with conda deactivate:

conda deactivate

Removing an environment

Use conda env remove:

conda env remove --name myenv

Pipenv

You can install the pipenv package with sudo -H pip3 install pipenv.

Creating a virtual environment

Launch a shell with:

# Note: this will remove an existing virtual environment and give you a clean slate
pipenv --three shell

Updating and maintaining an environment

You will see the output from the creation, and then a shell will be spawned in the environment. To install a package, just use pip3 (no sudo required):

# Install the numpy package
pip3 install numpy

To save your environment configuration, use pip3 to "freeze" the state:

# Without redirection, this will print to the screen
pip3 freeze > requirements.txt

Activating an environment

Go to the directory where you created the environment, and run pipenv shell.

Exiting an environment

Exit as you normall would, with exit or Ctrl-D (end of input).

Removing an environment

To remove an environment, execute pipenv --rm in the directory where you created the environment.

References