Set python virtualenv in vim

Viewed 21592

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

6 Answers

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.

If for some reasons you do not want to run vim inside a python virtual environment, then instead of sourcing venv/bin/activate, you can:

PYTHONPATH="$(source venv/bin/activate; python3 -c "import sys; print(':'.join(sys.path))"; deactivate)" vim

which also kinda source the virtual environment, but it keeps it somewhat separate from the environment in which vim is run.

Related