Assumptions:
— The system is running Mac OSX
— You have installed Python using homebrew
— You have “pip” installed. (Try “easy_install pip” if not installed)
Install Virtualenvwrapper:
virtualenvwrapper 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.
It’s cooler in the sense that the virtualenvs are generated in a seperate directory than the project directory. It’s an excellent improvement over virtualenv tool. It also provides some handy commands to generate, remove and switch environments.
Install it with this command:
1 |
pip install virtualenvwrapper |
After it is installed, we should create the dedicated directory for the virtualenvs:
1 |
mkdir ~/.virtualenvs |
Now add these lines to your bash profile (~/.bash_profile):
1 2 3 4 5 6 |
## virtualenvwrapper configs export WORKON_HOME=$HOME/.virtualenvs export PIP_VIRTUALENV_BASE=$WORKON_HOME export PIP_RESPECT_VIRTUALENV=true #virtualenv shell script source /usr/local/share/python/virtualenvwrapper.sh |
Creating an environment:
1 |
mkvirtualenv PROJECT_NAME |
Removing an environment:
1 |
rmvirtualenv PROJECT_NAME |
Switching to an environment:
Use the workon command:
1 2 3 4 5 |
# List all environments workon # Switch to environment named "env1" workon env1 |
Using hooks:
You can use predefined scripts to customize the behavior when an environment is activated. For example, to change directory to “~/codes/test” when “test” environment is activated, we shall edit add this line to $VIRTUAL_ENV/test/postactivate:
1 |
cd ~/codes/test |
Similarly, we can use the postdeactivate script to define a behavior when the script is deactivated.
Using pip:
While using pip, you can use an extra argument to define which environment you want the package to be installed:
1 |
pip install -E ENVIRONMENT_NAME PACKAGE |
Cool, eh?
One reply on “Mac OSX, homebrew & Python: Creating Virtual Environments”
Have you looked at vagrant and using it with provisioning tools like puppet / chef?