Skip to content

Python Virtual Environment

To run or develop python applications with different needs for packages a virtual environment can be created.

Requirements

Linux packages: * python3 * python3-venv * python3-pip

Install the system packages.

apt install python3 python3-venv

The package python3-pip is not needed since it is installed automatically in the virtual environment directory.

Create Environment Directory

In the root of the project directory a .venv is created using this command.

python3 -m venv .venv
This creates some scripts with absolute paths to the location of the .venv directory. So moving them needs some editing or just recreate them.

Install Required Packages

To make the pip command install the packages in the virtual directory (.venv) an activation script should be called first before using pip command.

source .venv/bin/acivate  # Activates needed environment variables.
pip install package-name package-name-2 # Install some packages.
pip install -r package-list.txt  # Install packages from a file.
deactivate # Deactivate which removes the environment variables.  
A package list could look like this.

# Some comment is allowed this way. 
Babel==0.9.5 # translation
CherryPy==3.2.0 # web server
Creoleparser==0.7.1 # wiki formatting
Genshi==0.5.1 # templating

Tricking Executable Python Script

To trick the Python executable script in using the virtual environment the bash parts are double quoted.

#!/bin/env bash

# Trick python to ignore this line by quoting.
"exec" "$(dirname ${BASH_SOURCE[0]})/venv/bin/python" "$0" "$@"

# Python code behid this. 

Easy Shell Script

A shell script venv.sh for doing it all could like this.

#!/usr/bin/env bash

# Target directory 
venv_dir=".venv"

echo "Creating environment directory '${venv_dir}'"

python3 -m venv "${venv_dir}"

source "${venv_dir}/bin/activate"

if [[ -f required-packages.txt ]]; then
  pip install -r required-packages.txt
fi

pip list
deactivate