How do I change the default virtualenv prompt?

bash, command-prompt, python, virtualenv, virtualenvwrapper

Solution

By default, when you switch into a virtualenv with the command "workon < name_of_env >", virtualenvwrapper prepends a string along the lines of "(< name_of_env >) " to your command prompt. The problem is that I set my Bash prompt with the lines:

PROMPT_COLOR1='0;36m'
PROMPT_COLOR2='1;34m'
PS1='\n\[\033[$PROMPT_COLOR1\](\t)\[\033[$PROMPT_COLOR2\] \u @ \w \n\[\033[$PROMPT_COLOR1\]$ \[\033[0;39m\]'

Which yields a command prompt along the lines of:

< old_line >

(19:11:05) kevin @ ~/research 
$ 

Switching into a new virtual environment with "workon < name_of_env >" turned the command prompt to something like:

< old_line >
(< name_of_env >)
(19:11:05) kevin @ ~/research 
$ 

Which was more cluttered than I wanted and the wrong color to boot. I was hoping for something like:

< old_line >

(< name_of_env >) (19:11:05) kevin @ ~/research 
$ 

Ian Bicking has previously pointed out that virtualenvwrapper's hooks were the solution but I figured I'd post my actual code to maybe save someone else a minute down the line.

I simply edited the file $WORKON_HOME/postactivate to include these lines:

# color virtualenv name properly and put it after the \n if there is one at the start of the prompt
if [ ${_OLD_VIRTUAL_PS1:0:2} == '\n' ]; then
    PS1="\n\[\033[$PROMPT_COLOR1\](`basename \"$VIRTUAL_ENV\"`) ${_OLD_VIRTUAL_PS1:2:${#_OLD_VIRTUAL_PS1}}"
else
    PS1="\[\033[$PROMPT_COLOR1\](`basename \"$VIRTUAL_ENV\"`) $_OLD_VIRTUAL_PS1 "
fi

and voila! The color and location are correct and it even works when you switch directly from one virtual environment to another (which I hadn't expected).

Problem

How do you change the default Virtualenvwrapper prompt? By default, working on a particular virtual environment with a command like `workon <_name_of_env_>` prepends the name of the virtualenv to your prompt. This may work poorly if you're not using a default command prompt.

Original source

Related problems