Skip to content

Instantly share code, notes, and snippets.

@mccutchen
Last active January 30, 2025 14:48
Show Gist options
  • Save mccutchen/e9c0ba406d4b89147b97c2329d65d740 to your computer and use it in GitHub Desktop.
Save mccutchen/e9c0ba406d4b89147b97c2329d65d740 to your computer and use it in GitHub Desktop.
Example direnv .envrc for Python projects that manages a local virtualenv that updates automatically when requirements.txt changes
#!/bin/bash
set -euo pipefail
VIRTUAL_ENV=".venv"
REQUIREMENTS_HASH_FILE="$VIRTUAL_ENV/requirements.shasum"
REQUIREMENTS_HASH_FUNC="shasum"
REQUIREMENTS_HASH_VAL=$($REQUIREMENTS_HASH_FUNC requirements.txt | cut -d ' ' -f 1)
function reset_venv() {
if ! has uv; then
echo 'error: `uv` command not found. install with `brew install uv`'
exit 1
fi
rm -rf "$VIRTUAL_ENV"
uv venv
uv pip install -r requirements.txt
printf '%s' "$REQUIREMENTS_HASH_VAL" >"$REQUIREMENTS_HASH_FILE"
}
if [ ! -f "$REQUIREMENTS_HASH_FILE" ]; then
echo "setting up new python virtualenv in $VIRTUAL_ENV ..."
reset_venv
elif [ "$(cat $REQUIREMENTS_HASH_FILE)" != "$REQUIREMENTS_HASH_VAL" ]; then
echo "python requirements changed, rebuilding virtualenv in $VIRTUAL_ENV ..."
echo "(found hash $(cat $REQUIREMENTS_HASH_FILE), want hash $REQUIREMENTS_HASH_VAL)"
reset_venv
fi
PATH_add "$VIRTUAL_ENV/bin"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment