Skip to content

Instantly share code, notes, and snippets.

@zlondrej
Created March 5, 2024 15:47
Show Gist options
  • Save zlondrej/8e3ea03efa8eae9d816c6cc29e07bc04 to your computer and use it in GitHub Desktop.
Save zlondrej/8e3ea03efa8eae9d816c6cc29e07bc04 to your computer and use it in GitHub Desktop.
Python virtual environment wrapper
#!/usr/bin/env bash
# This script is a wrapper for creating and managing Python virtual environments.
# Usage:
# py-venv-wrapper.sh <command>
# Run the script in the directory containing the requirements.txt file.
# The script will create a virtual environment in the ".venv" directory
# and execute the command within the virtual environment.
# The following environment variables can be set to customize the behavior of the script:
# - REQUIREMENTS: The path to the requirements.txt file. Default: "$PWD/requirements.txt"
# - VENV_DIR: The path to the virtual environment directory. Default: "$PWD/.venv"
set -e
REQUIREMENTS="${REQUIREMENTS:-"${PWD}/requirements.txt"}"
VENV_DIR="${VENV_DIR:-"${PWD}/.venv"}"
if [[ ! -f "${REQUIREMENTS}" ]]; then
echo "ERROR: '${REQUIREMENTS}' not found." >&2
exit 1
fi
UPDATE_VENV="false"
# Check if the requirements file has changed
if [[ ( ! -f "${VENV_DIR}/requirements.sha1" ) ]] || ! sha1sum --status --check "${VENV_DIR}/requirements.sha1"; then
UPDATE_VENV="true"
fi
cleanup()
{
rm -rf "${VENV_DIR}"
echo "Cleaning up virtual environment." >&2
}
# If the virtual environment does not exist or the requirements file has changed,
# tear down the existing virtual environment and recreate it from scratch.
if [[ ! -d "${VENV_DIR}" || "${UPDATE_VENV}" == "true" ]]; then
(
trap cleanup ERR
echo "Creating/updating virtual environment."
rm -rf "${VENV_DIR}"
python3 -m venv --copies "${VENV_DIR}"
source "${VENV_DIR}/bin/activate"
pip3 install -r "${REQUIREMENTS}"
deactivate
sha1sum "${REQUIREMENTS}" > "${VENV_DIR}/requirements.sha1"
echo "Virtual environment created."
echo
) >&2
fi
(
# Activate the virtual environment
source "${VENV_DIR}/bin/activate"
# Execute the command
"$@"
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment