virtualenv, virtualenvwrapper, and TextMate

by Rob McBroom

Since discovering virtualenvwrapper, I now want to use a separate environment for almost everything. I set one up to go through a Pyramid tutorial and thought it would be nice if TextMate (2 alpha) could run the copy of Python from the isolated environment when I hit ⌘R in application.py, and as a bonus, let me know about this by displaying the name of the environment in the title bar. This turns out to be pretty easy.

First, make sure TextMate knows about your WORKON_HOME variable somehow. There are a couple of ways to do this, but I just set it up in the application's preferences under "Variables".

Next, put this in $WORKON_HOME/postmkproject:

1
2
3
4
5
6
7
8
#!/bin/zsh
# This hook is run after a new project is activated.
export VIRTUAL_ENV_SHORT=`basename "$VIRTUAL_ENV"`
export TMPROPERTIES=$PROJECT_HOME/$VIRTUAL_ENV_SHORT/.tm_properties
echo "Configuring TextMate to use this virtualenv for this project"
echo "TM_PYTHON = \"\$WORKON_HOME/$VIRTUAL_ENV_SHORT/bin/python\"" >> $TMPROPERTIES
echo "[ *.py ]" >> $TMPROPERTIES
echo "windowTitle = \"\$TM_DISPLAYNAME ($VIRTUAL_ENV_SHORT)\"" >> $TMPROPERTIES

Now, when you create a project, its .tm_properties file should be set up automatically.

% mkproject pyramid_humans
New python executable in pyramid_humans/bin/python
Installing setuptools............done.
Installing pip...............done.
virtualenvwrapper.user_scripts creating /Users/rob/.virtualenvs/pyramid_humans/bin/predeactivate
virtualenvwrapper.user_scripts creating /Users/rob/.virtualenvs/pyramid_humans/bin/postdeactivate
virtualenvwrapper.user_scripts creating /Users/rob/.virtualenvs/pyramid_humans/bin/preactivate
virtualenvwrapper.user_scripts creating /Users/rob/.virtualenvs/pyramid_humans/bin/postactivate
virtualenvwrapper.user_scripts creating /Users/rob/.virtualenvs/pyramid_humans/bin/get_env_details
Creating /Users/rob/Coding/Python/pyramid_humans
Setting project for pyramid_humans to /Users/rob/Coding/Python/pyramid_humans
Configuring TextMate to use this virtualenv for this project

% cat .tm_properties
TM_PYTHON = "$WORKON_HOME/pyramid_humans/bin/python"
[ *.py ]
windowTitle = "$TM_DISPLAYNAME (pyramid_humans)"

The obvious drawback is that this happens for every project, whether you plan to use it with TextMate or not, but it's a very small, hidden file and I don't expect to have many projects like that anyway.

The proper way to impliment this is probably as a virtualenvwrapper template. That would allow you to get this only when you wanted it by running something like mkproject -t textmate pyramid_humans, but I haven't figured out how to create a template. It seems insanely complicated for something this small.

blog comments powered by Disqus