Skip to content

Instantly share code, notes, and snippets.

@teroyks
Last active January 20, 2022 10:43
Show Gist options
  • Save teroyks/ac31074ef973107e2717c0349a5f4c7b to your computer and use it in GitHub Desktop.
Save teroyks/ac31074ef973107e2717c0349a5f4c7b to your computer and use it in GitHub Desktop.
Activate venv somewhere in the directory tree

Find and Activate venv

Tries to find and activate a virtual environment either in the current directory or the closest one in the hierarchy.

Example:

  • in /foo/bar/baz
  • first, checks if /foo/bar/baz/venv/bin/activate is found (and uses that if it is)
  • next, tries /foo/bar/venv/bin/activate
  • after that, /foo/venv/bin/activate
  • if that was not found, outputs an error message

Note: you need to run the script with source (or .), i.e. source activate-env.sh for the environment activation to work.

# find and activate nearest venv in the directory tree
DIR=$(pwd)
while [ ! -e "$DIR/venv/bin/activate" ]; do
DIR=$(dirname "$DIR")
if [[ "$DIR" = "/" ]]; then
echo "'activate' script not found" >&2
return 1
fi
done
source "$DIR/venv/bin/activate"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment