Skip to content

Instantly share code, notes, and snippets.

@matthewfeickert
Created February 1, 2019 21:51
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matthewfeickert/06a7cf436821380c7dc93f569c3821f5 to your computer and use it in GitHub Desktop.
Save matthewfeickert/06a7cf436821380c7dc93f569c3821f5 to your computer and use it in GitHub Desktop.
Bash tab completion of activation of Python virtual environments (that are installed under `$HOME/venvs`)

Bash tab completion of activation of Python virtual environments

If _venv-activate.sh is installed at /opt/_venv-activate/_venv-activate.sh then if the following is added to a user's ~/.bashrc

# Enable tab completion of Python virtual environments
if [ -f /opt/_venv-activate/_venv-activate.sh ]; then
    . /opt/_venv-activate/_venv-activate.sh
fi

then a user can tab complete for possible Python virtual environments to activate with venv-activate if the virtual environments are installed under $HOME/venvs/

Example

$ mkdir -p $HOME/venvs
$ cd $HOME/venvs
$ python3 -m venv data-science
$ cd
$ venv-activate #tab

results in

$ venv-activate
data-science

and tab completing data-science and hitting enter then activates the virtual environment

(data-science) $
#!/usr/bin/env bash
_venv-activate()
{
local cur prev opts
COMPREPLY=()
cur="${COMP_WORDS[COMP_CWORD]}"
prev="${COMP_WORDS[COMP_CWORD-1]}"
opts="$(echo $($(which ls) -1 ${HOME}/venvs/ | sed 's/^//'))"
if [[ ${cur} == * ]] ; then
COMPREPLY=($(compgen -W "${opts}" $cur))
return 0
fi
}
function venv-activate() {
function display_venvs {
$(which ls) -1 ${HOME}/venvs/ | sed 's/^/* /'
}
if [[ -z "$1" ]]; then
printf "\nEnter a virtual environment:\n"
display_venvs
elif [[ -d "${HOME}/venvs/$1" ]]; then
source "${HOME}/venvs/$1/bin/activate"
return 0
else
printf "\n$1 is not a valid virtual environment."
printf "\nSelect from one of:\n"
display_venvs
fi
return 1
}
complete -F _venv-activate venv-activate
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment