Automatically activating workingenv.py environments on directory change

workingenv.py is a very useful tool for Python development. Quoting from its home page:

This tool creates an environment that is isolated from the rest of the Python installation, eliminating site-packages and any other source of modules, so that only the modules (and versions) you install into the environment will be available. This allows for isolated and controlled environments, as well as reproduceability.

To create, activate and deactivate an environment:

$ workingenv foo
$ . foo/bin/activate
(foo)$ deactivate
$

This is great, but what's even more so is using On Dir with it.

I need to work on multiple versions of Trac (stable, trunk, branches, etc.) at the same time, I have each version in its own directory beneath ~/projects/trac. Each Trac instance is completely self contained, so installing plugins in one will not affect the others.

So I use the following On Dir config to activate the workingenvs as I cd into each Trac directory.

enter ~/projects/trac/([^/]*)
    declare -F deactivate > /dev/null && deactivate
    activate=../env/$1/bin/activate
    test -r $activate && . $activate

leave ~/projects/trac
    declare -F deactivate > /dev/null && deactivate

Here's an example of me switching between environments. The last environment remains active until I leave the main Trac directory.

[aat@stalactite:~]cd projects/trac/trunk
(trunk)[aat@stalactite:~/projects/trac/trunk]cd ..
(trunk)[aat@stalactite:~/projects/trac]workingenv --site-packages ../env/stable
Updating working environment in /home/aat/projects/trac/env/stable
Installing local setuptools.................done.
(trunk)[aat@stalactite:~/projects/trac]cd stable/
(stable)[aat@stalactite:~/projects/trac/stable]cd ..
(stable)[aat@stalactite:~/projects/trac]cd trunk
(trunk)[aat@stalactite:~/projects/trac/trunk]cd ../..
[aat@stalactite:~/projects]

Of course, this can be extended to any project that needs its own independent Python environment, not just Trac.