Wednesday 23 May 2012

Virtualenvwrapper & Coloured Bash Prompts

During VIM Quest I’ve fostered a much closer relationship with the terminal. With the exception of the web browser the terminal (actually it’s iterm2 if I’m being specific) is now my main development environment and because of this colour is super important. I have a customised bash prompt that looks like this –

custom bash prompt

The above is made possible by setting my own value for $PS1 in my ~/.bash_login. PS1 is the name of the environment variable that controls this “stuff” (am I showing my limited knowledge of bash here?).

 export PS1="\[\033[01;33m\]\W\[\033[00m\] \$ " 

The problem is that whenever you activate a virtualenv, virtualenvwrapper sets a new value for PS1. This isn’t a bad thing because the value that it sets displays the current virtualenv that you’re working on inside of the parenthesis –

virtualenvwrappers resulting PS1

Whilst this is very helpful, the lack of colour irks me. Fortunately virtualenvwrapper comes with a rather nice suite of hooks that can be used to customise everything about the experience of using virtualenv. There are global hooks and hooks that are specific to each virtualenv and it’s the global hooks that I’ve used to create a solution to the problem of a non–coloured prompt after activating a virtualenv.

Inside of the directory specified by $WORKON_HOME there are a number of files, the one that I’ve added code to is the “postactivate” file. The file contains the following default content –

 #!/bin/bash # This hook is ran after each virtualenv is activated 

By adding the following to the file, I now get my coloured prompt back and I get the info about what virtualenv I’m working on.

 export PS1="\[\033[01;44m\](`basename $VIRTUAL_ENV`)\[\033[00m\]\[\033[01;33m\] \W\[\033[00m\] \$ " 

The resulting code looks like this where the text in the blue background is the virtualenv I’m in and the yellow text is the current working directory (cwd) without the full path.

My custom post virtualenv activated prompt

If you want to experiment with the colours, then you can use this explanation of bash colours as a starting point.