Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Show current pyenv python version in bash prompt, and also color virtual envs differently
####
#### pyenv-virtualenv bash prompt customization
####
# pyenv
eval "$(pyenv init -)"
# pyenv-virtualenv:
eval "$(pyenv virtualenv-init -)"
export PYENV_VIRTUALENV_DISABLE_PROMPT=1
pyenvVirtualenvUpdatePrompt() {
RED='\[\e[0;31m\]'
GREEN='\[\e[0;32m\]'
BLUE='\[\e[0;34m\]'
RESET='\[\e[0m\]'
[ -z "$PYENV_VIRTUALENV_ORIGINAL_PS1" ] && export PYENV_VIRTUALENV_ORIGINAL_PS1="$PS1"
[ -z "$PYENV_VIRTUALENV_GLOBAL_NAME" ] && export PYENV_VIRTUALENV_GLOBAL_NAME="$(pyenv global)"
VENV_NAME="$(pyenv version-name)"
VENV_NAME="${VENV_NAME##*/}"
GLOBAL_NAME="$PYENV_VIRTUALENV_GLOBAL_NAME"
# non-global versions:
COLOR="$BLUE"
# global version:
[ "$VENV_NAME" == "$GLOBAL_NAME" ] && COLOR="$RED"
# virtual envs:
[ "${VIRTUAL_ENV##*/}" == "$VENV_NAME" ] && COLOR="$GREEN"
if [ -z "$COLOR" ]; then
PS1="$PYENV_VIRTUALENV_ORIGINAL_PS1"
else
PS1="($COLOR${VENV_NAME}$RESET)$PYENV_VIRTUALENV_ORIGINAL_PS1"
fi
export PS1
}
export PROMPT_COMMAND="$PROMPT_COMMAND pyenvVirtualenvUpdatePrompt;"
## Recommanded pyenv setup:
## run this once, don't put it in .bash_profile (or similar) files!
# $ pyenv global system
# $ cd $HOME
# $ pyenv local 2.7.11 # or which ever version you like having as default
@itsthejoker

This comment has been minimized.

Copy link

@itsthejoker itsthejoker commented Jan 30, 2017

Thank you so much for this. I held on as long as I could until they finally killed the feature officially, but I spend so much time bouncing between environments that this is essential. I really appreciate it!

@wenbochang

This comment has been minimized.

Copy link

@wenbochang wenbochang commented Dec 21, 2018

thanks sir!

@JamesHh666

This comment has been minimized.

Copy link

@JamesHh666 JamesHh666 commented Dec 9, 2019

thank you so much!

@changchichung

This comment has been minimized.

Copy link

@changchichung changchichung commented Mar 24, 2021

may I ask how to update this script to do not modify prompt when using the system python??

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment