views:

80

answers:

3

I use vim for coding and for python coding in particular. Often I want to execute the current buffer with python interpreter. (for example to run unittests), usually I do this with :!python % <Enter>

This scenatio will work works fine with global python, but I want to run virtualenv python instead. How do I enable virtualenv within vim? Is it possible to switch virtualenv on the runtime?

I'm using macvim

A: 

Activate your virtualenv before starting vim. You will automatically get the corresponding interpreter instance.

sykora
I'm using MacVim, and I start it from the Dock, so it's not really a good option... As far as I understand activating the virtualenv is all about modifying the PATH, PYTHONHOME and PYTHONPATH env vars, maybe some other too. I dont mind to port the virtualenv's activate `script` to vim, I was just wondering if there is an existing solution.
ak
A: 

Here is a possibility:

  1. activate your environment (workon env)
  2. launch MacVim from that Terminal window using the command line (open -a MacVim)
Olivier
yeh, this is what sykora proposed, I will only note that it is better to open macvim with `open -a MacVim`. This way the application will be opened properly.
ak
Right, it is much better with `open -a`, I updated my post.
Olivier
+1  A: 

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.

dwf
wow, cool, this is what I was looking for, thanks a lot! I didn't know virtualenv creates this activate_this.py
ak