Last active
December 15, 2024 08:56
-
-
Save dbtek/fb2ddccb18f0cf63a654ea2cc94c8f19 to your computer and use it in GitHub Desktop.
Python 3 venv wrapper. Manages all virtual environments under ~/.venv/ .
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
# venv_wrapper, manage all virtual environments under ~/.venv/ | |
# Include the 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 | |
# $ rmvenv env1 env2 # removes multiple venvs | |
# $ lsvenv # lists all venvs | |
export VENV_HOME="$HOME/.venv" | |
[[ -d $VENV_HOME ]] || mkdir -p $VENV_HOME | |
lsvenv() { | |
ls -1 "$VENV_HOME" | |
} | |
venv() { | |
if [ $# -eq 0 ]; then | |
echo "Please provide venv name" | |
elif [ -d "$VENV_HOME/$1" ]; then | |
source "$VENV_HOME/$1/bin/activate" | |
else | |
echo "Virtual environment '$1' does not exist." | |
fi | |
} | |
mkvenv() { | |
if [ $# -eq 0 ]; then | |
echo "Please provide venv name" | |
else | |
if [ -d "$VENV_HOME/$1" ]; then | |
echo "Virtual environment '$1' already exists." | |
else | |
echo "Creating venv under $VENV_HOME/$1" | |
python3 -m venv "$VENV_HOME/$1" | |
echo "Activating $1" | |
venv "$1" | |
fi | |
fi | |
} | |
rmvenv() { | |
if [ $# -eq 0 ]; then | |
echo "Please provide one or more venv names" | |
else | |
current_venv=$(basename "${VIRTUAL_ENV:-}") | |
for env in "$@"; do | |
if [ -d "$VENV_HOME/$env" ]; then | |
if [ "$env" = "$current_venv" ]; then | |
deactivate | |
echo "Deactivated current virtual environment '$env'." | |
fi | |
rm -rf "$VENV_HOME/$env" | |
echo "Virtual environment '$env' removed." | |
else | |
echo "Virtual environment '$env' does not exist." | |
fi | |
done | |
fi | |
} | |
complete -C lsvenv venv | |
complete -C lsvenv rmvenv |
I created the venvwrapper package on Pypi which provides an improved version of this script.
At this point, the venvwrapper package supports bash and zsh.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Changes and Improvements:
Error Checking:
mkdir -p $VENV_HOME
to ensure the directory structure is created if it doesn't exist.User Feedback:
Multiple Environment Deletion:
rmvenv
function to accept multiple arguments, allowing deletion of multiple virtual environments in a single command.rmvenv
to iterate over all provided virtual environment names, checking for their existence and deleting them if they exist.Deactivation Before Deletion:
Improved Comments: