Building Python virtual environments using Anaconda

Here I'll walk through all the steps needed to get python running in Jupyter notebooks from scratch. We'll be setting up a virtual environment, which is good practice as it ensures work on each project does not cause conflicts in your python build for other projects.

Step 1. Installing Anaconda.

Find a link to the command line installer
e.g. https://repo.anaconda.com/archive/Anaconda3-2020.07-MacOSX-x86_64.sh

In terminal enter:
wget link_to_installer
then:
bash installer.sh

Let it initialize conda for you when it asks.
Check .bashrc to see if this puts in the path correctly.
If using a different shell (e.g. tcsh on atmos computers check .tcshrc)
For zsh on Mac use: bash -c "conda init zsh"

Verify conda installation using:
conda info

Step 2. Create a new virtual environment.

To see available environments:
conda env list

To create a new environment use one of these:
conda create -n myenv (change myenv to name)
conda create -n myenv python=3.6 (for a specific python version)
conda create --clone myenv --name myenv2

Step 3. Activating an environment

Environments must be activated to update or use them:
conda activate myenv

To stop working with an environment:
conda deactivate

To remove an environment entirely:
conda env remove -n myenv

Step 4. Set up environment to work with Jupyter notebooks.

Install ipykernel package:
conda install ipykernel

Then add the environment (i.e. kernel) to Jupyter using:
python -m ipykernel install --user --name=myenv

To remove an environment from Jupyter use:
jupyter kernelspec list
jupyter kernelspec uninstall myenv

To check that the kernel is set up for jupyter notebooks correctly:
Make sure you did the adding of the kernel to jupyter when environment was activated.
jupyter kernelspec list will point you to a directory with kernel.json.
"argv" in that json should point to a python folder *within your virtual environment*.
If not something went wrong. Remove kernel from jupyter and try to re-add.

Step 5. Adding, updating and removing packages.

First activate your environment

To view all packages in current environment:
conda list

To install a package:
conda install packagename
or:
pip install packagename

To install a specific package version:
conda install packagename=1.11
or for stricter constraints:
conda install packagename==1.11

To specify conda forge:
conda install --channel conda-forge packagename

To update a package:
conda update packagename

To remove a package:
conda remove --name myenv packagename

Misc tips.

To check python version:
python --version

To check python path:
which -a python (1st entry is path used)

To see history of environment:
conda list --revisions

To revert back to an old version of environment:
conda install --revision 2