Skip to content

Development environment with virtualenv

Rob Parrott edited this page Jun 11, 2014 · 11 revisions

Follow these steps (or pick and choose as you see fit) to setup your machine to develop Python applications in segregated environments by using "virtualenv".

Prerequisites

Uninstall any Python development stuff or modules you have installed globally. This is left as an exercise to the reader (hint: python setup.py develop --uninstall, pip uninstall, and rm are your friends)

Setup Python and Virtualenv with sane defaults

  • Install Python from a package manager (i.e. Homebrew) or use your system Python

  • Install pip for package management if you don't have it: easy_install pip (this and other Python install steps outside of the virtualenv may require root, depending on how your setup is configured.)

  • Use pip to install virtualenv and a helpful wrapper: pip install virtualenv virtualenvwrapper

  • Configure virtualenvwrapper:

    • Make a directory for your virtualenvs:
    mkdir ~/.virtualenvs
    
    • Update your .profile (or .bashrc or whatever) with defaults, setting PROJECT_HOME to be the place where you put your work files:

sh echo "export WORKON_HOME=$HOME/.virtualenvs" >> .profile echo "export PROJECT_HOME=$HOME/Projects" >> .profile echo "source which virtualenvwrapper.sh" >> .profile echo "export PIP_VIRTUALENV_BASE=$WORKON_HOME" >> .profile echo "export PIP_RESPECT_VIRTUALENV=true" >> .profile ```

* Source your updated .profile or open a new shell

Working on a project in virtualenv

  • Create a new project with virtualenv and virtualenvwrapper:

mkproject nepho


This command will will instantiate the env under `.virtualenvs`, create a project directory under `PROJECT_HOME`, and install pip and setuptools into the new environment.
* View a list of envs with `workon`, you can switch to an env by specifying its name.  This will also put you in the project directory:

workon nepho

* Clone in the nepho repository, then set it up for development (this will install necessary pip packages):
  ```
  git clone [email protected]:huit/nepho.git .
  python setup.py develop
  ```

* When you are done working on this project, you can run `deactivate` to deactivate the virtualenv, or `workon foo` to change to a different virtualenv.  All Python configuration and packages are contained within the environment, and will not affect other projects.

## Helpful hints
* Use the global virtualenv postactivate/postdeactivate hooks to print a message telling you that it worked:
  ```
  echo 'echo "virtualenv $(basename "VIRTUAL_ENV") activated"' >> ~/.virtualenvs/postactivate
  echo 'echo "virtualenv deactivated"' >> ~/.virtualenvs/postdeactivate
  ```

* __Optional:__ Install something fancy like [powerline](https://github.com/Lokaltog/powerline) to add the virtualenv information to your shell prompt (warning: this rabbit hole will destroy your productivity!)