Skip to content

Instantly share code, notes, and snippets.

@thomasaarholt
Created November 6, 2022 15:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thomasaarholt/2f31184bf2aeba578822e545a482c103 to your computer and use it in GitHub Desktop.
Save thomasaarholt/2f31184bf2aeba578822e545a482c103 to your computer and use it in GitHub Desktop.
Bash function for creating virtual environments that are automatically (de)activated upon cd entry(exit).
venv () {
RED='\033[0;31m'
NC='\033[0m' # No Color
# create virtualenv
if [ ! -d .venv ] # if venv does not exist already
then
python -m venv .venv --system-site-packages
else
echo -e "${RED}.venv${NC} already exists!"
return 0
fi
# Tell direnv to activate it when entered
if [ ! -f .envrc ] # if file does not exist already
then
echo "source .venv/bin/activate" >> .envrc
else
echo -e "${RED}.envrc${NC} already exists. Manually place `source .venv/bin/activate` in the file"
fi
direnv allow
# create vscode directory, fail if already exists
if [ ! -f .vscode/settings.json ] # if file does not exist already
then
mkdir -p .vscode
echo '{
"python.terminal.activateEnvInCurrentTerminal": true,
"python.defaultInterpreterPath": ".venv/bin/python"
}
' >> .vscode/settings.json
else
echo -e "${RED}.vscode/settings.json${NC} already exists. Please manually place the following in it:
'python.terminal.activateEnvInCurrentTerminal': true,
'python.defaultInterpreterPath": ".venv/bin/python'
"
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment