-
-
Save dbtek/fb2ddccb18f0cf63a654ea2cc94c8f19 to your computer and use it in GitHub Desktop.
# venv_wrapper, manage all virtual environments under ~/.venv/ | |
# Include following in .bashrc / .bash_profile / .zshrc | |
# See https://gist.github.com/dbtek/fb2ddccb18f0cf63a654ea2cc94c8f19 | |
# Usage | |
# $ mkvenv myvirtualenv # creates venv under ~/.venv/ | |
# $ venv myvirtualenv # activates venv | |
# $ deactivate # deactivates venv | |
# $ rmvenv myvirtualenv # removes venv | |
export VENV_HOME="$HOME/.venv" | |
[[ -d $VENV_HOME ]] || mkdir $VENV_HOME | |
lsvenv() { | |
ls -1 $VENV_HOME | |
} | |
venv() { | |
if [ $# -eq 0 ] | |
then | |
echo "Please provide venv name" | |
else | |
source "$VENV_HOME/$1/bin/activate" | |
fi | |
} | |
mkvenv() { | |
if [ $# -eq 0 ] | |
then | |
echo "Please provide venv name" | |
else | |
echo "Creating venv under $VENV_HOME/$1" | |
python3 -m venv $VENV_HOME/$1 | |
echo "Activating $1" | |
venv $1 | |
fi | |
} | |
rmvenv() { | |
if [ $# -eq 0 ] | |
then | |
echo "Please provide venv name" | |
else | |
rm -rf $VENV_HOME/$1 | |
fi | |
} | |
complete -C lsvenv venv | |
complete -C lsvenv rmvenv |
@maxwellmckinnon you are absolutely right. Any suggestions?
Updated gist with no argument checks. Thanks to maxwellmckinnon.
So glad I found this when I searched for "venv wrapper", works perfectly. Thanks!
Thanks for this! I found it handy to add an lsvenv
command as well to list the existing virtual environments under ~/.venv/
lsvenv() {
ls -1 $VENV_HOME
}
Thanks @zekefarwell. Added lsvenv
.
Useful gist 👍 . I added complete -W "`lsvenv`" venv
to the end of it so venv
can autocomplete with the tab key. It might help you out.
This is great! My system version is 3.10 which tends to break things, so I added a few lines so mkvenv
can optionally set the version. It's a bit fragile and basic, but it works for my purposes.
mkvenv() {
if [ $# -eq 0 ]
then
echo "Please provide venv name"
elif [ $# -eq 1 ]
then
python3 -m venv $VENV_HOME/$1
elif [ $# -eq 2 ]
then
python$2 -m venv $VENV_HOME/$1
fi
}
the ZSH equivalent for @leoschmitz 's one liner above is
compdef '_path_files -/ -W $VENV_HOME' venv
Autocompletion added for venv
and rmvenv
commands. Thanks @leoschmitz, @billyzs.
Auto activating newly created venv with mkvenv
is also added along with some informative messages.
This is great thanks. You might want to add protection against rmvenv with no argument given, so that someone doesn't blow away all their environments :)