Christos Andreopoulos
Christos Andreopoulos

Reputation: 19

How to make Vim's :python3 command use a virtual environment?

My system has Vim preinstalled although I also installed it with homebrew. I noticed when I run the following command in Vim:

:py3 import sys; print(sys.executable)

it gives an output of /opt/homebrew/bin/vim.

Shouldn't it say python3 in the end?

When I run the command

:py3 import pandas as pd; print(pd.__version__)

it says no module named pandas.

This is even though I installed pandas on a virtual environment that was suggested by homebrew. I am also running the command from Vim inside that environment.

Upvotes: 1

Views: 103

Answers (3)

Friedrich
Friedrich

Reputation: 4846

As answered correctly by phd, using :python3 and related commands will use Vim's built-in Python interpreter. Most of the time, this is not what you want to use in the first place.

Vim's Python interface is for when you want to manipulate Vim's state using Python code. Vim offers a vim Python module for exactly this purpose. This is useful when writing Vim plugins in Python.

Unless you're writing a Vim plugin or import vim, there's hardly a reason for using :python3.
To write, run and debug Python scripts, you don't need Vim's Python interface. In fact, you dodge all your problems by using the Python interpreter of your (virtual) environment.

Use either of:

  • :w !python run the current buffer in Python, even without saving. See :help :write_c.
  • :'<,'>w !python run current Visual selection in Python.
  • :!python %:p run current file in Python (you will need to :write it beforehand). See :help :!.

More details in Executing Python with Gvim

Upvotes: 3

Christos Andreopoulos
Christos Andreopoulos

Reputation: 19

ok this worked (pasted in vimrc file):

if has("python3") py3 sys.path.insert(0, '/Users/user/coding/data_analysis/lib/python3.13/site-packages') endif 

Upvotes: -1

phd
phd

Reputation: 95101

Shouldnt it say python3 in the end?

No, vim is linked with libpython.so; i.e. Python is embedded into vim.

Command :py3 calls that embedded Python so to access libraries installed into a virtual environment that venv must be created with the same Python version and you should update sys.path to include that venv's site-packages directory.

Se my virtualenv.py and how I call it from .vimrc: py3file ~/.vim/python/virtualenv.py

Upvotes: 2

Related Questions