In Part 1 we saw how to use virtualenv.

Now let’s see how to colorize the bash prompt and how to activate a virtual environment easily.

Colorize the prompt

When a virtual env. is activated, the prompt changes. However, this change is not very visible because it’s not colorized. The name of the virtual env. should be printed with a different color, thus it would be visible immediately if an env. is activated or not.

Fortunately someone else also had this problem :) Here I found an excellent solution. I only changed the PS1 line the following way:

PS1="${PYTHON_VIRTUALENV}${GREEN}\u@\h ${YELLOW}\w${COLOR_NONE} ${BRANCH}${PROMPT_SYMBOL} "

This way the prompt and the cursor are in one line. I made a fork, my slightly modified version is available here.

Update (20131001): I updated the script above to support light background too. Instructions are in the header in a comment.

Usage

Save the file above as ~/.bash_prompt and add the following line to the end of your ~/.bashrc :

source ~/.bash_prompt

The resulting prompt is way cooler than the default bash prompt, thus you can use it even if you don’t work with virtual environments!

See the end of the post for a screenshot.

Activating a virtual environment easily

The standard way for activating a virtual env. is to source the script “ activate “:

jabba@jabba-uplink ~/python/mystuff $ ls -al total 24 drwxrwxr-x 3 jabba jabba 4096 Sep 21 16:16 . drwxrwxr-x 234 jabba jabba 12288 Sep 21 15:58 .. -rwxrw-r-- 1 jabba jabba 53 Sep 21 16:16 hello.py drwxrwxr-x 6 jabba jabba 4096 Sep 21 16:13 venv jabba@jabba-uplink ~/python/mystuff $ . venv/bin/activate [venv] jabba@jabba-uplink ~/python/mystuff $

However, using the command “ workon venv ” would be much easier. I wanted to do it with an alias, but bash aliases do not accept arguments. There is a workaround: use functions instead.

Add the following lines to your ~/.bashrc :

func_workon() { if [[ -z "$1" ]] then echo "Usage: workon <venv>" else . $1/bin/activate fi } alias workon=func_workon alias workoff='deactivate'

Now you can activate a virtual env. much easier:

jabba@jabba-uplink ~/python/mystuff $ ls -al total 24 drwxrwxr-x 3 jabba jabba 4096 Sep 21 16:16 . drwxrwxr-x 234 jabba jabba 12288 Sep 21 15:58 .. -rwxrw-r-- 1 jabba jabba 53 Sep 21 16:16 hello.py drwxrwxr-x 6 jabba jabba 4096 Sep 21 16:13 venv jabba@jabba-uplink ~/python/mystuff $ workon venv [venv] jabba@jabba-uplink ~/python/mystuff $

For deactivation use the command “ deactivate “, or my alias “ workoff “.

Screenshot



Next step

There is virtualenvwrapper, which is “a set of extensions to Ian Bicking’s virtualenv tool. The extensions include wrappers for creating and deleting virtual environments and otherwise managing your development workflow, making it easier to work on more than one project at a time without introducing conflicts in their dependencies.”

I haven’t used it yet.