Virtualenv (notes)

last update: 2019-03-03

Python's virtualenv is a tool to create isolated Python environments. It allows you to quickly and easily set up a Python project. You can install a set of libraries in designated versions required by the project. These libraries do not have to be present on your operating system level in the same version. They don't even have to be installed at all. In an active virtualenv, only the libraries that were installed there are available. You cannot access the libraries installed in the operating system's python paths. This has multiple advantages:

Creating a virtualenv is a one-liner in your OS shell. As a best practice, always set the desired version of the Python interpreter during the creation. Thereafter, the virtual environment can be activated or de-activated with a single command as well.

virtualenv --python python3.6 env_name  # short: virtualenv -p python3.6 env_name
source env_name/bin/activate  # short . env_name/bin/activate
# check changed bash prompt after command
# installing packages only during the first time
pip install -U pip  # update pip; pip3 is used automatically in the environment
pip install flask flask-restful
pip install django==1.9.1  # pin django to desired version
which django-admin  # test django version
# initialize repository (alternatively you can include your venv)
git init
pip freeze > requirements.txt  # store environment setup information
# pip install -r requirements.txt  # install requirements if needed
# take care of the remaining VCS stuff by yourself
# ...