Skip to content

Instantly share code, notes, and snippets.

@rpalo
Forked from iley/venvwrapper.sh
Last active July 25, 2017 22:17
Show Gist options
  • Save rpalo/86cb98cc1c8bf0fd539ec1cf2c50d493 to your computer and use it in GitHub Desktop.
Save rpalo/86cb98cc1c8bf0fd539ec1cf2c50d493 to your computer and use it in GitHub Desktop.
Like virtualenvwrapper, but for venv, included with Python 3.4 and above!
if [ -z "$WORKON_HOME" ]; then
export WORKON_HOME="$HOME/.virtualenvs"
fi
workon () {
virtualenv="$1"
if [ -z "$virtualenv" ]; then
echo "Usage: workon env_name" >&2
return 1
fi
if ! [ -e "$WORKON_HOME/$virtualenv" ]; then
echo "Virtualenv '$virtualenv' does not exist" >&2
return 1
fi
if [ -n "$VIRTUAL_ENV" ]; then
deactivate
fi
. "$WORKON_HOME/$virtualenv/bin/activate"
proj_dir_file="$WORKON_HOME/$virtualenv/.project_dir"
if [ -e "$proj_dir_file" ]; then
cd < "$proj_dir_file"
fi
}
mkvenv () {
name="$1"
shift
if [ -z "$name" ]; then
echo "Usage: mkvenv name [args]" >&2
return 1
fi
env_path="$WORKON_HOME/$name"
if [ -e "$env_path" ]; then
echo "virtualenv '$env_path' already exists" >&2
return 1
fi
mkdir -p "$env_path"
python3 -m venv $* "$env_path"
}
rmvenv () {
name="$1"
if [ -z "$name" ]; then
echo "Usage: rmvenv name" >&2
return 1
fi
env_path="$WORKON_HOME/$name"
if [ ! -e "$env_path" ]; then
echo "virtualenv '$env_path' does not exists" >&2
return 1
fi
read -q "REPLY?Delete virtualenv '$env_path'? [y/N] " -c -n 1
echo
if [[ "$REPLY" =~ ^[Yy]$ ]]; then
rm -rf "$env_path"
else
echo "action aborted" >&2
return 1
fi
}
setvenvproject () {
if [ -z "$VIRTUAL_ENV" ]; then
echo "No active virtualenv" >&2
return 1
fi
current_dir=`pwd`
echo "$current_dir" > "$WORKON_HOME/$VIRTUAL_ENV/.project_dir"
echo "Setting project for $VIRTUAL_ENV to $current_dir"
}
clearvenvproject () {
if [ -z "$VIRTUAL_ENV" ]; then
echo "No active virtualenv" >&2
return 1
fi
proj_dir_name="$WORKON_HOME/$VIRTUAL_ENV/.project_dir"
previous_project=`cat $proj_dir_name`
rm -f "$WORKON_HOME/$VIRTUAL_ENV/.project_dir"
echo "Unsetting $previous_project as the project for $VIRTUAL_ENV"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment