Set python virtualenv in vim
Here's what I use (sorry the highlighting is screwy).
" Function to activate a virtualenv in the embedded interpreter for
" omnicomplete and other things like that.
function LoadVirtualEnv(path)
let activate_this = a:path . '/bin/activate_this.py'
if getftype(a:path) == "dir" && filereadable(activate_this)
python << EOF
import vim
activate_this = vim.eval('l:activate_this')
execfile(activate_this, dict(__file__=activate_this))
EOF
endif
endfunction
" Load up a 'stable' virtualenv if one exists in ~/.virtualenv
let defaultvirtualenv = $HOME . "/.virtualenvs/stable"
" Only attempt to load this virtualenv if the defaultvirtualenv
" actually exists, and we aren't running with a virtualenv active.
if has("python")
if empty($VIRTUAL_ENV) && getftype(defaultvirtualenv) == "dir"
call LoadVirtualEnv(defaultvirtualenv)
endif
endif
Note that you need to have MacVim compiled against the Python you are using for the virtualenv, e.g. if you downloaded Python 2.7 from Python.org you should recompile MacVim using --with-python-config-dir=/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/config
as an argument to ./configure
.
Hope that helps!
EDIT: Just one note of attribution: A lot of the detective work that went into writing this little ditty was done by this blogger, and he deserves some of the credit.
Activate your virtualenv before starting vim. You will automatically get the corresponding interpreter instance.
There is also a vim plugin on github:
https://github.com/jmcantrell/vim-virtualenv
I have not tried it, but it seems to solve the question as well.
You can create a function with an alias for vim to auto load/unload the virtualenv if it exists at the location from which you start it.
In this example, it checks for the virtualenv in .venv/bin/activate
.
vimVenAutoload() {
if [ -e .venv/bin/activate ]; then
. .venv/bin/activate;
vim $*;
deactivate;
else
vim $*;
fi;
}
alias vim="vimVenAutoload"
You can add this to your .bashrc
or .bash_profile
.
Small caveat: If a virtualenv is already loaded, it will be overwritten with the new one.