Same question as Use Vim with virtualenv, except for these differences:

  • I'm using bash, not zsh
  • using venv, not virtualenv or virtualenvwrapper

I have a keybinding to run the current buffer as a python script, but even if I've started vim with my virtual environment activated, the shell that it uses isn't in my venv, therefore it can't import any of the modules that I've pip-installed.

I have tried adding the following, one at a time, to /etc/profile, /etc/profile.d/vim.sh, ~/.bashrc, and ~/.bash_profile:

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

But even after closing and reopening my terminal, vim still starts a shell thinking that which python = /bin/python instead of the one in my venv. However, running :echo $VIRTUAL_ENV within vim does actually return the correct path to my venv, so at least I know can see the variable.

How can I get vim's non-interactive shell to use the parent shell's environment?

to answer D. Ben Knoble, these are the keybindings:

nnoremap <F5> :w<CR>:!clear;python %<CR>
inoremap <F5> <Esc>:w<CR>:!clear;python %<CR>

If I follow you correctly, I should call python like so?

:w<CR>:!clear;$VIRTUAL_ENV/bin/python %<CR>

This works as I try it now, but is it a reliable solution?

  • If you want to use bashrc it won't get processed by shell spawned from vim unless you set things up that way. Try using -i in vim's 'shell' setting: let &shell='/bin/bash -i'.
    – B Layer
    Sep 27 '19 at 14:51
  • 1
    Can you show the keybinding definition? If you run vim the with venv active, the path modification should be enough to use the right python/etc.
    – D. Ben Knoble
    Sep 27 '19 at 16:14

Your Answer

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

Browse other questions tagged or ask your own question.