'''See http://stackoverflow.com/a/5359988/120991 ''' from fabric.api import * from contextlib import contextmanager env.update( use_ssh_config=True, directory='/home/ubuntu/projects/thingy', activate='source /home/ubuntu/.virtualenvs/thingy/bin/activate', ) @contextmanager def virtualenv(): '''Context manager to activate virtualenv. ''' with cd(env.directory): with prefix(env.activate): yield def supervisor(command, process): with virtualenv(): run('supervisor restart something')