Max
Max

Reputation: 2162

Show pipenv virtualenv in PS1

Pipenv is a relatively new packaging tool that encompasses "Pipfile, Pip, and Virtualenv". I have made changes to simplify my PS1 in .bashrc but now find that I need my PS1 to tell me when I am using my virtualenv.

Current PS1:

PS1='\w $ '

From the below, you can see my prompt script does nothing to tell me about whether I'm using a virtual environment:

~ $ cd workspace/myproject/
~/workspace/myproject $ pipenv shell
Launching subshell in virtual environment. Type 'exit' or 'Ctrl+D' to return.
~/workspace/marcus_project $ 

I too often screw up my PS1 and was hoping for a simple fix to have the prompt in the virtualenv show up like so: (my-env) ~ $.

Upvotes: 3

Views: 3051

Answers (2)

Guillermo Aguirre
Guillermo Aguirre

Reputation: 841

If you have virtualenv installed this behaviour come out of the box in pipenv. What I did have some trouble with was that the pipenv shell messed up my custom PS1 I had defined. I'm answering here because when googling, this was the question that resembled my problem the most.

To fix this I had to go to vim ~/.virtualenvs/<name of the env>/bin/activate. Here I changed the code where it defines the PS1 for the one I had in my bash_profile. The PS1 pipenv shell is now using the PS1 inside the if [ "x(data-load) " != x ] ; then statement.

I'm sure this can be achieved in a better way instead of redefining the PS1 in the file, and using the one in .bash_profile but didn't want to waste more time with this.

...

if [ -z "${VIRTUAL_ENV_DISABLE_PROMPT-}" ] ; then
    # add this line to get original PS1 prompt
    PS1=ORIGINAL PS1 in .bash_profile
    if [ "x(data-load) " != x ] ; then
        # here add the name of the virtual env, and some color if in the mood
        PS1="\[\033[39m\](myenv) ${PS1-}"
    else
        PS1="(`basename \"$VIRTUAL_ENV\"`) ${PS1-}"
    fi
    export PS1
fi

...

Upvotes: 3

cxw
cxw

Reputation: 17051

Per the docs, create a file called .env in your project. Give it the contents

export PS1='(myenv) \w $ '

or whatever you want. pipenv shell will load it.

(Note: I haven't tried pipenv myself. Today I learned it exists! :) )

Take 2

If your .bashrc or .profile (or other startup files) set PS1, you can hack it.

  • Put export PIPENV_PS1='(myenv) \w $ ' in your .env. (The name PIPENV_PS1 isn't anything special — I just picked something I thought made sense.)
  • At the end of your .bashrc, add:

    if [[ $PIPENV_PS1 ]]; then
        export PS1="$PIPENV_PS1"
    fi
    

That way your .bashrc will copy the value you have set in .env.

Upvotes: 5

Related Questions