TroyGrosfield.com TroyGrosfield.com

Headline

Python virtualenv and virtualenvwrapper Cheat Sheet

Author
by Troy Grosfield
Date
April 20th, 2013
Category
Developer
Story

Commands for working with virtualenv and virtualenvwrapper.

Installation

Assuming you already have pip installed:

$ sudo pip install -U virtualenv

Install virtualenvwrapper

$ sudo pip install -U virtualenvwrapper

Create virtualenv

$ mkvirtualenv <env_name>

$ mkvirtualenv my_env

Create Virtualenv with a different python

My current system python is version 2.7.2.  I want my virtualenv to use the latest version of 2.7.x python:

$ which python2.7
/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7
$ mkvirtualenv my_env -p /Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7
Running virtualenv with interpreter /Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7
New python executable in my_env/bin/python
Installing setuptools............done.
Installing pip...............done.

Scripts

These scripts go in the root directory of your virtual environment.  In my case it was:

/Users/<my_user_name>/.virtualenvs

postactivate

This command is run every time you activate a virtual environment.  It will change your current working directory to the src folders of the virtual env you’re wanting to work on:

#!/bin/zsh
# This hook is run after every virtualenv is activated.
if [ !$_WS_ORIG_DIR ]
then
  export _WS_ORIG_DIR="$PWD"
fi

mkdir -p "$VIRTUAL_ENV/src"
cd "$VIRTUAL_ENV/src"

postdeactivate

This command is run every time you deactivate a virtual environment. It will change your current working directory to the directory you were working in before you switched into the virtual environment:

#!/bin/zsh
# This hook is run after every virtualenv is deactivated.

if [ !$_WS_ORIG_DIR ]
then
  cd $_WS_ORIG_DIR
  unset _WS_ORIG_DIR
fi
Tags
Comments
No Comments »

No Comments Yet

Leave a reply