J.Neue J.Neue - 1 month ago 10
Python Question

How to create a mapping to execute python code from Vim?

Here's the steps I follow to execute python code from Vim:


  1. I write a python source code using Vim

  2. I execute it via
    :w !python



and I'd like a shorter way to execute the code, so I searched the Internet for a shortcut key such as this map:

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


and added it to the
_vimrc
file. But when I hit F9, the following error message appears:

enter image description here

Here is the relevant text in the image above:

python: can't open file ''D:/py2.py'': [Errno 22] Invalid argument
shell returned 2.


I have already searched the Internet, but I have not got any result.

I use gVim 8.0 in Windows 10, if that helps.

Answer

Interacting with command-line through vim, the much preferred way would be with exclamation.
Instead of:

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

Try doing the easy way:

:update<bar>!python %<CR>

here in the above code:
update helps save file if modified (preferred) or can also use w.
<bar> will pipe the commands properly.
!python % will run the file as python filename.

So basically, put this in your .vimrc file, and that'll do it:

autocmd FileType python nnoremap <buffer> <F9> :update<bar>!python %<CR>