Creating and using Python Virtual Environments

In a lot of my courses I encourage students to use python virtual environments. Virtual environments are a great way of making sure that you have the correct version of packages installed. This is very short cheat sheet on how to set them up. I will assume that we are using python 3. Luckily python 3 has virtual environments set up. It is all in the documentation, but then sometimes people are too lazy to google, or do not know what to google for.

To create a virtual environment in the current directory do the following

python3 -m venv env

If you look in the directory you’ll see a sub-directory env this contains all files that drive the virtual environment. In particular there is a sub-directory env/bin/

Justins-MacBook-Air-2:Example justin$ ls env/bin/ 
Activate.ps1		easy_install		pip3.9
activate		easy_install-3.9	python
activate.csh		pip			python3
activate.fish		pip3			python3.9

The most important file is the activate script. To start your virtual environment you simply do

 source ./env/bin/activate

This executes the activate script. Notice that you prompt has changed to (env)

You are now free to install what ever packages want. For exampe

pip3 install panda
pip3 install numpy

Once you have done all your python goodness you should leave your virtual environment.

(env) Justins-MacBook-Air-2:Example justin$ deactivate 
Justin Pearson
Justin Pearson
Docent in Computing Science

Lecturer and researcher at Uppsala University.