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.
: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.
: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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.