3

I use to map F9 to :pyf % to run python files from vim. But after reading this answer, which suggests

nnoremap <buffer> <F9> :exec '!python' shellescape(@%, 1)<cr>

Just wondering which approach should be preferred for running python code from vim session.

dlmeetei
  • 9,905
  • 3
  • 31
  • 38

2 Answers2

5

:pyfile is a variant of :python (that reads the code from a file, not as direct arguments). Both execute the code inside Vim's embedded Python interpreter. This is mostly meant for Vim plugins written in Python. You have access to Vim's Python interface (cp. :help python-vim), and any code / globals will persist until you quit Vim.

For trivial code without side effects, this should be fine, although it's not meant for that.


:!python ... launches an external Python interpreter, completely separate from Vim. Vim doesn't even need to be compiled with Python support here. As each invocation is a separate process, there's no persistence between runs. Each one is fresh, just like launching the script directly from the command-line. Also, you're using the system's default Python interpreter, not the one Vim was compiled against.

I would recommend this approach, unless you're explicitly writing a Vim plugin.

Ingo Karkat
  • 167,457
  • 16
  • 250
  • 324
3

:pythonfile executes the file with Python built-in into vim so the script can import module vim.

!python executes external interpreter that doesn't have any access to vim internals.

phd
  • 82,685
  • 13
  • 120
  • 165