Python Virtual Environments

Create python environments for specific app/tooling needs. Used commonly to prevent scripts/apps from munging systemwide Python installation.

Creating Environment

See python pip and virtual environment for reference material.

Install pip and virtual environment packages.
apt install python3-pip python3-venv
Create a virtual environment.
test -d {ENV DIR} || python3 -m venv {ENV DIR}

Note

All other virtual environment commands are deprecated now.

Update ~/.bashrc to require virtual environments for pip.
export PIP_REQUIRE_VIRTUALENV=true

Using Virtual Environments

Activate virtual environment for use.
. {ENV DIR}/bin/activate
Deactivate the environment to return the normal system environment.
deactivate

Export/Import Environments

Environments may be exported for easy configuration with services and scripts.

Export current environment.
. {ENV DIR}/bin/activate
python3 -m pip freeze > {ENV CONFIG}
Install a specific environment.
. {ENV DIR}/bin/activate
python3 -m pip install --requirement {ENV CONFIG}

Updating Environments

Update environment and re-export.

Important

requirements.txt ({ENV CONFIG}) must be updated to use >= before attempting to update.

Update environment.
. {ENV DIR}/bin/activate
python3 -m pip install --requirement {ENV CONFIG} --upgrade
python3 -m pip freeze > {ENV CONFIG}

References