Python Virtual Environment

From NovaOrdis Knowledge Base
Jump to navigation Jump to search

External

Internal

Overview

A virtual environment is a mechanism to isolate a set of installed dependencies. Virtual environments can be managed with tools like virtualenv, venv, etc. and reside in directories called venv or .venv within the project's root. It is a good practice to avoid storing the content of venv or equivalent in source control. The content is populated locally on the developers' machines.

Manual Creation

A virtual environment can be created manually as follows:

python3 -m venv <virtual-env-dir-name>

Example:

python3 -m venv venv

After the virtual environment is created, it is usually a good idea to upgrade pip:

venv/bin/python3 -m pip install --upgrade pip

The dependencies can then be installed with:

venv/bin/pip install -r requirements.txt

Upgrade pip for an Already Initialized Virtual Environment

To upgrade pip within an already initialized virtual environment:

venv/bin/python3 -m pip install --upgrade pip

Virtual Environments and Dependencies

TO TEST THAT: The dependencies installed in a virtual environment are used automatically if the interpreter is ./venv/bin/python.

Also see pip and requirements.txt.

Activated Virtual Environment Shell

An "activated" virtual environment means making the virtual environment Python interpreter the default interpreter for the shell session.

To activate the virtual environment:

source .venv/bin/activate

To "deactivate", run:

deactivate

or simply exit the shell.

Bash Wrapper that Bootstraps a Virtual Environment

function init_venv() {
  [[ -d $(dirname $)/venv ]] && return 0
  info "initializing venv ..."
  python3 --version 1>/dev/null 2>&1 || fail "python3 not in PATH"
  python3 -m venv "$(dirname $)/venv"
}