Skip to content

Instantly share code, notes, and snippets.

@uolot
Last active September 17, 2018 10:52
Show Gist options
  • Save uolot/fc2bca39845f363e35ca0d9fe8bf1ec9 to your computer and use it in GitHub Desktop.
Save uolot/fc2bca39845f363e35ca0d9fe8bf1ec9 to your computer and use it in GitHub Desktop.
Bash completion for pip install

Bash completion for pip install

Provides packages names completion in bash for pip install, pip download and pip search

Examples

$ pip install mat<TAB>
Display all 188 possibilities? (y or n)

$ pip install matp<TAB>
matphys                    matplotlib-helpers         matplotlib-subsets
matplotboard               matplotlib-hep             matplotlib-venn
matplotlib                 matplotlib_iterm2          matplotlib_venn_wordcloud
matplotlib2tikz            matplotlib-label-lines     matplotlylib
matplotlib-colorbar        matplotlib-scalebar        matplotsave

Requirements

  • bash
  • curl
  • pip
  • readline

Installation

Source complete.sh from your .bashrc or copy and paste its contents.

Disadvantages

  • keeps a cache of PyPI index (~2MiB) in your home dir (can be moved to /tmp easily)
  • partially breaks pip install options' completion - available only after package name (works normally for other subcommands)
  • not tested with shells other than bash
_update_pip_index() {
INDEX_AGE=$(stat -c %Y ~/.pip_index 2>/dev/null || echo 0)
NOW=$(date +%s)
DIFF_S=$(expr $NOW - $INDEX_AGE)
DIFF_H=$(expr $DIFF_S / 3600)
if [ $DIFF_H -gt 24 ]; then
curl --silent https://pypi.org/simple/ | grep href | sed 's/>/</g' | awk -F'<' '{print $3}' > ~/.pip_index
fi
}
_pip_completion()
{
if [[ $COMP_CWORD == 2 && "install download search" =~ ${COMP_WORDS[1]} ]]; then
_update_pip_index
curr_word="${COMP_WORDS[COMP_CWORD]}"
packages=$(grep $curr_word ~/.pip_index)
COMPREPLY=( $(compgen -W "${packages}" -- ${curr_word}) )
return 0
fi
COMPREPLY=( $( COMP_WORDS="${COMP_WORDS[*]}" \
COMP_CWORD=$COMP_CWORD \
PIP_AUTO_COMPLETE=1 $1 ) )
}
complete -o default -F _pip_completion pip
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment