Skip to content

Instantly share code, notes, and snippets.

@pkienzle
Last active October 24, 2022 20:20
Show Gist options
  • Save pkienzle/4c1e750f6d0e9470dd46566c0fdcd38e to your computer and use it in GitHub Desktop.
Save pkienzle/4c1e750f6d0e9470dd46566c0fdcd38e to your computer and use it in GitHub Desktop.
Very simple python virtual environment management for bash/dash/zsh
# Source this into your ~/.bashrc or ~/.zshrc to add a simple "venv" command for
# creating/activating python environments.
# venv
# Show available environments.
# venv name
# Activates the environment in ~/.venv/name
# venv -n[3.x] name [packages...]
# Creates an environment using python 3.x (default 3.8).
# rm -r ~/.venv/name
# Removes an existing environment.
# apt install python3.x-venv
# Makes version 3.x available for new environments.
# Config variables
_venv_default_version=3.8
_venv_root="$HOME/.venv"
_venv_activate() {
# To activate an environment first deactivate any existing environment
# before sourcing $_venv_root/$name/bin/activate. Need to use source since we
# are updating environment variables. Do nothing if the target environment
# doesn't exist or if it is already active.
# Note: local variables available in bash, dash, zsh but not ksh
local target
target="$_venv_root/$1"
if test -d "$target"; then
if test -n "$VIRTUAL_ENV"; then
test "$VIRTUAL_ENV" = "$target" && { echo "$target is already active"; return 1; }
echo "deactivating $VIRTUAL_ENV"
deactivate
fi
echo "activating python environment $1 in $_venv_root"
source "$target/bin/activate"
else
echo "environment $1 does not exist; use venv -n $1 to create it"
return 1
fi
}
venv () {
# Note: local variables available in bash, dash, zsh but not ksh
local target name version
# If no environment specified then list available environments.
test -z $1 && { echo "usage: venv [-n{3.x}] envname [packages...]"; (cd "$_venv_root" && ls); return 1; }
# Check if first argument starts with "-n"
if test "${1#-n}" != "${1}"; then
# If version is provided as -n3.x then use 3.x otherwise use default version
version=${1#-n}; version=${version:-$_venv_default_version}
shift 1
# Check that we don't have an existing environment.
test -z "$1" && { echo "environment name is missing"; return 1; }
name=$1
target="$_venv_root/$name"
shift 1
test -d "$target" && { echo "$target already exists"; return 1; }
# Create and activate the new environment
mkdir -p "$_venv_root"
python$version -m venv "$target"
_venv_activate "$name"
# Install the requested packages.
echo "updating pip in the new environment"
pip install --upgrade pip
test $# -gt 0 && pip install "$@"
else
_venv_activate "$1"
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment