How to display the name of the current Virtualenv?
Shell's prompt
Inside your virtualenv
environment is a file, bin/activate
. You can edit this file to change your prompt to whatever you want it to look like. Specifically this section of the file:
...
else
PS1="(`basename \"$VIRTUAL_ENV\"`)$PS1"
fi
...
The variable PS1
is a special variable that controls what a shell's prompt will look like. Changing its value will change your virtualenv
prompt:
PS1="(this is my prompt) "
Example
Create a sample environment.
$ virtualenv tst-env
When you're using
virtualenv
you typically source this file.$ cd $HOME/tst-env $ source bin/activate (tst-env)[saml@grinchy tst-env]$
After making the above change to the variable
PS1
in thebin/activate
file my prompt is now this:$ source bin/activate (tst-env)
Here are the official instructions on how to do this.
If you're using virtualenvwrapper
and zsh
there are a number of zsh hooks in your ~/.virtualenvs/
directory that you can use to customize your environments. Here is a bit of info regarding these. You can force an update to PS1
that will prepend the current working virtualenv
to your shell prompt by adding:
_OLD_VIRTUAL_PS1=$PS1
PS1="(`basename \"$VIRTUAL_ENV\"`) $PS1"
builtin \export PS1
to ~/.virtualenvs/postactivate
. To remove the tag when you deactivate
, add:
PS1=$_OLD_VIRTUAL_PS1
builtin export PS1
to ~/.virtualenvs/postdeactivate
The only (plausible) thing that should break this is resourcing ~/.zshrc
while working in a virtualenv
You don't have to edit your ~/.zshrc
.
Since you are working with virtualenvwrapper
it's possible to add options or hooks to $WORKON_HOME/post(de)activate
files.
If you want to see more details consult here.
The above link allow me to do next:
In my case $WORKON_HOME=~/Envs
because I modified this path when I installed virtualenvwrapper; if you didn't you should have the folder ~/.virtualenvs
.
Open the file
postactivate
located in$WORKON_HOME
Add these lines:
PS1="$_OLD_VIRTUAL_PS1" _OLD_RPROMPT="$RPROMPT" RPROMPT="%{${fg_bold[white]}%}(env: %{${fg[green]}%}`basename \"$VIRTUAL_ENV\"`%{${fg_bold[white]}%})%{${reset_color}%} $RPROMPT"
Save and enjoy!
You will obtain something like this:
(OPTIONAL) If you want you could edit the
postdeactivate
file to add this line:RPROMPT="$_OLD_RPROMPT"