Created
September 25, 2017 09:21
-
-
Save tjumyk/09d3d55af4699e7407e55d583835af59 to your computer and use it in GitHub Desktop.
Python virtual environment manipulation functions for BASH
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# follow other existing lines | |
# manipulation of virtual environments | |
venv() | |
{ | |
local venv_home | |
if [ -z $1 ]; then | |
if [ -d ".venv" ]; then | |
if [ -L ".venv" ]; then | |
venv_home=$(readlink -f ".venv") | |
else | |
venv_home='.venv' | |
fi | |
else | |
echo "No venv was found in the current folder and no specific venv name was given" | |
return 1 | |
fi | |
else | |
venv_home="$HOME/.venvs/$1" | |
fi | |
source "$venv_home/bin/activate" | |
} | |
mkvenv() | |
{ | |
local py | |
py=$1 | |
if [ -z py ]; then | |
py=python3 | |
fi | |
if [ -f "requirements.txt" ]; then | |
local proj venv_home | |
proj=$(basename "$PWD") | |
venv_home="$HOME/.venvs/$proj" | |
if [ ! -d $venv_home ]; then | |
echo "Setting up a new virtual environment for project \"$proj\"..." | |
virtualenv -p "$py" "$venv_home" && ln -s "$venv_home" ".venv" | |
if [ $? != 0 ]; then | |
return 1 | |
fi | |
source "$venv_home/bin/activate" | |
pip install -U pip && pip install -U -r requirements.txt | |
deactivate | |
else | |
echo "A virtual environment for \"$proj\" is already set up at \"$venv_home\"" | |
return 1 | |
fi | |
else | |
echo "No requirements.txt found" | |
return 2 | |
fi | |
} | |
rmvenv() | |
{ | |
local venv_home | |
if [ -z $1 ]; then | |
if [ -d ".venv" ]; then | |
if [ -L ".venv" ]; then | |
venv_home=$(readlink -f ".venv") | |
rm ".venv" | |
else | |
venv_home=".venv" | |
fi | |
else | |
echo "No venv was found in the current folder and no specific venv name was given" | |
return 1 | |
fi | |
else | |
venv_home="$HOME/.venvs/$1" | |
fi | |
rm -r "$venv_home" | |
} | |
_list_venvs() | |
{ | |
local cur opts | |
COMPREPLY=() | |
if [[ ${COMP_CWORD} == 1 ]]; then | |
cur="${COMP_WORDS[COMP_CWORD]}" | |
opts=$(ls "$HOME/.venvs/") | |
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) ) | |
fi | |
} | |
complete -F _list_venvs venv | |
complete -F _list_venvs rmvenv |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment