pythonvirtualenvpyenvpyenv-virtualenv

Enable pyenv-virtualenv prompt at terminal


I just installed pyenv and virtualenv following: https://realpython.com/intro-to-pyenv/

After completing installation I was prompted with:

pyenv-virtualenv: prompt changing will be removed from future release. configure `export PYENV_VIRTUALENV_DISABLE_PROMPT=1' to simulate the behavior

I added export PYENV_VIRTUALENV_DISABLE_PROMPT=1 to my .bash_aliases just to see what the behavior would be, and sure enough it removed the prompt that used to exist at the beginning of the command prompt indicating the pyenv-virtualenv version. Used to be like:

(myenv) user@foo:~/my_project [main] $

where (myenv) is the active environment, and [main] is the git branch.

I would love to have the environment indicator back! It is very useful. I guess at some possibilities such as:

export PYENV_VIRTUALENV_DISABLE_PROMPT=0

export PYENV_VIRTUALENV_ENABLE_PROMPT=1

But these do not return the previous behavior. I have googled all over and can't figure out how to get this back.

This answer is not useful, as it seems like a hack around the original functionality, and displays the environment always, not just when I enter (or manually activate) an environment.


Solution

  • Borrowing a solution from here, the following works (added to .bashrc or .bash_aliases):

    export PYENV_VIRTUALENV_DISABLE_PROMPT=1
    export BASE_PROMPT=$PS1
    function updatePrompt {
        if [[ "$(pyenv virtualenvs)" == *"* $(pyenv version-name) "* ]]; then
            export PS1='($(pyenv version-name)) '$BASE_PROMPT
        else
            export PS1=$BASE_PROMPT
        fi
    }
    export PROMPT_COMMAND='updatePrompt'