4

I do a lot of Python and I use almost all the time a virtualenv along with virtualenvwrapper to keep my modules organised.

But when I want to use those plugin from inside vim, through an external command, it seems that the shell is not aware of that config.

I need to have access to the virtualenv because

e.g.

(venv) $ python
>> import simple_history
>> # OK here

(venv) $ vim
:!python 
>> import simple_history
ImportError: No module named simple_history

My shell is shell=/bin/zsh, I guess I need to use this setting to access my virtualenv, but I can't figure out how...

10

I actually fixed this myself a long time ago. The problem is that when you run !python you're starting up a new shell with your existing environment. But, this means workon xxxx wasn't called to actually activate the virtualenv. This lead to a lot of confusion for me since $VIRTUAL_ENV was set.

I got around it by adding the following to my ~/.zshenv script:

if [[ -n $VIRTUAL_ENV && -e "${VIRTUAL_ENV}/bin/activate" ]]; then
  source "${VIRTUAL_ENV}/bin/activate"
fi

Since ~/.zshenv is sourced within the current session, it's a pretty safe assumption that the $VIRTUAL_ENV wasn't activated. Now when you run !python in Vim, it should use the virtualenv interpreter. You can confirm this by running :echo system('which python').

  • Oh this is nice, maybe it's not the place to ask the question, but why should your snippet be in .zshenv instead of .zshrc? – nobe4 May 6 '16 at 6:17
  • 1
    @Nobe4 Because .zshrc is not always sourced, while .zshenv is guaranteed to be sourced. – Sato Katsura May 6 '16 at 7:52
  • Here is further information about the load order of zsh scripts: zsh.sourceforge.net/Intro/intro_3.html – Tommy A May 6 '16 at 13:36
  • 1
    I updated the answer because $ZSHENV_PATH_SET is irrelevant to solving the OP's problem. Adding the check for $VIRTUAL_ENV in that block was the result of late night troubleshooting. – Tommy A May 6 '16 at 13:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.